/******/ (function(modules) { // webpackBootstrap
/******/ 	// The module cache
/******/ 	var installedModules = {};
/******/
/******/ 	// The require function
/******/ 	function __webpack_require__(moduleId) {
/******/
/******/ 		// Check if module is in cache
/******/ 		if(installedModules[moduleId]) {
/******/ 			return installedModules[moduleId].exports;
/******/ 		}
/******/ 		// Create a new module (and put it into the cache)
/******/ 		var module = installedModules[moduleId] = {
/******/ 			i: moduleId,
/******/ 			l: false,
/******/ 			exports: {}
/******/ 		};
/******/
/******/ 		// Execute the module function
/******/ 		modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ 		// Flag the module as loaded
/******/ 		module.l = true;
/******/
/******/ 		// Return the exports of the module
/******/ 		return module.exports;
/******/ 	}
/******/
/******/
/******/ 	// expose the modules object (__webpack_modules__)
/******/ 	__webpack_require__.m = modules;
/******/
/******/ 	// expose the module cache
/******/ 	__webpack_require__.c = installedModules;
/******/
/******/ 	// define getter function for harmony exports
/******/ 	__webpack_require__.d = function(exports, name, getter) {
/******/ 		if(!__webpack_require__.o(exports, name)) {
/******/ 			Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ 		}
/******/ 	};
/******/
/******/ 	// define __esModule on exports
/******/ 	__webpack_require__.r = function(exports) {
/******/ 		if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ 			Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ 		}
/******/ 		Object.defineProperty(exports, '__esModule', { value: true });
/******/ 	};
/******/
/******/ 	// create a fake namespace object
/******/ 	// mode & 1: value is a module id, require it
/******/ 	// mode & 2: merge all properties of value into the ns
/******/ 	// mode & 4: return value when already ns object
/******/ 	// mode & 8|1: behave like require
/******/ 	__webpack_require__.t = function(value, mode) {
/******/ 		if(mode & 1) value = __webpack_require__(value);
/******/ 		if(mode & 8) return value;
/******/ 		if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ 		var ns = Object.create(null);
/******/ 		__webpack_require__.r(ns);
/******/ 		Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ 		if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ 		return ns;
/******/ 	};
/******/
/******/ 	// getDefaultExport function for compatibility with non-harmony modules
/******/ 	__webpack_require__.n = function(module) {
/******/ 		var getter = module && module.__esModule ?
/******/ 			function getDefault() { return module['default']; } :
/******/ 			function getModuleExports() { return module; };
/******/ 		__webpack_require__.d(getter, 'a', getter);
/******/ 		return getter;
/******/ 	};
/******/
/******/ 	// Object.prototype.hasOwnProperty.call
/******/ 	__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ 	// __webpack_public_path__
/******/ 	__webpack_require__.p = "";
/******/
/******/
/******/ 	// Load entry module and return exports
/******/ 	return __webpack_require__(__webpack_require__.s = 418);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__extends", function() { return __extends; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__assign", function() { return __assign; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__rest", function() { return __rest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__decorate", function() { return __decorate; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__param", function() { return __param; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__metadata", function() { return __metadata; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__awaiter", function() { return __awaiter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__generator", function() { return __generator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__createBinding", function() { return __createBinding; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__exportStar", function() { return __exportStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__values", function() { return __values; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__read", function() { return __read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spread", function() { return __spread; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__spreadArrays", function() { return __spreadArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__await", function() { return __await; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncGenerator", function() { return __asyncGenerator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncDelegator", function() { return __asyncDelegator; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__asyncValues", function() { return __asyncValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__makeTemplateObject", function() { return __makeTemplateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importStar", function() { return __importStar; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__importDefault", function() { return __importDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldGet", function() { return __classPrivateFieldGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "__classPrivateFieldSet", function() { return __classPrivateFieldSet; });
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

var __createBinding = Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
});

function __exportStar(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
}

function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};

function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

var __setModuleDefault = Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
}

function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, privateMap) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to get private field on non-instance");
    }
    return privateMap.get(receiver);
}

function __classPrivateFieldSet(receiver, privateMap, value) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to set private field on non-instance");
    }
    privateMap.set(receiver, value);
    return value;
}


/***/ }),
/* 1 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Mat4", function() { return /* reexport */ _3d["c" /* Mat4 */]; });
__webpack_require__.d(__webpack_exports__, "Mat3", function() { return /* reexport */ _3d["b" /* Mat3 */]; });
__webpack_require__.d(__webpack_exports__, "Vec2", function() { return /* reexport */ _3d["e" /* Vec2 */]; });
__webpack_require__.d(__webpack_exports__, "Vec3", function() { return /* reexport */ _3d["f" /* Vec3 */]; });
__webpack_require__.d(__webpack_exports__, "Vec4", function() { return /* reexport */ _3d["g" /* Vec4 */]; });
__webpack_require__.d(__webpack_exports__, "Quat", function() { return /* reexport */ _3d["d" /* Quat */]; });
__webpack_require__.d(__webpack_exports__, "EPSILON", function() { return /* reexport */ _3d["a" /* EPSILON */]; });
__webpack_require__.d(__webpack_exports__, "Tensor", function() { return /* reexport */ tensor_Tensor; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d.js + 4 modules
var _3d = __webpack_require__(25);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/tensor.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var tensor_Tensor;
(function (Tensor) {
    function Layout(dimensions, axisOrderSlowToFast, ctor) {
        // need to reverse the axis order for better access.
        var axisOrderFastToSlow = [];
        for (var i = 0; i < axisOrderSlowToFast.length; i++)
            axisOrderFastToSlow[i] = axisOrderSlowToFast[axisOrderSlowToFast.length - i - 1];
        var accessDimensions = [1];
        for (var i = 1; i < dimensions.length; i++)
            accessDimensions[i] = dimensions[axisOrderFastToSlow[i - 1]];
        return { dimensions: dimensions, axisOrderFastToSlow: axisOrderFastToSlow, axisOrderSlowToFast: axisOrderSlowToFast, accessDimensions: accessDimensions, defaultCtor: ctor || Float64Array };
    }
    function create(space, data) { return { space: space, data: data }; }
    Tensor.create = create;
    function Space(dimensions, axisOrderSlowToFast, ctor) {
        var layout = Layout(dimensions, axisOrderSlowToFast, ctor);
        var _a = accessors(layout), get = _a.get, set = _a.set, add = _a.add, dataOffset = _a.dataOffset, getCoords = _a.getCoords;
        return { rank: dimensions.length, dimensions: dimensions, axisOrderSlowToFast: axisOrderSlowToFast, create: creator(layout), get: get, set: set, add: add, dataOffset: dataOffset, getCoords: getCoords };
    }
    Tensor.Space = Space;
    function Data1(values) { return values; }
    Tensor.Data1 = Data1;
    function Vector(d, ctor) { return Space([d], [0], ctor); }
    Tensor.Vector = Vector;
    function ColumnMajorMatrix(rows, cols, ctor) { return Space([rows, cols], [1, 0], ctor); }
    Tensor.ColumnMajorMatrix = ColumnMajorMatrix;
    function RowMajorMatrix(rows, cols, ctor) { return Space([rows, cols], [0, 1], ctor); }
    Tensor.RowMajorMatrix = RowMajorMatrix;
    function toMat4(out, space, data) {
        if (space.rank !== 2)
            throw new Error('Invalid tensor rank');
        var d0 = Math.min(4, space.dimensions[0]), d1 = Math.min(4, space.dimensions[1]);
        for (var i = 0; i < d0; i++) {
            for (var j = 0; j < d1; j++)
                _3d["c" /* Mat4 */].setValue(out, i, j, space.get(data, i, j));
        }
        return out;
    }
    Tensor.toMat4 = toMat4;
    function toMat3(out, space, data) {
        if (space.rank !== 2)
            throw new Error('Invalid tensor rank');
        var d0 = Math.min(3, space.dimensions[0]), d1 = Math.min(3, space.dimensions[1]);
        for (var i = 0; i < d0; i++) {
            for (var j = 0; j < d1; j++)
                _3d["b" /* Mat3 */].setValue(out, i, j, space.get(data, i, j));
        }
        return out;
    }
    Tensor.toMat3 = toMat3;
    function toVec3(out, space, data) {
        if (space.rank !== 1)
            throw new Error('Invalid tensor rank');
        var d0 = Math.min(3, space.dimensions[0]);
        for (var i = 0; i < d0; i++)
            out[i] = data[i];
        return out;
    }
    Tensor.toVec3 = toVec3;
    function toVec4(out, space, data) {
        if (space.rank !== 1)
            throw new Error('Invalid tensor rank');
        var d0 = Math.min(4, space.dimensions[0]);
        for (var i = 0; i < d0; i++)
            out[i] = data[i];
        return out;
    }
    Tensor.toVec4 = toVec4;
    function areEqualExact(a, b) {
        var len = a.length;
        if (len !== b.length)
            return false;
        for (var i = 0; i < len; i++)
            if (a[i] !== b[i])
                return false;
        return true;
    }
    Tensor.areEqualExact = areEqualExact;
    function accessors(layout) {
        var dimensions = layout.dimensions, ao = layout.axisOrderFastToSlow;
        switch (dimensions.length) {
            case 1: return {
                get: function (t, d) { return t[d]; },
                set: function (t, d, x) { return t[d] = x; },
                add: function (t, d, x) { return t[d] += x; },
                dataOffset: function (d) { return d; },
                getCoords: function (o, c) { c[0] = o; return c; }
            };
            case 2: {
                // column major
                if (ao[0] === 0 && ao[1] === 1) {
                    var rows_1 = dimensions[0];
                    return {
                        get: function (t, i, j) { return t[j * rows_1 + i]; },
                        set: function (t, i, j, x) { return t[j * rows_1 + i] = x; },
                        add: function (t, i, j, x) { return t[j * rows_1 + i] += x; },
                        dataOffset: function (i, j) { return j * rows_1 + i; },
                        getCoords: function (o, c) { c[0] = o % rows_1; c[1] = Math.floor(o / rows_1); return c; }
                    };
                }
                if (ao[0] === 1 && ao[1] === 0) {
                    var cols_1 = dimensions[1];
                    return {
                        get: function (t, i, j) { return t[i * cols_1 + j]; },
                        set: function (t, i, j, x) { return t[i * cols_1 + j] = x; },
                        add: function (t, i, j, x) { return t[i * cols_1 + j] += x; },
                        dataOffset: function (i, j) { return i * cols_1 + j; },
                        getCoords: function (o, c) { c[0] = Math.floor(o / cols_1); c[1] = o % cols_1; return c; }
                    };
                }
                throw new Error('bad axis order');
            }
            case 3: {
                if (ao[0] === 0 && ao[1] === 1 && ao[2] === 2) { // 012 ijk
                    var u_1 = dimensions[0], v_1 = dimensions[1], uv_1 = u_1 * v_1;
                    return {
                        get: function (t, i, j, k) { return t[i + j * u_1 + k * uv_1]; },
                        set: function (t, i, j, k, x) { return t[i + j * u_1 + k * uv_1] = x; },
                        add: function (t, i, j, k, x) { return t[i + j * u_1 + k * uv_1] += x; },
                        dataOffset: function (i, j, k) { return i + j * u_1 + k * uv_1; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_1);
                            c[0] = o % u_1;
                            c[1] = p % v_1;
                            c[2] = Math.floor(p / v_1);
                            return c;
                        }
                    };
                }
                if (ao[0] === 0 && ao[1] === 2 && ao[2] === 1) { // 021 ikj
                    var u_2 = dimensions[0], v_2 = dimensions[2], uv_2 = u_2 * v_2;
                    return {
                        get: function (t, i, j, k) { return t[i + k * u_2 + j * uv_2]; },
                        set: function (t, i, j, k, x) { return t[i + k * u_2 + j * uv_2] = x; },
                        add: function (t, i, j, k, x) { return t[i + k * u_2 + j * uv_2] += x; },
                        dataOffset: function (i, j, k) { return i + k * u_2 + j * uv_2; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_2);
                            c[0] = o % u_2;
                            c[1] = Math.floor(p / v_2);
                            c[2] = p % v_2;
                            return c;
                        }
                    };
                }
                if (ao[0] === 1 && ao[1] === 0 && ao[2] === 2) { // 102 jik
                    var u_3 = dimensions[1], v_3 = dimensions[0], uv_3 = u_3 * v_3;
                    return {
                        get: function (t, i, j, k) { return t[j + i * u_3 + k * uv_3]; },
                        set: function (t, i, j, k, x) { return t[j + i * u_3 + k * uv_3] = x; },
                        add: function (t, i, j, k, x) { return t[j + i * u_3 + k * uv_3] += x; },
                        dataOffset: function (i, j, k) { return j + i * u_3 + k * uv_3; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_3);
                            c[0] = p % v_3;
                            c[1] = o % u_3;
                            c[2] = Math.floor(p / v_3);
                            return c;
                        }
                    };
                }
                if (ao[0] === 1 && ao[1] === 2 && ao[2] === 0) { // 120 jki
                    var u_4 = dimensions[1], v_4 = dimensions[2], uv_4 = u_4 * v_4;
                    return {
                        get: function (t, i, j, k) { return t[j + k * u_4 + i * uv_4]; },
                        set: function (t, i, j, k, x) { return t[j + k * u_4 + i * uv_4] = x; },
                        add: function (t, i, j, k, x) { return t[j + k * u_4 + i * uv_4] += x; },
                        dataOffset: function (i, j, k) { return j + k * u_4 + i * uv_4; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_4);
                            c[0] = Math.floor(p / v_4);
                            c[1] = o % u_4;
                            c[2] = p % v_4;
                            return c;
                        }
                    };
                }
                if (ao[0] === 2 && ao[1] === 0 && ao[2] === 1) { // 201 kij
                    var u_5 = dimensions[2], v_5 = dimensions[0], uv_5 = u_5 * v_5;
                    return {
                        get: function (t, i, j, k) { return t[k + i * u_5 + j * uv_5]; },
                        set: function (t, i, j, k, x) { return t[k + i * u_5 + j * uv_5] = x; },
                        add: function (t, i, j, k, x) { return t[k + i * u_5 + j * uv_5] += x; },
                        dataOffset: function (i, j, k) { return k + i * u_5 + j * uv_5; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_5);
                            c[0] = p % v_5;
                            c[1] = Math.floor(p / v_5);
                            c[2] = o % u_5;
                            return c;
                        }
                    };
                }
                if (ao[0] === 2 && ao[1] === 1 && ao[2] === 0) { // 210 kji
                    var u_6 = dimensions[2], v_6 = dimensions[1], uv_6 = u_6 * v_6;
                    return {
                        get: function (t, i, j, k) { return t[k + j * u_6 + i * uv_6]; },
                        set: function (t, i, j, k, x) { return t[k + j * u_6 + i * uv_6] = x; },
                        add: function (t, i, j, k, x) { return t[k + j * u_6 + i * uv_6] += x; },
                        dataOffset: function (i, j, k) { return k + j * u_6 + i * uv_6; },
                        getCoords: function (o, c) {
                            var p = Math.floor(o / u_6);
                            c[0] = Math.floor(p / v_6);
                            c[1] = p % v_6;
                            c[2] = o % u_6;
                            return c;
                        }
                    };
                }
                throw new Error('bad axis order');
            }
            default: return {
                get: function (t) {
                    var c = [];
                    for (var _a = 1; _a < arguments.length; _a++) {
                        c[_a - 1] = arguments[_a];
                    }
                    return t[dataOffset(layout, c)];
                },
                set: function (t) {
                    var c = [];
                    for (var _a = 1; _a < arguments.length; _a++) {
                        c[_a - 1] = arguments[_a];
                    }
                    return t[dataOffset(layout, c)] = c[c.length - 1];
                },
                add: function (t) {
                    var c = [];
                    for (var _a = 1; _a < arguments.length; _a++) {
                        c[_a - 1] = arguments[_a];
                    }
                    return t[dataOffset(layout, c)] += c[c.length - 1];
                },
                dataOffset: function () {
                    var c = [];
                    for (var _a = 0; _a < arguments.length; _a++) {
                        c[_a] = arguments[_a];
                    }
                    return dataOffset(layout, c);
                },
                getCoords: function (o, c) { return getCoords(layout, o, c); },
            };
        }
    }
    function creator(layout) {
        var ds = layout.dimensions;
        var size = 1;
        for (var i = 0, _i = ds.length; i < _i; i++)
            size *= ds[i];
        return function (ctor) { return new (ctor || layout.defaultCtor)(size); };
    }
    function dataOffset(layout, coord) {
        var acc = layout.accessDimensions, ao = layout.axisOrderFastToSlow;
        var d = acc.length - 1;
        var o = acc[d] * coord[ao[d]];
        for (var i = d - 1; i >= 0; i--) {
            o = (o + coord[ao[i]]) * acc[i];
        }
        return o;
    }
    function getCoords(layout, o, coords) {
        var dim = layout.dimensions, ao = layout.axisOrderFastToSlow;
        var d = dim.length;
        var c = o;
        for (var i = 0; i < d; i++) {
            var d_1 = dim[ao[i]];
            coords[ao[i]] = c % d_1;
            c = Math.floor(c / d_1);
        }
        coords[ao[d + 1]] = c;
        return coords;
    }
    // Convers "slow to fast" axis order to "fast to slow" and vice versa.
    function invertAxisOrder(v) {
        var ret = [];
        for (var i = 0; i < v.length; i++) {
            ret[i] = v[v.length - i - 1];
        }
        return ret;
    }
    Tensor.invertAxisOrder = invertAxisOrder;
    function reorder(xs, indices) {
        var ret = [];
        for (var i = 0; i < xs.length; i++)
            ret[i] = xs[indices[i]];
        return ret;
    }
    function convertToCanonicalAxisIndicesFastToSlow(order) {
        var indices = new Int32Array(order.length);
        for (var i = 0; i < order.length; i++)
            indices[order[i]] = i;
        return function (xs) { return reorder(xs, indices); };
    }
    Tensor.convertToCanonicalAxisIndicesFastToSlow = convertToCanonicalAxisIndicesFastToSlow;
    function convertToCanonicalAxisIndicesSlowToFast(order) {
        var indices = new Int32Array(order.length);
        for (var i = 0; i < order.length; i++)
            indices[order[order.length - i - 1]] = i;
        return function (xs) { return reorder(xs, indices); };
    }
    Tensor.convertToCanonicalAxisIndicesSlowToFast = convertToCanonicalAxisIndicesSlowToFast;
})(tensor_Tensor || (tensor_Tensor = {}));
//# sourceMappingURL=tensor.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


//# sourceMappingURL=linear-algebra.js.map

/***/ }),
/* 2 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ParamDefinition", function() { return ParamDefinition; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _index__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _object__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(85);
/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/* harmony import */ var _color_lists__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(88);
/* harmony import */ var _assets__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(114);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var ParamDefinition;
(function (ParamDefinition) {
    ParamDefinition.Essential = { isEssential: true };
    function setInfo(param, info) {
        if (!info)
            return param;
        if (info.label)
            param.label = info.label;
        if (info.description)
            param.description = info.description;
        if (info.legend)
            param.legend = info.legend;
        if (info.fieldLabels)
            param.fieldLabels = info.fieldLabels;
        if (info.isHidden)
            param.isHidden = info.isHidden;
        if (info.shortLabel)
            param.shortLabel = info.shortLabel;
        if (info.twoColumns)
            param.twoColumns = info.twoColumns;
        if (info.isEssential)
            param.isEssential = info.isEssential;
        if (info.category)
            param.category = info.category;
        if (info.hideIf)
            param.hideIf = info.hideIf;
        if (info.help)
            param.help = info.help;
        return param;
    }
    function Optional(p) {
        var ret = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, p);
        ret.isOptional = true;
        return ret;
    }
    ParamDefinition.Optional = Optional;
    function Value(defaultValue, info) {
        return setInfo({ type: 'value', defaultValue: defaultValue }, info);
    }
    ParamDefinition.Value = Value;
    function Select(defaultValue, options, info) {
        return setInfo({ type: 'select', defaultValue: checkDefaultKey(defaultValue, options), options: options, cycle: info === null || info === void 0 ? void 0 : info.cycle }, info);
    }
    ParamDefinition.Select = Select;
    function MultiSelect(defaultValue, options, info) {
        // TODO: check if default value is a subset of options?
        var ret = setInfo({ type: 'multi-select', defaultValue: defaultValue, options: options }, info);
        if (info === null || info === void 0 ? void 0 : info.emptyValue)
            ret.emptyValue = info.emptyValue;
        return ret;
    }
    ParamDefinition.MultiSelect = MultiSelect;
    function Boolean(defaultValue, info) {
        return setInfo({ type: 'boolean', defaultValue: defaultValue }, info);
    }
    ParamDefinition.Boolean = Boolean;
    function Text(defaultValue, info) {
        if (defaultValue === void 0) { defaultValue = ''; }
        return setInfo({ type: 'text', defaultValue: defaultValue }, info);
    }
    ParamDefinition.Text = Text;
    function Color(defaultValue, info) {
        var ret = setInfo({ type: 'color', defaultValue: defaultValue }, info);
        if (info === null || info === void 0 ? void 0 : info.isExpanded)
            ret.isExpanded = info.isExpanded;
        return ret;
    }
    ParamDefinition.Color = Color;
    function ColorList(defaultValue, info) {
        var def;
        if (typeof defaultValue === 'string') {
            var colors = Object(_color_lists__WEBPACK_IMPORTED_MODULE_5__["getColorListFromName"])(defaultValue);
            def = { kind: colors.type !== 'qualitative' ? 'interpolate' : 'set', colors: colors.list };
        }
        else {
            def = defaultValue;
        }
        return setInfo({ type: 'color-list', presetKind: (info === null || info === void 0 ? void 0 : info.presetKind) || 'all', defaultValue: def }, info);
    }
    ParamDefinition.ColorList = ColorList;
    function Vec3(defaultValue, range, info) {
        return setInfo(setRange({ type: 'vec3', defaultValue: defaultValue }, range), info);
    }
    ParamDefinition.Vec3 = Vec3;
    function Mat4(defaultValue, info) {
        return setInfo({ type: 'mat4', defaultValue: defaultValue }, info);
    }
    ParamDefinition.Mat4 = Mat4;
    function Url(url, info) {
        var defaultValue = typeof url === 'string' ? _assets__WEBPACK_IMPORTED_MODULE_6__["Asset"].Url(url) : _assets__WEBPACK_IMPORTED_MODULE_6__["Asset"].Url(url.url, { body: url.body });
        var ret = setInfo({ type: 'url', defaultValue: defaultValue }, info);
        return ret;
    }
    ParamDefinition.Url = Url;
    function File(info) {
        var ret = setInfo({ type: 'file', defaultValue: null }, info);
        if (info === null || info === void 0 ? void 0 : info.accept)
            ret.accept = info.accept;
        return ret;
    }
    ParamDefinition.File = File;
    function FileList(info) {
        var ret = setInfo({ type: 'file-list', defaultValue: null }, info);
        if (info === null || info === void 0 ? void 0 : info.accept)
            ret.accept = info.accept;
        return ret;
    }
    ParamDefinition.FileList = FileList;
    function setRange(p, range) {
        if (!range)
            return p;
        if (typeof range.min !== 'undefined')
            p.min = range.min;
        if (typeof range.max !== 'undefined')
            p.max = range.max;
        if (typeof range.step !== 'undefined')
            p.step = range.step;
        return p;
    }
    function Numeric(defaultValue, range, info) {
        return setInfo(setRange({ type: 'number', defaultValue: defaultValue }, range), info);
    }
    ParamDefinition.Numeric = Numeric;
    function Interval(defaultValue, range, info) {
        return setInfo(setRange({ type: 'interval', defaultValue: defaultValue }, range), info);
    }
    ParamDefinition.Interval = Interval;
    function LineGraph(defaultValue, info) {
        return setInfo({ type: 'line-graph', defaultValue: defaultValue }, info);
    }
    ParamDefinition.LineGraph = LineGraph;
    function Group(params, info) {
        var ret = setInfo({ type: 'group', defaultValue: (info === null || info === void 0 ? void 0 : info.customDefault) || getDefaultValues(params), params: params }, info);
        if (info === null || info === void 0 ? void 0 : info.isExpanded)
            ret.isExpanded = info.isExpanded;
        if (info === null || info === void 0 ? void 0 : info.isFlat)
            ret.isFlat = info.isFlat;
        if (info === null || info === void 0 ? void 0 : info.pivot)
            ret.pivot = info.pivot;
        return ret;
    }
    ParamDefinition.Group = Group;
    function EmptyGroup(info) {
        return Group({}, info);
    }
    ParamDefinition.EmptyGroup = EmptyGroup;
    function Mapped(defaultKey, names, map, info) {
        var name = checkDefaultKey(defaultKey, names);
        return setInfo({
            type: 'mapped',
            defaultValue: { name: name, params: map(name).defaultValue },
            select: Select(name, names, info),
            map: map
        }, info);
    }
    ParamDefinition.Mapped = Mapped;
    function MappedStatic(defaultKey, map, info) {
        var options = (info === null || info === void 0 ? void 0 : info.options) ? info.options
            : Object.keys(map).map(function (k) { return [k, map[k].label || Object(_string__WEBPACK_IMPORTED_MODULE_4__[/* stringToWords */ "d"])(k)]; });
        var name = checkDefaultKey(defaultKey, options);
        return setInfo({
            type: 'mapped',
            defaultValue: { name: name, params: map[name].defaultValue },
            select: Select(name, options, info),
            map: function (key) { return map[key]; }
        }, info);
    }
    ParamDefinition.MappedStatic = MappedStatic;
    function ObjectList(element, getLabel, info) {
        return setInfo({ type: 'object-list', element: element, getLabel: getLabel, ctor: _defaultObjectListCtor, defaultValue: (info === null || info === void 0 ? void 0 : info.defaultValue) || [] }, info);
    }
    ParamDefinition.ObjectList = ObjectList;
    function _defaultObjectListCtor() { return getDefaultValues(this.element); }
    function Converted(fromValue, toValue, converted) {
        return { type: 'converted', defaultValue: toValue(converted.defaultValue), converted: converted, fromValue: fromValue, toValue: toValue };
    }
    ParamDefinition.Converted = Converted;
    function Conditioned(defaultValue, conditionParams, conditionForValue, conditionedValue, info) {
        var options = Object.keys(conditionParams).map(function (k) { return [k, k]; });
        return setInfo({ type: 'conditioned', select: Select(conditionForValue(defaultValue), options, info), defaultValue: defaultValue, conditionParams: conditionParams, conditionForValue: conditionForValue, conditionedValue: conditionedValue }, info);
    }
    ParamDefinition.Conditioned = Conditioned;
    function Script(defaultValue, info) {
        return setInfo({ type: 'script', defaultValue: defaultValue }, info);
    }
    ParamDefinition.Script = Script;
    function For(params) {
        return 0;
    }
    ParamDefinition.For = For;
    function getDefaultValues(params) {
        var d = {};
        for (var _a = 0, _b = Object.keys(params); _a < _b.length; _a++) {
            var k = _b[_a];
            if (params[k].isOptional)
                continue;
            d[k] = params[k].defaultValue;
        }
        return d;
    }
    ParamDefinition.getDefaultValues = getDefaultValues;
    function setDefaultValues(params, defaultValues) {
        for (var _a = 0, _b = Object.keys(params); _a < _b.length; _a++) {
            var k = _b[_a];
            if (params[k].isOptional)
                continue;
            params[k].defaultValue = defaultValues[k];
        }
    }
    ParamDefinition.setDefaultValues = setDefaultValues;
    function clone(params) {
        return Object(_object__WEBPACK_IMPORTED_MODULE_3__[/* deepClone */ "b"])(params);
    }
    ParamDefinition.clone = clone;
    function validate(params, values) {
        // TODO
        return void 0;
    }
    ParamDefinition.validate = validate;
    function areEqual(params, a, b) {
        if (a === b)
            return true;
        if (typeof a !== 'object' || typeof b !== 'object')
            return false;
        for (var _a = 0, _b = Object.keys(params); _a < _b.length; _a++) {
            var k = _b[_a];
            if (!isParamEqual(params[k], a[k], b[k]))
                return false;
        }
        return true;
    }
    ParamDefinition.areEqual = areEqual;
    function isParamEqual(p, a, b) {
        if (a === b)
            return true;
        if (p.type === 'group') {
            return areEqual(p.params, a, b);
        }
        else if (p.type === 'mapped') {
            var u = a, v = b;
            if (u.name !== v.name)
                return false;
            var map = p.map(u.name);
            return isParamEqual(map, u.params, v.params);
        }
        else if (p.type === 'multi-select') {
            var u = a, v = b;
            if (u.length !== v.length)
                return false;
            if (u.length < 10) {
                for (var i = 0, _i = u.length; i < _i; i++) {
                    if (u[i] === v[i])
                        continue;
                    if (v.indexOf(u[i]) < 0)
                        return false;
                }
            }
            else {
                // TODO: should the value of multiselect be a set?
                var vSet = new Set(v);
                for (var i = 0, _i = u.length; i < _i; i++) {
                    if (u[i] === v[i])
                        continue;
                    if (!vSet.has(u[i]))
                        return false;
                }
            }
            return true;
        }
        else if (p.type === 'interval') {
            return a[0] === b[0] && a[1] === b[1];
        }
        else if (p.type === 'line-graph') {
            var u = a, v = b;
            if (u.length !== v.length)
                return false;
            for (var i = 0, _i = u.length; i < _i; i++) {
                if (!_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].areEqual(u[i], v[i]))
                    return false;
            }
            return true;
        }
        else if (p.type === 'vec3') {
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].equals(a, b);
        }
        else if (p.type === 'mat4') {
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat4"].areEqual(a, b, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["EPSILON"]);
        }
        else if (p.type === 'script') {
            var u = a, v = b;
            return u.language === v.language && u.expression === v.expression;
        }
        else if (p.type === 'object-list') {
            var u = a, v = b;
            var l = u.length;
            if (l !== v.length)
                return false;
            for (var i = 0; i < l; i++) {
                if (!areEqual(p.element, u[i], v[i]))
                    return false;
            }
            return true;
        }
        else if (typeof a === 'object' && typeof b === 'object') {
            return Object(_index__WEBPACK_IMPORTED_MODULE_1__[/* shallowEqualObjects */ "m"])(a, b);
        }
        // a === b was checked at the top.
        return false;
    }
    ParamDefinition.isParamEqual = isParamEqual;
    function merge(params, a, b) {
        if (a === undefined)
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, b);
        if (b === undefined)
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, a);
        var o = Object.create(null);
        for (var _a = 0, _b = Object.keys(params); _a < _b.length; _a++) {
            var k = _b[_a];
            o[k] = mergeParam(params[k], a[k], b[k]);
        }
        return o;
    }
    ParamDefinition.merge = merge;
    function mergeParam(p, a, b) {
        if (a === undefined)
            return typeof b === 'object' && !Array.isArray(b) ? Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, b) : b;
        if (b === undefined)
            return typeof a === 'object' && !Array.isArray(a) ? Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, a) : a;
        if (p.type === 'group') {
            return merge(p.params, a, b);
        }
        else if (p.type === 'mapped') {
            var u = a, v = b;
            if (u.name !== v.name)
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, v);
            var map = p.map(v.name);
            return {
                name: v.name,
                params: mergeParam(map, u.params, v.params)
            };
        }
        else if (p.type === 'value') {
            return b;
        }
        else if (typeof a === 'object' && typeof b === 'object') {
            if (Array.isArray(b)) {
                return b;
            }
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, a), b);
        }
        else {
            return b;
        }
    }
    ParamDefinition.mergeParam = mergeParam;
    /**
     * Map an object to a list of [K, string][] to be used as options, stringToWords for key used by default (or identity of null).
     *
     * if options is { [string]: string } and mapping is not provided, use the Value.
     */
    function objectToOptions(options, f) {
        var ret = [];
        for (var _a = 0, _b = Object.keys(options); _a < _b.length; _a++) {
            var k = _b[_a];
            if (!f) {
                if (typeof options[k] === 'string')
                    ret.push([k, options[k]]);
                else
                    ret.push([k, f === null ? k : Object(_string__WEBPACK_IMPORTED_MODULE_4__[/* stringToWords */ "d"])(k)]);
            }
            else {
                var o = f(k, options[k]);
                ret.push(typeof o === 'string' ? [k, o] : [k, o[0], o[1]]);
            }
        }
        return ret;
    }
    ParamDefinition.objectToOptions = objectToOptions;
    /**
     * Map array of options using stringToWords by default (or identity of null).
     */
    function arrayToOptions(xs, f) {
        var ret = [];
        for (var _a = 0, xs_1 = xs; _a < xs_1.length; _a++) {
            var x = xs_1[_a];
            if (!f) {
                ret.push([x, f === null ? x : Object(_string__WEBPACK_IMPORTED_MODULE_4__[/* stringToWords */ "d"])(x)]);
            }
            else {
                ret.push([x, f(x)]);
            }
        }
        return ret;
    }
    ParamDefinition.arrayToOptions = arrayToOptions;
    function optionLabel(param, value) {
        for (var _a = 0, _b = param.options; _a < _b.length; _a++) {
            var o = _b[_a];
            if (o[0] === value)
                return o[1];
        }
        return '';
    }
    ParamDefinition.optionLabel = optionLabel;
    function checkDefaultKey(k, options) {
        for (var _a = 0, options_1 = options; _a < options_1.length; _a++) {
            var o = options_1[_a];
            if (o[0] === k)
                return k;
        }
        return options.length > 0 ? options[0][0] : void 0;
    }
})(ParamDefinition || (ParamDefinition = {}));
//# sourceMappingURL=param-definition.js.map

/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(420);
} else {}


/***/ }),
/* 4 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _structure_coordinates__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(165);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Time", function() { return _structure_coordinates__WEBPACK_IMPORTED_MODULE_0__["b"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Coordinates", function() { return _structure_coordinates__WEBPACK_IMPORTED_MODULE_0__["a"]; });

/* harmony import */ var _structure_topology__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(398);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Topology", function() { return _structure_topology__WEBPACK_IMPORTED_MODULE_1__["a"]; });

/* harmony import */ var _structure_model__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(243);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _structure_model__WEBPACK_IMPORTED_MODULE_2__) if(["Time","Coordinates","Topology","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _structure_model__WEBPACK_IMPORTED_MODULE_2__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/* harmony import */ var _structure_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(27);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureElement", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["d"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Bond", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["a"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Structure", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["c"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Unit", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["g"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureSymmetry", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["f"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureProperties", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["e"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnitRing", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["h"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "UnitRings", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["i"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CifExportContext", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["b"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "mmCIF_Export_Filters", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["k"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "encode_mmCIF_categories", function() { return _structure_structure__WEBPACK_IMPORTED_MODULE_3__["j"]; });

/* harmony import */ var _structure_query__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(166);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "QueryContext", function() { return _structure_query__WEBPACK_IMPORTED_MODULE_4__["b"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Queries", function() { return _structure_query__WEBPACK_IMPORTED_MODULE_4__["a"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureSelection", function() { return _structure_query__WEBPACK_IMPORTED_MODULE_4__["d"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureQuery", function() { return _structure_query__WEBPACK_IMPORTED_MODULE_4__["c"]; });

/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





//# sourceMappingURL=structure.js.map

/***/ }),
/* 5 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "f", function() { return /* reexport */ value_cell["c" /* ValueRef */]; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ value_cell["a" /* ValueBox */]; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ value_cell["b" /* ValueCell */]; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ bit_flags["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ string_builder["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ uuid["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "k", function() { return /* binding */ noop; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* binding */ arrayEqual; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* binding */ deepEqual; });
__webpack_require__.d(__webpack_exports__, "l", function() { return /* binding */ shallowEqual; });
__webpack_require__.d(__webpack_exports__, "m", function() { return /* binding */ shallowEqualObjects; });
__webpack_require__.d(__webpack_exports__, "i", function() { return /* binding */ defaults; });
__webpack_require__.d(__webpack_exports__, "j", function() { return /* binding */ formatTime; });

// UNUSED EXPORTS: Mask, round, default, extend, shallowClone, assign, merge, formatProgress

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/bit-flags.js
var bit_flags = __webpack_require__(207);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string-builder.js
var string_builder = __webpack_require__(106);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/uuid.js
var uuid = __webpack_require__(194);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/mask.js
/**
 * Copyright (c) 2017 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
// TODO check if the removal of FastSet and the removal of the context object for forEach
// have any performance implications
function _ascSort(a, b) {
    return a - b;
}
function sortAsc(array) {
    Array.prototype.sort.call(array, _ascSort);
    return array;
}
var Mask;
(function (Mask) {
    var EmptyMask = /** @class */ (function () {
        function EmptyMask() {
            this.size = 0;
        }
        EmptyMask.prototype.has = function (i) { return false; };
        EmptyMask.prototype.forEach = function (f, ctx) { return ctx; };
        return EmptyMask;
    }());
    var SingletonMask = /** @class */ (function () {
        function SingletonMask(idx) {
            this.idx = idx;
            this.size = 1;
        }
        SingletonMask.prototype.has = function (i) { return i === this.idx; };
        SingletonMask.prototype.forEach = function (f, ctx) { f(this.idx, ctx); return ctx; };
        return SingletonMask;
    }());
    var BitMask = /** @class */ (function () {
        function BitMask(mask, size) {
            this.mask = mask;
            this.size = size;
            this.length = mask.length;
        }
        BitMask.prototype.has = function (i) { return i < this.length && !!this.mask[i]; };
        BitMask.prototype._forEach = function (f, ctx) {
            for (var i = 0; i < this.length; i++) {
                if (this.mask[i])
                    f(i, ctx);
            }
        };
        BitMask.prototype.forEach = function (f, ctx) {
            this._forEach(f, ctx);
            return ctx;
        };
        return BitMask;
    }());
    var AllMask = /** @class */ (function () {
        function AllMask(size) {
            this.size = size;
        }
        AllMask.prototype.has = function (i) { return true; };
        AllMask.prototype._forEach = function (f, ctx) {
            for (var i = 0; i < this.size; i++) {
                f(i, ctx);
            }
        };
        AllMask.prototype.forEach = function (f, ctx) {
            this._forEach(f, ctx);
            return ctx;
        };
        return AllMask;
    }());
    var SetMask = /** @class */ (function () {
        function SetMask(set) {
            this.set = set;
            this._flat = void 0;
            this.size = set.size;
        }
        SetMask.prototype.has = function (i) { return this.set.has(i); };
        SetMask.prototype._forEach = function (f, ctx) {
            for (var _i = 0, _a = this.flatten(); _i < _a.length; _i++) {
                var idx = _a[_i];
                f(idx, ctx);
            }
        };
        SetMask.prototype.flatten = function () {
            if (this._flat)
                return this._flat;
            var indices = new Int32Array(this.size);
            var offset = 0;
            this.set.forEach(function (i) { return indices[offset++] = i; });
            sortAsc(indices);
            this._flat = indices;
            return this._flat;
        };
        SetMask.prototype.forEach = function (f, ctx) {
            this._forEach(f, ctx);
            return ctx;
        };
        return SetMask;
    }());
    function always(size) { return new AllMask(size); }
    Mask.always = always;
    Mask.never = new EmptyMask();
    function ofSet(set) {
        return new SetMask(set);
    }
    Mask.ofSet = ofSet;
    function singleton(i) {
        return new SingletonMask(i);
    }
    Mask.singleton = singleton;
    function ofUniqueIndices(indices) {
        var len = indices.length;
        if (len === 0)
            return new EmptyMask();
        if (len === 1)
            return new SingletonMask(indices[0]);
        var max = 0;
        for (var _i = 0, _a = indices; _i < _a.length; _i++) {
            var i = _a[_i];
            if (i > max)
                max = i;
        }
        if (len === max)
            return new AllMask(len);
        var f = len / max;
        if (f < 1 / 12) {
            var set = new Set();
            for (var _b = 0, _c = indices; _b < _c.length; _b++) {
                var i = _c[_b];
                set.add(i);
            }
            return new SetMask(set);
        }
        var mask = new Int8Array(max + 1);
        for (var _d = 0, _e = indices; _d < _e.length; _d++) {
            var i = _e[_d];
            mask[i] = 1;
        }
        return new BitMask(mask, indices.length);
    }
    Mask.ofUniqueIndices = ofUniqueIndices;
    function ofMask(mask, size) {
        return new BitMask(mask, size);
    }
    Mask.ofMask = ofMask;
    function hasAny(mask, xs) {
        for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
            var x = xs_1[_i];
            if (mask.has(x))
                return true;
        }
        return false;
    }
    Mask.hasAny = hasAny;
    function complement(mask, against) {
        var count = 0;
        var max = 0;
        against.forEach(function (i) {
            if (!mask.has(i)) {
                count++;
                if (i > max)
                    max = i;
            }
        });
        if (count / max < 1 / 12) {
            // set based
            var set_1 = new Set();
            against.forEach(function (i) {
                if (!mask.has(i)) {
                    set_1.add(i);
                }
            });
            return ofSet(set_1);
        }
        else {
            // mask based
            var target_1 = new Uint8Array(max + 1);
            against.forEach(function (i) {
                if (!mask.has(i)) {
                    target_1[i] = 1;
                }
            });
            return ofMask(target_1, count);
        }
    }
    Mask.complement = complement;
})(Mask || (Mask = {}));
/* harmony default export */ var mask = (Mask);
//# sourceMappingURL=mask.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/value-cell.js
var value_cell = __webpack_require__(58);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/index.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var noop = function () { };
function round(n, d) {
    var f = Math.pow(10, d);
    return Math.round(f * n) / f;
}
function arrayEqual(arr1, arr2) {
    var length = arr1.length;
    if (length !== arr2.length)
        return false;
    for (var i = 0; i < length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false;
        }
    }
    return true;
}
var mol_util_hasOwnProperty = Object.prototype.hasOwnProperty;
function deepEqual(a, b) {
    // from https://github.com/epoberezkin/fast-deep-equal MIT
    if (a === b)
        return true;
    var arrA = Array.isArray(a);
    var arrB = Array.isArray(b);
    if (arrA && arrB) {
        if (a.length !== b.length)
            return false;
        for (var i = 0; i < a.length; i++) {
            if (!deepEqual(a[i], b[i]))
                return false;
        }
        return true;
    }
    if (arrA !== arrB)
        return false;
    if (a && b && typeof a === 'object' && typeof b === 'object') {
        var keys = Object.keys(a);
        if (keys.length !== Object.keys(b).length)
            return false;
        var dateA = a instanceof Date;
        var dateB = b instanceof Date;
        if (dateA && dateB)
            return a.getTime() === b.getTime();
        if (dateA !== dateB)
            return false;
        var regexpA = a instanceof RegExp;
        var regexpB = b instanceof RegExp;
        if (regexpA && regexpB)
            return a.toString() === b.toString();
        if (regexpA !== regexpB)
            return false;
        for (var i = 0; i < keys.length; i++) {
            if (!mol_util_hasOwnProperty.call(b, keys[i]))
                return false;
        }
        for (var i = 0; i < keys.length; i++) {
            if (!deepEqual(a[keys[i]], b[keys[i]]))
                return false;
        }
        return true;
    }
    return false;
}
function shallowEqual(a, b) {
    if (a === b)
        return true;
    var arrA = Array.isArray(a);
    var arrB = Array.isArray(b);
    if (arrA && arrB)
        return shallowEqualArrays(a, b);
    if (arrA !== arrB)
        return false;
    if (a && b && typeof a === 'object' && typeof b === 'object') {
        return shallowEqualObjects(a, b);
    }
    return false;
}
function shallowEqualObjects(a, b) {
    if (a === b)
        return true;
    if (!a || !b)
        return false;
    var keys = Object.keys(a);
    if (Object.keys(b).length !== keys.length)
        return false;
    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
        var k = keys_1[_i];
        if (!mol_util_hasOwnProperty.call(a, k) || a[k] !== b[k])
            return false;
    }
    return true;
}
function shallowEqualArrays(a, b) {
    if (a === b)
        return true;
    if (!a || !b)
        return false;
    if (a.length !== b.length)
        return false;
    for (var i = 0, il = a.length; i < il; ++i) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
}
/** Returns `value` if not `undefined`, otherwise returns `defaultValue` */
function defaults(value, defaultValue) {
    return value !== undefined ? value : defaultValue;
}
function extend(object, source, guard) {
    var v;
    var s = source;
    var o = object;
    var g = guard;
    for (var _i = 0, _a = Object.keys(source); _i < _a.length; _i++) {
        var k = _a[_i];
        v = s[k];
        if (v !== void 0)
            o[k] = v;
        else if (guard)
            o[k] = g[k];
    }
    if (guard) {
        for (var _b = 0, _c = Object.keys(guard); _b < _c.length; _b++) {
            var k = _c[_b];
            v = o[k];
            if (v === void 0)
                o[k] = g[k];
        }
    }
    return object;
}
function shallowClone(o) {
    return extend({}, o);
}
function _assign(target) {
    for (var s = 1; s < arguments.length; s++) {
        var from = arguments[s];
        for (var _i = 0, _a = Object.keys(from); _i < _a.length; _i++) {
            var key = _a[_i];
            if (mol_util_hasOwnProperty.call(from, key)) {
                target[key] = from[key];
            }
        }
    }
    return target;
}
var mol_util_assign = Object.assign || _assign;
function _shallowMerge1(source, update) {
    var changed = false;
    for (var _i = 0, _a = Object.keys(update); _i < _a.length; _i++) {
        var k = _a[_i];
        if (!mol_util_hasOwnProperty.call(update, k))
            continue;
        if (update[k] !== source[k]) {
            changed = true;
            break;
        }
    }
    if (!changed)
        return source;
    return mol_util_assign(shallowClone(source), update);
}
function _shallowMerge(source) {
    var ret = source;
    for (var s = 1; s < arguments.length; s++) {
        if (!arguments[s])
            continue;
        ret = _shallowMerge1(source, arguments[s]);
        if (ret !== source) {
            for (var i = s + 1; i < arguments.length; i++) {
                ret = mol_util_assign(ret, arguments[i]);
            }
            break;
        }
    }
    return ret;
}
var merge = _shallowMerge;
function padTime(n) { return (n < 10 ? '0' : '') + n; }
function formatTime(d) {
    var h = d.getHours(), m = d.getMinutes(), s = d.getSeconds();
    return h + ":" + padTime(m) + ":" + padTime(s);
}
function formatProgress(p) {
    var tp = p.root.progress;
    if (tp.isIndeterminate)
        return tp.message;
    var x = (100 * tp.current / tp.max).toFixed(2);
    return tp.message + " " + x + "%";
}
//# sourceMappingURL=index.js.map

/***/ }),
/* 6 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Interval", function() { return /* reexport */ int_interval; });
__webpack_require__.d(__webpack_exports__, "OrderedSet", function() { return /* reexport */ ordered_set; });
__webpack_require__.d(__webpack_exports__, "Segmentation", function() { return /* reexport */ segmentation; });
__webpack_require__.d(__webpack_exports__, "SortedArray", function() { return /* reexport */ sorted_array; });
__webpack_require__.d(__webpack_exports__, "Tuple", function() { return /* reexport */ tuple; });
__webpack_require__.d(__webpack_exports__, "LinkedIndex", function() { return /* reexport */ linked_index; });
__webpack_require__.d(__webpack_exports__, "IntMap", function() { return /* reexport */ int_map; });
__webpack_require__.d(__webpack_exports__, "Iterator", function() { return /* reexport */ iterator["a" /* default */]; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/tuple.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var tuple_IntTuple;
(function (IntTuple) {
    IntTuple.Zero = 0;
    var _a = (function () {
        var data = new ArrayBuffer(8);
        var data_1 = new ArrayBuffer(8);
        return {
            _int32: new Int32Array(data),
            _float64: new Float64Array(data),
            _int32_1: new Int32Array(data_1),
            _float64_1: new Float64Array(data_1)
        };
    }()), _int32 = _a._int32, _float64 = _a._float64, _int32_1 = _a._int32_1, _float64_1 = _a._float64_1;
    function is(x) {
        return typeof x === 'number';
    }
    IntTuple.is = is;
    function create(fst, snd) {
        _int32[0] = fst;
        _int32[1] = snd;
        return _float64[0];
    }
    IntTuple.create = create;
    function fst(t) {
        _float64[0] = t;
        return _int32[0];
    }
    IntTuple.fst = fst;
    function snd(t) {
        _float64[0] = t;
        return _int32[1];
    }
    IntTuple.snd = snd;
    /** Normal equality does not work, because NaN === NaN ~> false */
    function areEqual(a, b) {
        _float64[0] = a;
        _float64_1[0] = b;
        return _int32[0] === _int32_1[0] && _int32[1] === _int32_1[1];
    }
    IntTuple.areEqual = areEqual;
    function compare(a, b) {
        _float64[0] = a;
        _float64_1[0] = b;
        var x = _int32[0] - _int32_1[0];
        if (x !== 0)
            return x;
        return _int32[1] - _int32_1[1];
    }
    IntTuple.compare = compare;
    function compareInArray(xs, i, j) {
        _float64[0] = xs[i];
        _float64_1[0] = xs[j];
        var x = _int32[0] - _int32_1[0];
        if (x !== 0)
            return x;
        return _int32[1] - _int32_1[1];
    }
    IntTuple.compareInArray = compareInArray;
    function hashCode(t) {
        _float64[0] = t;
        return Object(util["i" /* hash2 */])(_int32[0], _int32[1]);
    }
    IntTuple.hashCode = hashCode;
    function toString(t) {
        _float64[0] = t;
        return "(" + _int32[0] + ", " + _int32[1] + ")";
    }
    IntTuple.toString = toString;
})(tuple_IntTuple || (tuple_IntTuple = {}));
/* harmony default export */ var tuple = (tuple_IntTuple);
//# sourceMappingURL=tuple.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/impl/interval.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var Empty = tuple.Zero;
function ofRange(min, max) { return max < min ? tuple.create(min, min) : tuple.create(min, max + 1); }
function ofBounds(start, end) { return end <= start ? tuple.create(start, start) : tuple.create(start, end); }
function ofLength(length) { return length < 0 ? tuple.create(0, 0) : tuple.create(0, length); }
var interval_is = tuple.is;
var interval_start = tuple.fst;
var interval_end = tuple.snd;
var interval_min = tuple.fst;
function interval_max(i) { return tuple.snd(i) - 1; }
function size(i) { return tuple.snd(i) - tuple.fst(i); }
var interval_hashCode = tuple.hashCode;
var interval_toString = tuple.toString;
function has(int, v) { return tuple.fst(int) <= v && v < tuple.snd(int); }
/** Returns the index of `x` in `set` or -1 if not found. */
function indexOf(int, x) { var m = interval_start(int); return x >= m && x < interval_end(int) ? x - m : -1; }
function getAt(int, i) { return tuple.fst(int) + i; }
var interval_areEqual = tuple.areEqual;
function areIntersecting(a, b) {
    var sa = size(a), sb = size(b);
    if (sa === 0 && sb === 0)
        return true;
    return sa > 0 && sb > 0 && interval_max(a) >= interval_min(b) && interval_min(a) <= interval_max(b);
}
function isSubInterval(a, b) {
    if (!size(a))
        return size(b) === 0;
    if (!size(b))
        return true;
    return interval_start(a) <= interval_start(b) && interval_end(a) >= interval_end(b);
}
function findPredecessorIndex(int, v) {
    var s = interval_start(int);
    if (v <= s)
        return 0;
    var e = interval_end(int);
    if (v >= e)
        return e - s;
    return v - s;
}
function findPredecessorIndexInInterval(int, v, bounds) {
    var bS = interval_start(bounds);
    var s = interval_start(int);
    if (v <= bS + s)
        return bS;
    var bE = interval_end(bounds);
    if (v >= bE + s)
        return bE;
    return v - s;
}
function findRange(int, min, max) {
    return ofBounds(findPredecessorIndex(int, min), findPredecessorIndex(int, max + 1));
}
function intersect(a, b) {
    if (!areIntersecting(a, b))
        return Empty;
    return ofBounds(Math.max(interval_start(a), interval_start(b)), Math.min(interval_end(a), interval_end(b)));
}
function intersectionSize(a, b) {
    return size(findRange(a, interval_min(b), interval_max(b)));
}
//# sourceMappingURL=interval.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/interval.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var interval_Interval;
(function (Interval) {
    Interval.Empty = Empty;
    Interval.ofSingleton = function (v) { return ofRange(v, v); };
    /** Create interval from range [min, max] */
    Interval.ofRange = ofRange;
    /** Create interval from bounds [start, end), i.e. [start, end - 1] */
    Interval.ofBounds = ofBounds;
    /** Create interval from length [0, length), i.e. [0, length - 1] */
    Interval.ofLength = ofLength;
    Interval.is = interval_is;
    /** Test if a value is within the bounds of the interval */
    Interval.has = has;
    /** Returns the index of `x` in `set` or -1 if not found. */
    Interval.indexOf = indexOf;
    Interval.getAt = getAt;
    /** Start value of the Interval<T>, same as min value */
    Interval.start = interval_start;
    /** End value of the Interval<T>, same as max + 1 */
    Interval.end = interval_end;
    /** Min value of the Interval<T>, same as start value */
    Interval.min = interval_min;
    /** Max value of the Interval<T>, same as end - 1 */
    Interval.max = interval_max;
    /** Number of values in the interval */
    Interval.size = size;
    /** Hash code describing the interval */
    Interval.hashCode = interval_hashCode;
    /** String representation of the interval */
    Interval.toString = interval_toString;
    /** Test if two intervals are identical */
    Interval.areEqual = interval_areEqual;
    /** Test if two intervals are intersecting, i.e. their bounds overlap */
    Interval.areIntersecting = areIntersecting;
    /** Test if interval b is fully included in interval a */
    Interval.isSubInterval = isSubInterval;
    Interval.findPredecessorIndex = findPredecessorIndex;
    Interval.findPredecessorIndexInInterval = findPredecessorIndexInInterval;
    Interval.findRange = findRange;
    /** Size of the intersection of the two intervals */
    Interval.intersectionSize = intersectionSize;
    /** Get a new interval that is the intersection of the two intervals */
    Interval.intersect = intersect;
})(interval_Interval || (interval_Interval = {}));
/* harmony default export */ var int_interval = (interval_Interval);
//# sourceMappingURL=interval.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/impl/sorted-array.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var sorted_array_Empty = [];
function ofSingleton(v) { return [v]; }
function ofSortedArray(xs) { return xs; }
function ofUnsortedArray(xs) { Object(util["q" /* sortArray */])(xs); return xs; }
function sorted_array_ofRange(min, max) {
    if (max < min)
        return [];
    var ret = new Int32Array(max - min + 1);
    for (var i = min; i <= max; i++)
        ret[i - min] = i;
    return ret;
}
function sorted_array_is(xs) { return xs && (Array.isArray(xs) || !!xs.buffer); }
function sorted_array_start(xs) { return xs[0]; }
function sorted_array_end(xs) { return xs[xs.length - 1] + 1; }
function sorted_array_min(xs) { return xs[0]; }
function sorted_array_max(xs) { return xs[xs.length - 1]; }
function sorted_array_size(xs) { return xs.length; }
function sorted_array_hashCode(xs) {
    // hash of tuple (size, min, max, mid)
    var s = xs.length;
    if (!s)
        return 0;
    if (s > 2)
        return Object(util["k" /* hash4 */])(s, xs[0], xs[s - 1], xs[s >> 1]);
    return Object(util["j" /* hash3 */])(s, xs[0], xs[s - 1]);
}
function sorted_array_toString(xs) {
    var s = xs.length;
    if (s > 5)
        return "[" + xs[0] + ", " + xs[1] + ", ..., " + xs[s - 1] + "], length " + s;
    return "[" + xs.join(', ') + "]";
}
/** Returns the index of `x` in `set` or -1 if not found. */
function sorted_array_indexOf(xs, v) {
    var l = xs.length;
    return l === 0 ? -1 : xs[0] <= v && v <= xs[l - 1] ? binarySearchRange(xs, v, 0, l) : -1;
}
function indexOfInInterval(xs, v, bounds) {
    return indexOfInRange(xs, v, int_interval.start(bounds), int_interval.end(bounds));
}
function indexOfInRange(xs, v, s, e) {
    var l = xs.length;
    return l === 0 || e <= s ? -1 : xs[s] <= v && v <= xs[e - 1] ? binarySearchRange(xs, v, s, e) : -1;
}
function sorted_array_has(xs, v) { return sorted_array_indexOf(xs, v) >= 0; }
function sorted_array_getAt(xs, i) { return xs[i]; }
function sorted_array_areEqual(a, b) {
    if (a === b)
        return true;
    var aSize = a.length;
    if (aSize !== b.length || a[0] !== b[0] || a[aSize - 1] !== b[aSize - 1])
        return false;
    for (var i = 0; i < aSize; i++) {
        if (a[i] !== b[i])
            return false;
    }
    return true;
}
/**
 * Returns 0 if `v` is smaller or equal the first element of `xs`
 * Returns length of `xs` if `v` is bigger than the last element of `xs`
 * Otherwise returns the first index where the value of `xs` is equal or bigger than `v`
 */
function sorted_array_findPredecessorIndex(xs, v) {
    var len = xs.length;
    if (v <= xs[0])
        return 0;
    if (v > xs[len - 1])
        return len;
    return binarySearchPredIndexRange(xs, v, 0, len);
}
function sorted_array_findPredecessorIndexInInterval(xs, v, bounds) {
    var s = int_interval.start(bounds), e = int_interval.end(bounds);
    var sv = xs[s];
    if (v <= sv)
        return s;
    if (e > s && v > xs[e - 1])
        return e;
    // do a linear search if there are only 10 or less items remaining
    if (v - sv <= 11)
        return linearSearchPredInRange(xs, v, s + 1, e);
    return binarySearchPredIndexRange(xs, v, s, e);
}
function sorted_array_findRange(xs, min, max) {
    return int_interval.ofBounds(sorted_array_findPredecessorIndex(xs, min), sorted_array_findPredecessorIndex(xs, max + 1));
}
function binarySearchRange(xs, value, start, end) {
    var min = start, max = end - 1;
    while (min <= max) {
        // do a linear search if there are only 10 or less items remaining
        if (min + 11 > max) {
            for (var i = min; i <= max; i++) {
                if (value === xs[i])
                    return i;
            }
            return -1;
        }
        var mid = (min + max) >> 1;
        var v = xs[mid];
        if (value < v)
            max = mid - 1;
        else if (value > v)
            min = mid + 1;
        else
            return mid;
    }
    return -1;
}
function binarySearchPredIndexRange(xs, value, start, end) {
    var min = start, max = end - 1;
    while (min < max) {
        // do a linear search if there are only 10 or less items remaining
        if (min + 11 > max) {
            for (var i = min; i <= max; i++) {
                if (value <= xs[i])
                    return i;
            }
            return max + 1;
        }
        var mid = (min + max) >> 1;
        var v = xs[mid];
        if (value < v)
            max = mid - 1;
        else if (value > v)
            min = mid + 1;
        else
            return mid;
    }
    if (min > max)
        return max + 1;
    return xs[min] >= value ? min : min + 1;
}
function linearSearchPredInRange(xs, value, start, end) {
    for (var i = start; i < end; i++) {
        if (value <= xs[i])
            return i;
    }
    return end;
}
function sorted_array_areIntersecting(a, b) {
    if (a === b)
        return true;
    var _a = getSuitableIntersectionRange(a, b), i = _a.startI, j = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y)
            i++;
        else if (x > y)
            j++;
        else
            return true;
    }
    return false;
}
function isSubset(a, b) {
    if (a === b)
        return true;
    var lenB = b.length;
    var _a = getSuitableIntersectionRange(a, b), i = _a.startI, j = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    // must be able to advance by lenB elements
    if (endJ - j < lenB || endI - i < lenB)
        return false;
    var equal = 0;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            i++;
            j++;
            equal++;
        }
    }
    return equal === lenB;
}
function union(a, b) {
    if (a === b)
        return a;
    var lenA = a.length, lenB = b.length;
    if (lenA === 0)
        return b;
    if (lenB === 0)
        return a;
    if (a[0] > b[0])
        return union(b, a);
    var _a = getSuitableIntersectionRange(a, b), startI = _a.startI, startJ = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    var commonCount = getCommonCount(a, b, startI, startJ, endI, endJ);
    // A === B || B is subset of A ==> A
    if ((commonCount === lenA && commonCount === lenB) || commonCount === lenB)
        return a;
    // A is subset of B ===> B
    if (commonCount === lenA)
        return b;
    var indices = new Int32Array(lenA + lenB - commonCount);
    var i = 0, j = 0, offset = 0;
    // insert the "prefixes"
    for (i = 0; i < startI; i++)
        indices[offset++] = a[i];
    while (j < endJ && a[startI] > b[j])
        indices[offset++] = b[j++];
    // insert the common part
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            indices[offset++] = x;
            i++;
        }
        else if (x > y) {
            indices[offset++] = y;
            j++;
        }
        else {
            indices[offset++] = x;
            i++;
            j++;
        }
    }
    // insert the remaining common part
    for (; i < endI; i++)
        indices[offset++] = a[i];
    for (; j < endJ; j++)
        indices[offset++] = b[j];
    // insert the "tail"
    for (; i < lenA; i++)
        indices[offset++] = a[i];
    for (; j < lenB; j++)
        indices[offset++] = b[j];
    return ofSortedArray(indices);
}
function sorted_array_intersectionSize(a, b) {
    if (a === b)
        return sorted_array_size(a);
    var _a = getSuitableIntersectionRange(a, b), startI = _a.startI, startJ = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    return getCommonCount(a, b, startI, startJ, endI, endJ);
}
function getCommonCount(a, b, startI, startJ, endI, endJ) {
    var i = startI, j = startJ;
    var commonCount = 0;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            i++;
            j++;
            commonCount++;
        }
    }
    return commonCount;
}
function sorted_array_intersect(a, b) {
    if (a === b)
        return a;
    var _a = getSuitableIntersectionRange(a, b), startI = _a.startI, startJ = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    var commonCount = getCommonCount(a, b, startI, startJ, endI, endJ);
    var lenA = a.length, lenB = b.length;
    // no common elements
    if (!commonCount)
        return sorted_array_Empty;
    // A === B || B is subset of A ==> B
    if ((commonCount === lenA && commonCount === lenB) || commonCount === lenB)
        return b;
    // A is subset of B ==> A
    if (commonCount === lenA)
        return a;
    var indices = new Int32Array(commonCount);
    var offset = 0;
    var i = startI;
    var j = startJ;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            indices[offset++] = x;
            i++;
            j++;
        }
    }
    return ofSortedArray(indices);
}
function subtract(a, b) {
    if (a === b)
        return sorted_array_Empty;
    var lenA = a.length;
    var _a = getSuitableIntersectionRange(a, b), sI = _a.startI, sJ = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    var i = sI, j = sJ;
    var commonCount = 0;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            i++;
            j++;
            commonCount++;
        }
    }
    // A isnt intersecting B ===> A
    if (!commonCount)
        return a;
    // A === B || A is subset of B ===> Empty
    if (commonCount >= lenA)
        return sorted_array_Empty;
    var indices = new Int32Array(lenA - commonCount);
    var offset = 0;
    // insert the "prefix"
    for (var k = 0; k < sI; k++)
        indices[offset++] = a[k];
    i = sI;
    j = sJ;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            indices[offset++] = x;
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            i++;
            j++;
        }
    }
    // insert the "tail"
    for (; i < lenA; i++)
        indices[offset++] = a[i];
    return ofSortedArray(indices);
}
function deduplicate(xs) {
    if (xs.length < 2)
        return xs;
    var count = 1;
    for (var i = 0, _i = xs.length - 1; i < _i; i++) {
        if (xs[i] !== xs[i + 1])
            count++;
    }
    if (count === xs.length)
        return xs;
    var ret = new Int32Array(count);
    var o = 0;
    for (var i = 0, _i = xs.length - 1; i < _i; i++) {
        if (xs[i] !== xs[i + 1])
            ret[o++] = xs[i];
    }
    ret[o] = xs[xs.length - 1];
    return ret;
}
function indicesOf(a, b) {
    if (a === b)
        return ofSortedArray(Object(util["g" /* createRangeArray */])(0, a.length - 1));
    var _a = getSuitableIntersectionRange(a, b), sI = _a.startI, sJ = _a.startJ, endI = _a.endI, endJ = _a.endJ;
    var i = sI, j = sJ;
    var commonCount = 0;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            i++;
            j++;
            commonCount++;
        }
    }
    var lenA = a.length;
    // no common elements
    if (!commonCount)
        return sorted_array_Empty;
    // A is subset of B ==> A
    if (commonCount === lenA)
        return ofSortedArray(Object(util["g" /* createRangeArray */])(0, a.length - 1));
    var indices = new Int32Array(commonCount);
    var offset = 0;
    i = sI;
    j = sJ;
    while (i < endI && j < endJ) {
        var x = a[i], y = b[j];
        if (x < y) {
            i++;
        }
        else if (x > y) {
            j++;
        }
        else {
            indices[offset++] = i;
            i++;
            j++;
        }
    }
    return ofSortedArray(indices);
}
var _maxIntRangeRet = { startI: 0, startJ: 0, endI: 0, endJ: 0 };
// for small sets, just gets the whole range, for large sets does a bunch of binary searches
function getSuitableIntersectionRange(a, b) {
    var la = a.length, lb = b.length;
    var ratio = la / lb;
    if (la >= 128 || lb >= 128 || ratio <= 0.34 || ratio >= 2.99) {
        _maxIntRangeRet.startI = sorted_array_findPredecessorIndex(a, sorted_array_start(b));
        _maxIntRangeRet.startJ = sorted_array_findPredecessorIndex(b, sorted_array_start(a));
        _maxIntRangeRet.endI = sorted_array_findPredecessorIndex(a, sorted_array_end(b));
        _maxIntRangeRet.endJ = sorted_array_findPredecessorIndex(b, sorted_array_end(a));
    }
    else {
        _maxIntRangeRet.startI = 0;
        _maxIntRangeRet.startJ = 0;
        _maxIntRangeRet.endI = la;
        _maxIntRangeRet.endJ = lb;
    }
    return _maxIntRangeRet;
}
//# sourceMappingURL=sorted-array.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/sorted-array.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var sorted_array_SortedArray;
(function (SortedArray) {
    SortedArray.Empty = sorted_array_Empty;
    SortedArray.ofUnsortedArray = ofUnsortedArray;
    SortedArray.ofSingleton = ofSingleton;
    SortedArray.ofSortedArray = ofSortedArray;
    /** create sorted array [min, max] (it DOES contain the max value) */
    SortedArray.ofRange = sorted_array_ofRange;
    /** create sorted array [min, max) (it does NOT contain the max value) */
    SortedArray.ofBounds = function (min, max) { return sorted_array_ofRange(min, max - 1); };
    SortedArray.is = sorted_array_is;
    SortedArray.has = sorted_array_has;
    /** Returns the index of `x` in `set` or -1 if not found. */
    SortedArray.indexOf = sorted_array_indexOf;
    SortedArray.indexOfInInterval = indexOfInInterval;
    SortedArray.indexOfInRange = indexOfInRange;
    /** Returns `array[0]` */
    SortedArray.start = sorted_array_start;
    /** Returns `array[array.length - 1] + 1` */
    SortedArray.end = sorted_array_end;
    SortedArray.min = sorted_array_min;
    SortedArray.max = sorted_array_max;
    SortedArray.size = sorted_array_size;
    SortedArray.hashCode = sorted_array_hashCode;
    SortedArray.toString = sorted_array_toString;
    SortedArray.areEqual = sorted_array_areEqual;
    SortedArray.areIntersecting = sorted_array_areIntersecting;
    SortedArray.isSubset = isSubset;
    SortedArray.union = union;
    SortedArray.intersect = sorted_array_intersect;
    SortedArray.subtract = subtract;
    SortedArray.findPredecessorIndex = sorted_array_findPredecessorIndex;
    SortedArray.findPredecessorIndexInInterval = sorted_array_findPredecessorIndexInInterval;
    SortedArray.findRange = sorted_array_findRange;
    SortedArray.intersectionSize = sorted_array_intersectionSize;
    SortedArray.deduplicate = deduplicate;
    /** Returns indices of xs in the array. E.g. indicesOf([10, 11, 12], [10, 12]) ==> [0, 2] */
    SortedArray.indicesOf = indicesOf;
})(sorted_array_SortedArray || (sorted_array_SortedArray = {}));
/* harmony default export */ var sorted_array = (sorted_array_SortedArray);
//# sourceMappingURL=sorted-array.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/impl/ordered-set.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var ordered_set_Empty = int_interval.Empty;
var ordered_set_ofSingleton = int_interval.ofSingleton;
var ordered_set_ofRange = int_interval.ofRange;
var ordered_set_ofBounds = int_interval.ofBounds;
function ordered_set_ofSortedArray(xs) {
    if (!xs.length)
        return ordered_set_Empty;
    // check if the array is just a range
    if (xs[xs.length - 1] - xs[0] + 1 === xs.length)
        return int_interval.ofRange(xs[0], xs[xs.length - 1]);
    return xs;
}
function ordered_set_size(set) { return int_interval.is(set) ? int_interval.size(set) : sorted_array.size(set); }
function ordered_set_has(set, x) { return int_interval.is(set) ? int_interval.has(set, x) : sorted_array.has(set, x); }
/** Returns the index of `x` in `set` or -1 if not found. */
function ordered_set_indexOf(set, x) { return int_interval.is(set) ? int_interval.indexOf(set, x) : sorted_array.indexOf(set, x); }
function ordered_set_getAt(set, i) { return int_interval.is(set) ? int_interval.getAt(set, i) : set[i]; }
function ordered_set_min(set) { return int_interval.is(set) ? int_interval.min(set) : sorted_array.min(set); }
function ordered_set_max(set) { return int_interval.is(set) ? int_interval.max(set) : sorted_array.max(set); }
function ordered_set_start(set) { return int_interval.is(set) ? int_interval.start(set) : sorted_array.start(set); }
function ordered_set_end(set) { return int_interval.is(set) ? int_interval.end(set) : sorted_array.end(set); }
function ordered_set_hashCode(set) { return int_interval.is(set) ? int_interval.hashCode(set) : sorted_array.hashCode(set); }
// TODO: possibly add more hash functions to allow for multilevel hashing.
function ordered_set_toString(set) { return int_interval.is(set) ? int_interval.toString(set) : sorted_array.toString(set); }
function ordered_set_areEqual(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return int_interval.areEqual(a, b);
        return areEqualIS(a, b);
    }
    else if (int_interval.is(b))
        return areEqualIS(b, a);
    return sorted_array.areEqual(a, b);
}
function ordered_set_areIntersecting(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return int_interval.areIntersecting(a, b);
        return areIntersectingSI(b, a);
    }
    else if (int_interval.is(b))
        return areIntersectingSI(a, b);
    return sorted_array.areIntersecting(a, b);
}
/** Check if the 2nd argument is a subset of the 1st */
function ordered_set_isSubset(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return int_interval.isSubInterval(a, b);
        return isSubsetIS(a, b);
    }
    else if (int_interval.is(b))
        return isSubsetSI(a, b);
    return sorted_array.isSubset(a, b);
}
function ordered_set_findPredecessorIndex(set, x) {
    return int_interval.is(set) ? int_interval.findPredecessorIndex(set, x) : sorted_array.findPredecessorIndex(set, x);
}
function ordered_set_findPredecessorIndexInInterval(set, x, bounds) {
    return int_interval.is(set) ? int_interval.findPredecessorIndexInInterval(set, x, bounds) : sorted_array.findPredecessorIndexInInterval(set, x, bounds);
}
function ordered_set_findRange(set, min, max) {
    return int_interval.is(set) ? int_interval.findRange(set, min, max) : sorted_array.findRange(set, min, max);
}
function ordered_set_intersectionSize(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return int_interval.intersectionSize(a, b);
        return intersectionSizeSI(b, a);
    }
    else if (int_interval.is(b))
        return intersectionSizeSI(a, b);
    return sorted_array.intersectionSize(a, b);
}
function ordered_set_union(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return unionII(a, b);
        return unionSI(b, a);
    }
    else if (int_interval.is(b))
        return unionSI(a, b);
    return ordered_set_ofSortedArray(sorted_array.union(a, b));
}
function ordered_set_intersect(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return int_interval.intersect(a, b);
        return intersectSI(b, a);
    }
    else if (int_interval.is(b))
        return intersectSI(a, b);
    return ordered_set_ofSortedArray(sorted_array.intersect(a, b));
}
function ordered_set_subtract(a, b) {
    if (int_interval.is(a)) {
        if (int_interval.is(b))
            return subtractII(a, b);
        return subtractIS(a, b);
    }
    else if (int_interval.is(b))
        return subtractSI(a, b);
    return ordered_set_ofSortedArray(sorted_array.subtract(a, b));
}
function areEqualIS(a, b) { return int_interval.size(a) === sorted_array.size(b) && int_interval.start(a) === sorted_array.start(b) && int_interval.end(a) === sorted_array.end(b); }
function areIntersectingSI(a, b) {
    return a.length !== 0 && int_interval.size(sorted_array.findRange(a, int_interval.min(b), int_interval.max(b))) !== 0;
}
function isSubsetSI(a, b) {
    var minB = int_interval.min(b), maxB = int_interval.max(b);
    if (maxB - minB + 1 === 0)
        return true;
    var minA = sorted_array.min(a), maxA = sorted_array.max(a);
    if (minB < minA || maxB > maxA)
        return false;
    var r = sorted_array.findRange(a, minB, maxB);
    return int_interval.size(r) === int_interval.size(b);
}
function isSubsetIS(a, b) {
    var minA = int_interval.min(a), maxA = int_interval.max(a);
    if (maxA - minA + 1 === 0)
        return false;
    var minB = sorted_array.min(b), maxB = sorted_array.max(b);
    return minB >= minA && maxB <= maxA;
}
function areRangesIntersecting(a, b) {
    var sa = ordered_set_size(a), sb = ordered_set_size(b);
    if (sa === 0 && sb === 0)
        return true;
    return sa > 0 && sb > 0 && ordered_set_max(a) >= ordered_set_min(b) && ordered_set_min(a) <= ordered_set_max(b);
}
function isRangeSubset(a, b) {
    if (!ordered_set_size(a))
        return ordered_set_size(b) === 0;
    if (!ordered_set_size(b))
        return true;
    return ordered_set_min(a) <= ordered_set_min(b) && ordered_set_max(a) >= ordered_set_max(b);
}
function unionII(a, b) {
    if (int_interval.areEqual(a, b))
        return a;
    var sizeA = int_interval.size(a), sizeB = int_interval.size(b);
    if (!sizeB)
        return a;
    if (!sizeA)
        return b;
    var minA = int_interval.min(a), minB = int_interval.min(b);
    if (areRangesIntersecting(a, b))
        return int_interval.ofRange(Math.min(minA, minB), Math.max(int_interval.max(a), int_interval.max(b)));
    var lSize, lMin, rSize, rMin;
    if (minA < minB) {
        lSize = sizeA;
        lMin = minA;
        rSize = sizeB;
        rMin = minB;
    }
    else {
        lSize = sizeB;
        lMin = minB;
        rSize = sizeA;
        rMin = minA;
    }
    var arr = new Int32Array(sizeA + sizeB);
    for (var i = 0; i < lSize; i++)
        arr[i] = i + lMin;
    for (var i = 0; i < rSize; i++)
        arr[i + lSize] = i + rMin;
    return ordered_set_ofSortedArray(arr);
}
function unionSI(a, b) {
    var bSize = int_interval.size(b);
    if (!bSize)
        return a;
    // is the array fully contained in the range?
    if (isRangeSubset(b, a))
        return b;
    var min = int_interval.min(b), max = int_interval.max(b);
    var r = sorted_array.findRange(a, min, max);
    var start = int_interval.start(r), end = int_interval.end(r);
    var indices = new Int32Array(start + (a.length - end) + bSize);
    var offset = 0;
    for (var i = 0; i < start; i++)
        indices[offset++] = a[i];
    for (var i = min; i <= max; i++)
        indices[offset++] = i;
    for (var i = end, _i = a.length; i < _i; i++)
        indices[offset++] = a[i];
    return ordered_set_ofSortedArray(indices);
}
function intersectionSizeSI(a, b) {
    if (!int_interval.size(b))
        return 0;
    var r = sorted_array.findRange(a, int_interval.min(b), int_interval.max(b));
    return int_interval.end(r) - int_interval.start(r);
}
function intersectSI(a, b) {
    if (!int_interval.size(b))
        return ordered_set_Empty;
    var r = sorted_array.findRange(a, int_interval.min(b), int_interval.max(b));
    var start = int_interval.start(r), end = int_interval.end(r);
    var resultSize = end - start;
    if (!resultSize)
        return ordered_set_Empty;
    if (resultSize === a.length)
        return a;
    var indices = new Int32Array(resultSize);
    var offset = 0;
    for (var i = start; i < end; i++) {
        indices[offset++] = a[i];
    }
    return ordered_set_ofSortedArray(indices);
}
function subtractII(a, b) {
    if (int_interval.areEqual(a, b))
        return ordered_set_Empty;
    if (!int_interval.areIntersecting(a, b))
        return a;
    var minA = int_interval.min(a), maxA = int_interval.max(a);
    var minB = int_interval.min(b), maxB = int_interval.max(b);
    if (maxA < minA || maxB < minB)
        return a;
    // is A subset of B? ==> Empty
    if (int_interval.isSubInterval(b, a))
        return ordered_set_Empty;
    if (int_interval.isSubInterval(a, b)) {
        // this splits the interval into two, gotta represent it as a set.
        var l = minB - minA, r = maxA - maxB;
        if (l <= 0)
            return int_interval.ofRange(maxB + 1, maxB + r);
        if (r <= 0)
            return int_interval.ofRange(minA, minA + l - 1);
        var ret = new Int32Array(l + r);
        var offset = 0;
        for (var i = 0; i < l; i++)
            ret[offset++] = minA + i;
        for (var i = 1; i <= r; i++)
            ret[offset++] = maxB + i;
        return ordered_set_ofSortedArray(ret);
    }
    if (minA < minB)
        return int_interval.ofRange(minA, minB - 1);
    return int_interval.ofRange(maxB + 1, maxA);
}
function subtractSI(a, b) {
    var min = int_interval.min(b), max = int_interval.max(b);
    // is empty?
    if (max < min)
        return a;
    var r = sorted_array.findRange(a, min, max);
    var start = int_interval.start(r), end = int_interval.end(r);
    var resultSize = a.length - (end - start);
    // A is subset of B
    if (resultSize <= 0)
        return ordered_set_Empty;
    // No common elements
    if (resultSize === a.length)
        return a;
    var ret = new Int32Array(resultSize);
    var offset = 0;
    for (var i = 0; i < start; i++)
        ret[offset++] = a[i];
    for (var i = end, _i = a.length; i < _i; i++)
        ret[offset++] = a[i];
    return ordered_set_ofSortedArray(ret);
}
function subtractIS(a, b) {
    var min = int_interval.min(a), max = int_interval.max(a);
    // is empty?
    if (max < min)
        return a;
    var rSize = max - min + 1;
    var interval = sorted_array.findRange(b, min, max);
    var start = int_interval.start(interval), end = int_interval.end(interval);
    var commonCount = end - start;
    // No common elements.
    if (commonCount === 0)
        return a;
    var resultSize = rSize - commonCount;
    // A is subset of B
    if (resultSize <= 0)
        return ordered_set_Empty;
    var ret = new Int32Array(resultSize);
    var li = b.length - 1;
    var fst = b[Math.min(start, li)], last = b[Math.min(end, li)];
    var offset = 0;
    for (var i = min; i < fst; i++)
        ret[offset++] = i;
    for (var i = fst; i <= last; i++) {
        if (sorted_array.indexOfInInterval(b, i, interval) < 0)
            ret[offset++] = i;
    }
    for (var i = last + 1; i <= max; i++)
        ret[offset++] = i;
    return ordered_set_ofSortedArray(ret);
}
function ordered_set_forEach(set, f, ctx) {
    if (int_interval.is(set)) {
        var start_1 = int_interval.min(set);
        for (var i = start_1, _i = int_interval.max(set); i <= _i; i++) {
            f(i, i - start_1, ctx);
        }
    }
    else {
        for (var i = 0, _i = set.length; i < _i; i++) {
            f(set[i], i, ctx);
        }
    }
    return ctx;
}
function ordered_set_forEachSegment(set, segment, f, ctx) {
    if (int_interval.is(set)) {
        var sI = 0;
        for (var i = int_interval.min(set), _i = int_interval.max(set); i <= _i; i++) {
            var s = segment(i);
            var endI = i + 1;
            while (endI < _i && segment(endI) === s)
                endI++;
            i = endI - 1;
            f(s, sI, ctx);
            sI++;
        }
    }
    else {
        var sI = 0;
        for (var i = 0, _i = set.length; i < _i; i++) {
            var s = segment(set[i]);
            var endI = i + 1;
            while (endI < _i && segment(set[endI]) === s)
                endI++;
            i = endI - 1;
            f(s, sI, ctx);
            sI++;
        }
    }
    return ctx;
}
function indexedIntersect(idxA, a, b) {
    if (a === b)
        return idxA;
    var lenI = ordered_set_size(idxA), lenA = a.length, lenB = b.length;
    if (lenI === 0 || lenA === 0 || lenB === 0)
        return ordered_set_Empty;
    var startJ = sorted_array.findPredecessorIndex(b, a[ordered_set_min(idxA)]);
    var endJ = sorted_array.findPredecessorIndex(b, a[ordered_set_max(idxA)] + 1);
    var commonCount = 0;
    var offset = 0;
    var O = 0;
    var j = startJ;
    while (O < lenI && j < endJ) {
        var x = a[ordered_set_getAt(idxA, O)], y = b[j];
        if (x < y) {
            O++;
        }
        else if (x > y) {
            j++;
        }
        else {
            commonCount++;
            O++;
            j++;
        }
    }
    // no common elements
    if (commonCount === 0)
        return ordered_set_Empty;
    // A === B
    if (commonCount === lenA && commonCount === lenB)
        return idxA;
    var indices = new Int32Array(commonCount);
    offset = 0;
    O = 0;
    j = startJ;
    while (O < lenI && j < endJ) {
        var x = a[ordered_set_getAt(idxA, O)], y = b[j];
        if (x < y) {
            O++;
        }
        else if (x > y) {
            j++;
        }
        else {
            indices[offset++] = j;
            O++;
            j++;
        }
    }
    return ordered_set_ofSortedArray(indices);
}
//# sourceMappingURL=ordered-set.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/ordered-set.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var ordered_set_OrderedSet;
(function (OrderedSet) {
    OrderedSet.Empty = ordered_set_Empty;
    OrderedSet.ofSingleton = ordered_set_ofSingleton;
    /** Create interval from range [min, max] */
    OrderedSet.ofRange = ordered_set_ofRange;
    /** Create interval from bounds [start, end), i.e. [start, end - 1] */
    OrderedSet.ofBounds = ordered_set_ofBounds;
    /** It is the responsibility of the caller to ensure the array is sorted and contains unique values. */
    OrderedSet.ofSortedArray = ordered_set_ofSortedArray;
    OrderedSet.has = ordered_set_has;
    /** Returns the index of `x` in `set` or -1 if not found. */
    OrderedSet.indexOf = ordered_set_indexOf;
    /** Returns the value in `set` at index `i`. */
    OrderedSet.getAt = ordered_set_getAt;
    OrderedSet.min = ordered_set_min;
    OrderedSet.max = ordered_set_max;
    OrderedSet.start = ordered_set_start;
    OrderedSet.end = ordered_set_end;
    /** Number of elements in the OrderedSet */
    OrderedSet.size = ordered_set_size;
    OrderedSet.hashCode = ordered_set_hashCode;
    OrderedSet.areEqual = ordered_set_areEqual;
    OrderedSet.areIntersecting = ordered_set_areIntersecting;
    /** Check if the 2nd argument is a subset of the 1st */
    OrderedSet.isSubset = ordered_set_isSubset;
    OrderedSet.union = ordered_set_union;
    OrderedSet.intersect = ordered_set_intersect;
    OrderedSet.indexedIntersect = indexedIntersect;
    /** Returns elements of `a` that are not in `b`, i.e `a` - `b` */
    OrderedSet.subtract = ordered_set_subtract;
    /**
     * Returns 0 if `x` is smaller or equal the first element of `set`
     * Returns length of `set` if `x` is bigger than the last element of `set`
     * Otherwise returns the first index where the value of `set` is equal or bigger than `x`
     */
    OrderedSet.findPredecessorIndex = ordered_set_findPredecessorIndex;
    OrderedSet.findPredecessorIndexInInterval = ordered_set_findPredecessorIndexInInterval;
    OrderedSet.findRange = ordered_set_findRange;
    OrderedSet.intersectionSize = ordered_set_intersectionSize;
    function forEach(set, f, ctx) {
        return ordered_set_forEach(set, f, ctx);
    }
    OrderedSet.forEach = forEach;
    function forEachSegment(set, segment, f, ctx) {
        return ordered_set_forEachSegment(set, segment, f, ctx);
    }
    OrderedSet.forEachSegment = forEachSegment;
    function isInterval(set) {
        return int_interval.is(set);
    }
    OrderedSet.isInterval = isInterval;
    function isSortedArray(set) {
        return !int_interval.is(set);
    }
    OrderedSet.isSortedArray = isSortedArray;
    function toArray(set) {
        var array = [];
        OrderedSet.forEach(set, function (v) { return array.push(v); });
        return array;
    }
    OrderedSet.toArray = toArray;
    function toString(set) {
        return ordered_set_toString(set);
    }
    OrderedSet.toString = toString;
})(ordered_set_OrderedSet || (ordered_set_OrderedSet = {}));
/* harmony default export */ var ordered_set = (ordered_set_OrderedSet);
//# sourceMappingURL=ordered-set.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/impl/segmentation.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



function segmentation_create(values) {
    var offsets = sorted_array.ofSortedArray(values);
    var max = sorted_array.max(offsets);
    var index = new Int32Array(max);
    for (var i = 0, _i = values.length - 1; i < _i; i++) {
        for (var j = values[i], _j = values[i + 1]; j < _j; j++) {
            index[j] = i;
        }
    }
    return { offsets: offsets, index: index, count: values.length - 1 };
}
function ofOffsets(offsets, bounds) {
    var s = int_interval.start(bounds);
    var segments = new Int32Array(offsets.length + 1);
    for (var i = 0, _i = offsets.length; i < _i; i++) {
        segments[i] = offsets[i] - s;
    }
    segments[offsets.length] = int_interval.end(bounds) - s;
    return segmentation_create(segments);
}
/** Get number of segments in a segmentation */
function count(_a) {
    var count = _a.count;
    return count;
}
function getSegment(_a, value) {
    var index = _a.index;
    return index[value];
}
function projectValue(_a, set, value) {
    var offsets = _a.offsets;
    var last = ordered_set.max(offsets);
    var idx = value >= last ? -1 : ordered_set.findPredecessorIndex(offsets, value - 1);
    return ordered_set.findRange(set, ordered_set.getAt(offsets, idx), ordered_set.getAt(offsets, idx + 1) - 1);
}
var segmentation_SegmentIterator = /** @class */ (function () {
    function SegmentIterator(segments, segmentMap, set, inputRange) {
        this.segments = segments;
        this.segmentMap = segmentMap;
        this.set = set;
        this.segmentMin = 0;
        this.segmentMax = 0;
        this.setRange = int_interval.Empty;
        this.value = { index: 0, start: 0, end: 0 };
        this.hasNext = false;
        this.setRange = inputRange;
        this.updateSegmentRange();
    }
    SegmentIterator.prototype.move = function () {
        while (this.hasNext) {
            if (this.updateValue()) {
                this.value.index = this.segmentMin++;
                this.hasNext = this.segmentMax >= this.segmentMin && int_interval.size(this.setRange) > 0;
                break;
            }
            else {
                this.updateSegmentRange();
            }
        }
        return this.value;
    };
    SegmentIterator.prototype.updateValue = function () {
        var segmentEnd = this.segments[this.segmentMin + 1];
        // TODO: add optimized version for interval and array?
        var setEnd = ordered_set.findPredecessorIndexInInterval(this.set, segmentEnd, this.setRange);
        this.value.start = int_interval.start(this.setRange);
        this.value.end = setEnd;
        this.setRange = int_interval.ofBounds(setEnd, int_interval.end(this.setRange));
        return setEnd > this.value.start;
    };
    SegmentIterator.prototype.updateSegmentRange = function () {
        var sMin = int_interval.min(this.setRange), sMax = int_interval.max(this.setRange);
        if (sMax < sMin) {
            this.hasNext = false;
            return;
        }
        this.segmentMin = this.segmentMap[ordered_set.getAt(this.set, sMin)];
        this.segmentMax = this.segmentMap[ordered_set.getAt(this.set, sMax)];
        this.hasNext = this.segmentMax >= this.segmentMin;
    };
    SegmentIterator.prototype.setSegment = function (segment) {
        this.setRange = int_interval.ofBounds(segment.start, segment.end);
        this.updateSegmentRange();
    };
    return SegmentIterator;
}());

function segmentation_segments(segs, set, segment) {
    var int = typeof segment !== 'undefined' ? int_interval.ofBounds(segment.start, segment.end) : int_interval.ofBounds(0, ordered_set.size(set));
    return new segmentation_SegmentIterator(segs.offsets, segs.index, set, int);
}
//# sourceMappingURL=segmentation.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/segmentation.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var segmentation_Segmentation;
(function (Segmentation) {
    Segmentation.create = segmentation_create;
    Segmentation.ofOffsets = ofOffsets;
    Segmentation.count = count;
    Segmentation.getSegment = getSegment;
    Segmentation.projectValue = projectValue;
    /** Segment iterator that mutates a single segment object to mark all the segments. */
    Segmentation.transientSegments = segmentation_segments;
})(segmentation_Segmentation || (segmentation_Segmentation = {}));
/* harmony default export */ var segmentation = (segmentation_Segmentation);
//# sourceMappingURL=segmentation.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/linked-index.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function LinkedIndex(size) {
    return new LinkedIndexImpl(size);
}
var LinkedIndexImpl = /** @class */ (function () {
    function LinkedIndexImpl(size) {
        this.head = size > 0 ? 0 : -1;
        this.prev = new Int32Array(size);
        this.next = new Int32Array(size);
        for (var i = 0; i < size; i++) {
            this.next[i] = i + 1;
            this.prev[i] = i - 1;
        }
        this.prev[0] = -1;
        this.next[size - 1] = -1;
    }
    LinkedIndexImpl.prototype.remove = function (i) {
        var _a = this, prev = _a.prev, next = _a.next;
        var p = prev[i], n = next[i];
        if (p >= 0) {
            next[p] = n;
            prev[i] = -1;
        }
        if (n >= 0) {
            prev[n] = p;
            next[i] = -1;
        }
        if (i === this.head) {
            if (p < 0)
                this.head = n;
            else
                this.head = p;
        }
    };
    LinkedIndexImpl.prototype.has = function (i) {
        return this.prev[i] >= 0 || this.next[i] >= 0 || this.head === i;
    };
    return LinkedIndexImpl;
}());
/* harmony default export */ var linked_index = (LinkedIndex);
//# sourceMappingURL=linked-index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int/map.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var map_IntMap;
(function (IntMap) {
    IntMap.Empty = new Map();
    function keyArray(map) {
        return Object(util["n" /* iterableToArray */])(map.keys());
    }
    IntMap.keyArray = keyArray;
    function Mutable() {
        return new Map();
    }
    IntMap.Mutable = Mutable;
    function asImmutable(map) {
        return map;
    }
    IntMap.asImmutable = asImmutable;
    function copy(map) {
        var ret = Mutable();
        var it = map.keys();
        while (true) {
            var _a = it.next(), done = _a.done, value = _a.value;
            if (done)
                break;
            ret.set(value, map.get(value));
        }
        return ret;
    }
    IntMap.copy = copy;
    function addFrom(map, src) {
        var it = src.keys();
        while (true) {
            var _a = it.next(), done = _a.done, value = _a.value;
            if (done)
                break;
            map.set(value, src.get(value));
        }
        return map;
    }
    IntMap.addFrom = addFrom;
})(map_IntMap || (map_IntMap = {}));
/* harmony default export */ var int_map = (map_IntMap);
//# sourceMappingURL=map.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/iterator.js
var iterator = __webpack_require__(290);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/int.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */









//# sourceMappingURL=int.js.map

/***/ }),
/* 7 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Database", function() { return /* reexport */ db_database; });
__webpack_require__.d(__webpack_exports__, "Table", function() { return /* reexport */ db_table; });
__webpack_require__.d(__webpack_exports__, "Column", function() { return /* reexport */ db_column; });
__webpack_require__.d(__webpack_exports__, "ColumnHelpers", function() { return /* reexport */ column_helpers; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db/column-helpers.js
var column_helpers = __webpack_require__(186);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/number-parser.js
var number_parser = __webpack_require__(97);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/db/column.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var column_Column;
(function (Column) {
    var Schema;
    (function (Schema) {
        // T also serves as a default value for undefined columns
        Schema.str = { '@type': 'str', T: '', valueType: 'str' };
        Schema.int = { '@type': 'int', T: 0, valueType: 'int' };
        Schema.coord = { '@type': 'coord', T: 0, valueType: 'float' };
        Schema.float = { '@type': 'float', T: 0, valueType: 'float' };
        function Str(defaultValue) {
            if (defaultValue === void 0) { defaultValue = ''; }
            return { '@type': 'str', T: defaultValue, valueType: 'str' };
        }
        Schema.Str = Str;
        ;
        function Int(defaultValue) {
            if (defaultValue === void 0) { defaultValue = 0; }
            return { '@type': 'int', T: defaultValue, valueType: 'int' };
        }
        Schema.Int = Int;
        ;
        function Float(defaultValue) {
            if (defaultValue === void 0) { defaultValue = 0; }
            return { '@type': 'float', T: defaultValue, valueType: 'float' };
        }
        Schema.Float = Float;
        ;
        function Tensor(space, baseType) {
            if (baseType === void 0) { baseType = Schema.float; }
            return { '@type': 'tensor', T: space.create(), space: space, valueType: 'tensor', baseType: baseType };
        }
        Schema.Tensor = Tensor;
        function Vector(dim, baseType) {
            if (baseType === void 0) { baseType = Schema.float; }
            return Tensor(linear_algebra["Tensor"].Vector(dim, baseType['@type'] === 'int' ? Int32Array : Float64Array), baseType);
        }
        Schema.Vector = Vector;
        function Matrix(rows, cols, baseType) {
            if (baseType === void 0) { baseType = Schema.float; }
            return Tensor(linear_algebra["Tensor"].ColumnMajorMatrix(rows, cols, baseType['@type'] === 'int' ? Int32Array : Float64Array), baseType);
        }
        Schema.Matrix = Matrix;
        function Aliased(t, defaultValue) {
            if (typeof defaultValue !== 'undefined')
                return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, t), { T: defaultValue });
            return t;
        }
        Schema.Aliased = Aliased;
        function List(separator, itemParse, defaultValue) {
            if (defaultValue === void 0) { defaultValue = []; }
            return { '@type': 'list', T: defaultValue, separator: separator, itemParse: itemParse, valueType: 'list' };
        }
        Schema.List = List;
    })(Schema = Column.Schema || (Column.Schema = {}));
    function is(v) {
        return !!v && !!v.schema && !!v.value;
    }
    Column.is = is;
    function Undefined(rowCount, schema) {
        return constColumn(schema['T'], rowCount, schema, 1 /* NotPresent */);
    }
    Column.Undefined = Undefined;
    function ofConst(v, rowCount, type) {
        return constColumn(v, rowCount, type, 0 /* Present */);
    }
    Column.ofConst = ofConst;
    function ofLambda(spec) {
        return lambdaColumn(spec);
    }
    Column.ofLambda = ofLambda;
    /** values [min, max] (i.e. include both values) */
    function range(min, max) {
        return ofLambda({
            value: function (i) { return i + min; },
            rowCount: Math.max(max - min + 1, 0),
            schema: Schema.int
        });
    }
    Column.range = range;
    function ofArray(spec) {
        return arrayColumn(spec);
    }
    Column.ofArray = ofArray;
    function ofIntArray(array) {
        return arrayColumn({ array: array, schema: Schema.int });
    }
    Column.ofIntArray = ofIntArray;
    function ofFloatArray(array) {
        return arrayColumn({ array: array, schema: Schema.float });
    }
    Column.ofFloatArray = ofFloatArray;
    function ofStringArray(array) {
        return arrayColumn({ array: array, schema: Schema.str });
    }
    Column.ofStringArray = ofStringArray;
    function ofStringAliasArray(array) {
        return arrayColumn({ array: array, schema: Schema.Aliased(Schema.str) });
    }
    Column.ofStringAliasArray = ofStringAliasArray;
    function ofStringListArray(array, separator) {
        if (separator === void 0) { separator = ','; }
        return arrayColumn({ array: array, schema: Schema.List(separator, function (x) { return x; }) });
    }
    Column.ofStringListArray = ofStringListArray;
    function ofIntTokens(tokens) {
        var count = tokens.count, data = tokens.data, indices = tokens.indices;
        return lambdaColumn({
            value: function (row) { return Object(number_parser["d" /* parseInt */])(data, indices[2 * row], indices[2 * row + 1]) || 0; },
            rowCount: count,
            schema: Schema.int,
        });
    }
    Column.ofIntTokens = ofIntTokens;
    function ofFloatTokens(tokens) {
        var count = tokens.count, data = tokens.data, indices = tokens.indices;
        return lambdaColumn({
            value: function (row) { return Object(number_parser["b" /* parseFloat */])(data, indices[2 * row], indices[2 * row + 1]) || 0; },
            rowCount: count,
            schema: Schema.float,
        });
    }
    Column.ofFloatTokens = ofFloatTokens;
    function ofStringTokens(tokens) {
        var count = tokens.count, data = tokens.data, indices = tokens.indices;
        return lambdaColumn({
            value: function (row) {
                var ret = data.substring(indices[2 * row], indices[2 * row + 1]);
                if (ret === '.' || ret === '?')
                    return '';
                return ret;
            },
            rowCount: count,
            schema: Schema.str,
        });
    }
    Column.ofStringTokens = ofStringTokens;
    function window(column, start, end) {
        return windowColumn(column, start, end);
    }
    Column.window = window;
    function view(column, indices, checkIndentity) {
        if (checkIndentity === void 0) { checkIndentity = true; }
        return columnView(column, indices, checkIndentity);
    }
    Column.view = view;
    /** A map of the 1st occurence of each value. */
    function createFirstIndexMap(column) {
        return createFirstIndexMapOfColumn(column);
    }
    Column.createFirstIndexMap = createFirstIndexMap;
    function createIndexer(column) {
        return createIndexerOfColumn(column);
    }
    Column.createIndexer = createIndexer;
    function mapToArray(column, f, ctor) {
        return mapToArrayImpl(column, f, ctor || Array);
    }
    Column.mapToArray = mapToArray;
    function areEqual(a, b) {
        return areColumnsEqual(a, b);
    }
    Column.areEqual = areEqual;
    function indicesOf(c, test) {
        return columnIndicesOf(c, test);
    }
    Column.indicesOf = indicesOf;
    /** Makes the column backed by an array. Useful for columns that are accessed often. */
    function asArrayColumn(c, array) {
        if (c.__array)
            return c;
        if (!c.isDefined)
            return Undefined(c.rowCount, c.schema);
        return arrayColumn({ array: c.toArray({ array: array }), schema: c.schema, valueKind: c.valueKind });
    }
    Column.asArrayColumn = asArrayColumn;
    function copyToArray(c, array, offset) {
        if (offset === void 0) { offset = 0; }
        if (!c.isDefined)
            return;
        var cArray = c.__array;
        if (cArray) {
            for (var i = 0, _i = cArray.length; i < _i; i++)
                array[offset + i] = cArray[i];
        }
        else {
            for (var i = 0, _i = c.rowCount; i < _i; i++)
                array[offset + i] = c.value(i);
        }
    }
    Column.copyToArray = copyToArray;
    function isIdentity(c) {
        for (var i = 0, _i = c.rowCount; i < _i; i++) {
            if (i !== c.value(i))
                return false;
        }
        return true;
    }
    Column.isIdentity = isIdentity;
})(column_Column || (column_Column = {}));
/* harmony default export */ var db_column = (column_Column);
function createFirstIndexMapOfColumn(c) {
    var map = new Map();
    for (var i = 0, _i = c.rowCount; i < _i; i++) {
        var v = c.value(i);
        if (!map.has(v))
            map.set(c.value(i), i);
    }
    return map;
}
function createIndexerOfColumn(c) {
    var map = new Map();
    for (var i = 0, _i = c.rowCount; i < _i; i++) {
        var v = c.value(i);
        if (!map.has(v))
            map.set(c.value(i), i);
    }
    return function (v) { return map.has(v) ? map.get(v) : -1; };
}
function constColumn(v, rowCount, schema, valueKind) {
    var value = function (row) { return v; };
    return {
        schema: schema,
        __array: void 0,
        isDefined: valueKind === 0 /* Present */,
        rowCount: rowCount,
        value: value,
        valueKind: function (row) { return valueKind; },
        toArray: function (params) {
            var array = column_helpers["createArray"](rowCount, params).array;
            for (var i = 0, _i = array.length; i < _i; i++)
                array[i] = v;
            return array;
        },
        areValuesEqual: function (rowA, rowB) { return true; }
    };
}
function lambdaColumn(_a) {
    var value = _a.value, valueKind = _a.valueKind, areValuesEqual = _a.areValuesEqual, rowCount = _a.rowCount, schema = _a.schema;
    return {
        schema: schema,
        __array: void 0,
        isDefined: true,
        rowCount: rowCount,
        value: value,
        valueKind: valueKind ? valueKind : function (row) { return 0 /* Present */; },
        toArray: function (params) {
            var _a = column_helpers["createArray"](rowCount, params), array = _a.array, start = _a.start;
            for (var i = 0, _i = array.length; i < _i; i++)
                array[i] = value(i + start);
            return array;
        },
        areValuesEqual: areValuesEqual ? areValuesEqual : function (rowA, rowB) { return value(rowA) === value(rowB); }
    };
}
function arrayColumn(_a) {
    var array = _a.array, schema = _a.schema, valueKind = _a.valueKind;
    var rowCount = array.length;
    var value = schema.valueType === 'str'
        ? function (row) { var v = array[row]; return typeof v === 'string' ? v : '' + v; }
        : function (row) { return array[row]; };
    var isTyped = column_helpers["isTypedArray"](array);
    return {
        schema: schema,
        __array: array,
        isDefined: true,
        rowCount: rowCount,
        value: value,
        valueKind: valueKind ? valueKind : function (row) { return 0 /* Present */; },
        toArray: schema.valueType === 'str'
            ? function (params) {
                var _a = column_helpers["getArrayBounds"](rowCount, params), start = _a.start, end = _a.end;
                var ret = new (params && typeof params.array !== 'undefined' ? params.array : array.constructor)(end - start);
                for (var i = 0, _i = end - start; i < _i; i++) {
                    var v = array[start + i];
                    ret[i] = typeof v === 'string' ? v : '' + v;
                }
                return ret;
            }
            : isTyped
                ? function (params) { return column_helpers["typedArrayWindow"](array, params); }
                : function (params) {
                    var _a = column_helpers["getArrayBounds"](rowCount, params), start = _a.start, end = _a.end;
                    if (start === 0 && end === array.length)
                        return array;
                    var ret = new (params && typeof params.array !== 'undefined' ? params.array : array.constructor)(end - start);
                    for (var i = 0, _i = end - start; i < _i; i++)
                        ret[i] = array[start + i];
                    return ret;
                },
        areValuesEqual: function (rowA, rowB) { return array[rowA] === array[rowB]; }
    };
}
function windowColumn(column, start, end) {
    if (!column.isDefined)
        return column_Column.Undefined(end - start, column.schema);
    if (start === 0 && end === column.rowCount)
        return column;
    if (!!column.__array && column_helpers["isTypedArray"](column.__array))
        return windowTyped(column, start, end);
    return windowFull(column, start, end);
}
function windowTyped(c, start, end) {
    var array = column_helpers["typedArrayWindow"](c.__array, { start: start, end: end });
    var vk = c.valueKind;
    return arrayColumn({ array: array, schema: c.schema, valueKind: function (row) { return vk(start + row); } });
}
function windowFull(c, start, end) {
    var v = c.value, vk = c.valueKind, ave = c.areValuesEqual;
    var value = start === 0 ? v : function (row) { return v(row + start); };
    var rowCount = end - start;
    return {
        schema: c.schema,
        __array: void 0,
        isDefined: c.isDefined,
        rowCount: rowCount,
        value: value,
        valueKind: start === 0 ? vk : function (row) { return vk(row + start); },
        toArray: function (params) {
            var array = column_helpers["createArray"](rowCount, params).array;
            for (var i = 0, _i = array.length; i < _i; i++)
                array[i] = v(i + start);
            return array;
        },
        areValuesEqual: start === 0 ? ave : function (rowA, rowB) { return ave(rowA + start, rowB + start); }
    };
}
function column_isIdentity(map, rowCount) {
    if (map.length !== rowCount)
        return false;
    for (var i = 0, _i = map.length; i < _i; i++) {
        if (map[i] !== i)
            return false;
    }
    return true;
}
function columnView(c, map, checkIdentity) {
    if (!c.isDefined || c.rowCount === 0)
        return c;
    if (checkIdentity && column_isIdentity(map, c.rowCount))
        return c;
    if (!!c.__array && typeof c.value(0) === typeof c.__array[0])
        return arrayView(c, map);
    return viewFull(c, map);
}
function arrayView(c, map) {
    var array = c.__array;
    var ret = new array.constructor(map.length);
    for (var i = 0, _i = map.length; i < _i; i++)
        ret[i] = array[map[i]];
    var vk = c.valueKind;
    return arrayColumn({ array: ret, schema: c.schema, valueKind: function (row) { return vk(map[row]); } });
}
function viewFull(c, map) {
    var v = c.value, vk = c.valueKind, ave = c.areValuesEqual;
    var value = function (row) { return v(map[row]); };
    var rowCount = map.length;
    return {
        schema: c.schema,
        __array: void 0,
        isDefined: c.isDefined,
        rowCount: rowCount,
        value: value,
        valueKind: function (row) { return vk(map[row]); },
        toArray: function (params) {
            var array = column_helpers["createArray"](rowCount, params).array;
            for (var i = 0, _i = array.length; i < _i; i++)
                array[i] = v(map[i]);
            return array;
        },
        areValuesEqual: function (rowA, rowB) { return ave(map[rowA], map[rowB]); }
    };
}
function mapToArrayImpl(c, f, ctor) {
    var ret = new ctor(c.rowCount);
    for (var i = 0, _i = c.rowCount; i < _i; i++)
        ret[i] = f(c.value(i));
    return ret;
}
function areColumnsEqual(a, b) {
    if (a === b)
        return true;
    if (a.rowCount !== b.rowCount || a.isDefined !== b.isDefined || a.schema.valueType !== b.schema.valueType)
        return false;
    if (!!a.__array && !!b.__array)
        return areArraysEqual(a, b);
    return column_areValuesEqual(a, b);
}
function areArraysEqual(a, b) {
    var xs = a.__array, ys = b.__array;
    for (var i = 0, _i = a.rowCount; i < _i; i++) {
        if (xs[i] !== ys[i])
            return false;
    }
    return true;
}
function column_areValuesEqual(a, b) {
    var va = a.value, vb = b.value;
    for (var i = 0, _i = a.rowCount; i < _i; i++) {
        if (va(i) !== vb(i))
            return false;
    }
    return true;
}
function columnIndicesOf(c, test) {
    var ret = [], v = c.value;
    for (var i = 0, _i = c.rowCount; i < _i; i++) {
        if (test(v(i)))
            ret[ret.length] = i;
    }
    return ret;
}
//# sourceMappingURL=column.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util/sort.js
var util_sort = __webpack_require__(272);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/db/table.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




/** An immutable table */
var table_Table;
(function (Table) {
    function is(t) {
        return t && typeof t._rowCount === 'number' && !!t._columns && !!t._schema;
    }
    Table.is = is;
    function pickColumns(schema, table, guard) {
        if (guard === void 0) { guard = {}; }
        var ret = Object.create(null);
        var keys = Object.keys(schema);
        ret._rowCount = table._rowCount;
        ret._columns = keys;
        ret._schema = schema;
        for (var _a = 0, keys_1 = keys; _a < keys_1.length; _a++) {
            var k = keys_1[_a];
            if (!!table[k])
                ret[k] = table[k];
            else if (!!guard[k])
                ret[k] = guard[k];
            else
                throw Error("Cannot find column '" + k + "'.");
        }
        return ret;
    }
    Table.pickColumns = pickColumns;
    function ofColumns(schema, columns) {
        var _columns = Object.keys(columns);
        var _rowCount = columns[_columns[0]].rowCount;
        return Object(tslib_es6["__assign"])({ _rowCount: _rowCount, _columns: _columns, _schema: schema }, columns);
    }
    Table.ofColumns = ofColumns;
    function ofPartialColumns(schema, partialColumns, rowCount) {
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        for (var _a = 0, columns_1 = columns; _a < columns_1.length; _a++) {
            var k = columns_1[_a];
            if (k in partialColumns)
                ret[k] = partialColumns[k];
            else
                ret[k] = db_column.Undefined(rowCount, schema[k]);
        }
        return ret;
    }
    Table.ofPartialColumns = ofPartialColumns;
    function ofUndefinedColumns(schema, rowCount) {
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        for (var _a = 0, columns_2 = columns; _a < columns_2.length; _a++) {
            var k = columns_2[_a];
            ret[k] = db_column.Undefined(rowCount, schema[k]);
        }
        return ret;
    }
    Table.ofUndefinedColumns = ofUndefinedColumns;
    function ofRows(schema, rows) {
        var ret = Object.create(null);
        var rowCount = rows.length;
        var columns = Object.keys(schema);
        ret._rowCount = rowCount;
        ret._columns = columns;
        ret._schema = schema;
        var _loop_1 = function (k) {
            ret[k] = db_column.ofLambda({
                rowCount: rowCount,
                schema: schema[k],
                value: function (r) { return rows[r][k]; },
                valueKind: function (r) { return typeof rows[r][k] === 'undefined' ? 1 /* NotPresent */ : 0 /* Present */; }
            });
        };
        for (var _a = 0, columns_3 = columns; _a < columns_3.length; _a++) {
            var k = columns_3[_a];
            _loop_1(k);
        }
        return ret;
    }
    Table.ofRows = ofRows;
    function ofArrays(schema, arrays) {
        var _a;
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = 0;
        ret._columns = columns;
        ret._schema = schema;
        for (var _b = 0, columns_4 = columns; _b < columns_4.length; _b++) {
            var k = columns_4[_b];
            if (typeof arrays[k] !== 'undefined') {
                ret[k] = db_column.ofArray({ array: arrays[k], schema: schema[k] });
                ret._rowCount = (_a = arrays[k]) === null || _a === void 0 ? void 0 : _a.length;
            }
            else {
                ret[k] = db_column.Undefined(ret._rowCount, schema[k]);
            }
        }
        return ret;
    }
    Table.ofArrays = ofArrays;
    function view(table, schema, view) {
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = view.length;
        ret._columns = columns;
        ret._schema = schema;
        for (var _a = 0, columns_5 = columns; _a < columns_5.length; _a++) {
            var k = columns_5[_a];
            ret[k] = db_column.view(table[k], view);
        }
        return ret;
    }
    Table.view = view;
    function pick(table, schema, test) {
        var _view = [];
        for (var i = 0, il = table._rowCount; i < il; ++i) {
            if (test(i))
                _view.push(i);
        }
        return view(table, schema, _view);
    }
    Table.pick = pick;
    function window(table, schema, start, end) {
        if (start === 0 && end === table._rowCount)
            return table;
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = end - start;
        ret._columns = columns;
        ret._schema = schema;
        for (var _a = 0, columns_6 = columns; _a < columns_6.length; _a++) {
            var k = columns_6[_a];
            ret[k] = db_column.window(table[k], start, end);
        }
        return ret;
    }
    Table.window = window;
    function concat(tables, schema) {
        var ret = Object.create(null);
        var columns = Object.keys(schema);
        ret._rowCount = 0;
        for (var _a = 0, tables_1 = tables; _a < tables_1.length; _a++) {
            var table = tables_1[_a];
            ret._rowCount += table._rowCount;
        }
        var arrays = {};
        for (var _b = 0, columns_7 = columns; _b < columns_7.length; _b++) {
            var column = columns_7[_b];
            arrays[column] = new Array(ret._rowCount);
        }
        ret._columns = columns;
        ret._schema = schema;
        var offset = 0;
        for (var _c = 0, tables_2 = tables; _c < tables_2.length; _c++) {
            var table = tables_2[_c];
            for (var _d = 0, columns_8 = columns; _d < columns_8.length; _d++) {
                var k = columns_8[_d];
                db_column.copyToArray(table[k], arrays[k], offset);
            }
            offset += table._rowCount;
        }
        for (var _e = 0, columns_9 = columns; _e < columns_9.length; _e++) {
            var k = columns_9[_e];
            ret[k] = db_column.ofArray({ array: arrays[k], schema: schema[k] });
        }
        return ret;
    }
    Table.concat = concat;
    function columnToArray(table, name, array) {
        table[name] = db_column.asArrayColumn(table[name], array);
    }
    Table.columnToArray = columnToArray;
    /** Sort and return a new table */
    function sort(table, cmp) {
        var indices = new Int32Array(table._rowCount);
        for (var i = 0, _i = indices.length; i < _i; i++)
            indices[i] = i;
        Object(util_sort["c" /* sortArray */])(indices, function (_, i, j) { return cmp(i, j); });
        var isIdentity = true;
        for (var i = 0, _i = indices.length; i < _i; i++) {
            if (indices[i] !== i) {
                isIdentity = false;
                break;
            }
        }
        if (isIdentity)
            return table;
        var ret = Object.create(null);
        ret._rowCount = table._rowCount;
        ret._columns = table._columns;
        ret._schema = table._schema;
        for (var _a = 0, _b = table._columns; _a < _b.length; _a++) {
            var c = _b[_a];
            ret[c] = db_column.view(table[c], indices, false);
        }
        return ret;
    }
    Table.sort = sort;
    function areEqual(a, b) {
        if (a._rowCount !== b._rowCount)
            return false;
        if (a._columns.length !== b._columns.length)
            return false;
        for (var _a = 0, _b = a._columns; _a < _b.length; _a++) {
            var c = _b[_a];
            if (!b[c])
                return false;
        }
        for (var _c = 0, _d = a._columns; _c < _d.length; _c++) {
            var c = _d[_c];
            if (!db_column.areEqual(a[c], b[c]))
                return false;
        }
        return true;
    }
    Table.areEqual = areEqual;
    /** Allocate a new object with the given row values. */
    function getRow(table, index) {
        var row = Object.create(null);
        var cols = table._columns;
        for (var i = 0; i < cols.length; i++) {
            var c = cols[i];
            row[c] = table[c].value(index);
        }
        return row;
    }
    Table.getRow = getRow;
    /** Pick the first row for which `test` evaluates to true */
    function pickRow(table, test) {
        for (var i = 0, il = table._rowCount; i < il; ++i) {
            if (test(i))
                return getRow(table, i);
        }
    }
    Table.pickRow = pickRow;
    function getRows(table) {
        var ret = [];
        var c = table._rowCount;
        for (var i = 0; i < c; i++) {
            ret[i] = getRow(table, i);
        }
        return ret;
    }
    Table.getRows = getRows;
    function toArrays(table) {
        var arrays = {};
        var _columns = table._columns;
        for (var i = 0; i < _columns.length; i++) {
            var c = _columns[i];
            arrays[c] = table[c].toArray();
        }
        return arrays;
    }
    Table.toArrays = toArrays;
    function formatToString(table) {
        var sb = mol_util["b" /* StringBuilder */].create();
        var cols = table._columns, _rowCount = table._rowCount;
        var headerLength = 1;
        mol_util["b" /* StringBuilder */].write(sb, '|');
        for (var i = 0; i < cols.length; i++) {
            mol_util["b" /* StringBuilder */].write(sb, cols[i]);
            mol_util["b" /* StringBuilder */].write(sb, '|');
            headerLength += cols[i].length + 1;
        }
        mol_util["b" /* StringBuilder */].newline(sb);
        mol_util["b" /* StringBuilder */].write(sb, new Array(headerLength + 1).join('-'));
        mol_util["b" /* StringBuilder */].newline(sb);
        for (var r = 0; r < _rowCount; r++) {
            mol_util["b" /* StringBuilder */].write(sb, '|');
            for (var i = 0; i < cols.length; i++) {
                var c = table[cols[i]];
                if (c.valueKind(r) === 0 /* Present */) {
                    mol_util["b" /* StringBuilder */].write(sb, c.value(r));
                    mol_util["b" /* StringBuilder */].write(sb, '|');
                }
                else {
                    mol_util["b" /* StringBuilder */].write(sb, '.|');
                }
            }
            mol_util["b" /* StringBuilder */].newline(sb);
        }
        return mol_util["b" /* StringBuilder */].getString(sb);
    }
    Table.formatToString = formatToString;
})(table_Table || (table_Table = {}));
/* harmony default export */ var db_table = (table_Table);
//# sourceMappingURL=table.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/db/database.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var database_Database;
(function (Database) {
    function ofTables(name, schema, tables) {
        var keys = Object.keys(tables);
        var ret = Object.create(null);
        var tableNames = [];
        ret._name = name;
        ret._tableNames = tableNames;
        ret._schema = schema;
        for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
            var k = keys_1[_i];
            if (!db_table.is(tables[k]))
                continue;
            ret[k] = tables[k];
            tableNames[tableNames.length] = k;
        }
        return ret;
    }
    Database.ofTables = ofTables;
    function getTablesAsRows(database) {
        var ret = {};
        for (var _i = 0, _a = database._tableNames; _i < _a.length; _i++) {
            var k = _a[_i];
            ret[k] = db_table.getRows(database[k]);
        }
        return ret;
    }
    Database.getTablesAsRows = getTablesAsRows;
})(database_Database || (database_Database = {}));
/* harmony default export */ var db_database = (database_Database);
//# sourceMappingURL=database.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/db.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





//# sourceMappingURL=db.js.map

/***/ }),
/* 8 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PluginStateObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PluginStateTransform; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(13);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var PluginStateObject;
(function (PluginStateObject) {
    PluginStateObject.Create = _mol_state__WEBPACK_IMPORTED_MODULE_1__["StateObject"].factory();
    function isRepresentation3D(o) {
        return !!o && o.type.typeClass === 'Representation3D';
    }
    PluginStateObject.isRepresentation3D = isRepresentation3D;
    function isBehavior(o) {
        return !!o && o.type.typeClass === 'Behavior';
    }
    PluginStateObject.isBehavior = isBehavior;
    function CreateRepresentation3D(type) {
        return PluginStateObject.Create(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, type), { typeClass: 'Representation3D' }));
    }
    PluginStateObject.CreateRepresentation3D = CreateRepresentation3D;
    function CreateBehavior(type) {
        return PluginStateObject.Create(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, type), { typeClass: 'Behavior' }));
    }
    PluginStateObject.CreateBehavior = CreateBehavior;
    var Root = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Root, _super);
        function Root() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Root;
    }(PluginStateObject.Create({ name: 'Root', typeClass: 'Root' })));
    PluginStateObject.Root = Root;
    var Group = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Group, _super);
        function Group() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Group;
    }(PluginStateObject.Create({ name: 'Group', typeClass: 'Group' })));
    PluginStateObject.Group = Group;
    var Data;
    (function (Data) {
        var String = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(String, _super);
            function String() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return String;
        }(PluginStateObject.Create({ name: 'String Data', typeClass: 'Data', })));
        Data.String = String;
        var Binary = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Binary, _super);
            function Binary() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Binary;
        }(PluginStateObject.Create({ name: 'Binary Data', typeClass: 'Data' })));
        Data.Binary = Binary;
        var Blob = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Blob, _super);
            function Blob() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Blob;
        }(PluginStateObject.Create({ name: 'Data Blob', typeClass: 'Data' })));
        Data.Blob = Blob;
    })(Data = PluginStateObject.Data || (PluginStateObject.Data = {}));
    var Format;
    (function (Format) {
        var Json = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Json, _super);
            function Json() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Json;
        }(PluginStateObject.Create({ name: 'JSON Data', typeClass: 'Data' })));
        Format.Json = Json;
        var Cif = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Cif, _super);
            function Cif() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Cif;
        }(PluginStateObject.Create({ name: 'CIF File', typeClass: 'Data' })));
        Format.Cif = Cif;
        var Cube = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Cube, _super);
            function Cube() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Cube;
        }(PluginStateObject.Create({ name: 'Cube File', typeClass: 'Data' })));
        Format.Cube = Cube;
        var Psf = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Psf, _super);
            function Psf() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Psf;
        }(PluginStateObject.Create({ name: 'PSF File', typeClass: 'Data' })));
        Format.Psf = Psf;
        var Ply = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Ply, _super);
            function Ply() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Ply;
        }(PluginStateObject.Create({ name: 'PLY File', typeClass: 'Data' })));
        Format.Ply = Ply;
        var Ccp4 = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Ccp4, _super);
            function Ccp4() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Ccp4;
        }(PluginStateObject.Create({ name: 'CCP4/MRC/MAP File', typeClass: 'Data' })));
        Format.Ccp4 = Ccp4;
        var Dsn6 = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Dsn6, _super);
            function Dsn6() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Dsn6;
        }(PluginStateObject.Create({ name: 'DSN6/BRIX File', typeClass: 'Data' })));
        Format.Dsn6 = Dsn6;
        var Dx = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Dx, _super);
            function Dx() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Dx;
        }(PluginStateObject.Create({ name: 'DX File', typeClass: 'Data' })));
        Format.Dx = Dx;
        var Blob = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Blob, _super);
            function Blob() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Blob;
        }(PluginStateObject.Create({ name: 'Format Blob', typeClass: 'Data' })));
        Format.Blob = Blob;
    })(Format = PluginStateObject.Format || (PluginStateObject.Format = {}));
    var Molecule;
    (function (Molecule) {
        var Coordinates = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Coordinates, _super);
            function Coordinates() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Coordinates;
        }(PluginStateObject.Create({ name: 'Coordinates', typeClass: 'Object' })));
        Molecule.Coordinates = Coordinates;
        var Topology = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Topology, _super);
            function Topology() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Topology;
        }(PluginStateObject.Create({ name: 'Topology', typeClass: 'Object' })));
        Molecule.Topology = Topology;
        var Model = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Model, _super);
            function Model() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Model;
        }(PluginStateObject.Create({ name: 'Model', typeClass: 'Object' })));
        Molecule.Model = Model;
        var Trajectory = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Trajectory, _super);
            function Trajectory() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Trajectory;
        }(PluginStateObject.Create({ name: 'Trajectory', typeClass: 'Object' })));
        Molecule.Trajectory = Trajectory;
        var Structure = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Structure, _super);
            function Structure() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Structure;
        }(PluginStateObject.Create({ name: 'Structure', typeClass: 'Object' })));
        Molecule.Structure = Structure;
        (function (Structure) {
            var Representation3D = /** @class */ (function (_super) {
                Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Representation3D, _super);
                function Representation3D() {
                    return _super !== null && _super.apply(this, arguments) || this;
                }
                return Representation3D;
            }(CreateRepresentation3D({ name: 'Structure 3D' })));
            Structure.Representation3D = Representation3D;
            var Representation3DState = /** @class */ (function (_super) {
                Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Representation3DState, _super);
                function Representation3DState() {
                    return _super !== null && _super.apply(this, arguments) || this;
                }
                return Representation3DState;
            }(PluginStateObject.Create({ name: 'Structure 3D State', typeClass: 'Object' })));
            Structure.Representation3DState = Representation3DState;
            var Selections = /** @class */ (function (_super) {
                Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Selections, _super);
                function Selections() {
                    return _super !== null && _super.apply(this, arguments) || this;
                }
                return Selections;
            }(PluginStateObject.Create({ name: 'Selections', typeClass: 'Object' })));
            Structure.Selections = Selections;
        })(Structure = Molecule.Structure || (Molecule.Structure = {}));
    })(Molecule = PluginStateObject.Molecule || (PluginStateObject.Molecule = {}));
    var Volume;
    (function (Volume) {
        var Data = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Data, _super);
            function Data() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Data;
        }(PluginStateObject.Create({ name: 'Volume', typeClass: 'Object' })));
        Volume.Data = Data;
        var Representation3D = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Representation3D, _super);
            function Representation3D() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Representation3D;
        }(CreateRepresentation3D({ name: 'Volume 3D' })));
        Volume.Representation3D = Representation3D;
    })(Volume = PluginStateObject.Volume || (PluginStateObject.Volume = {}));
    var Shape;
    (function (Shape) {
        var Provider = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Provider, _super);
            function Provider() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Provider;
        }(PluginStateObject.Create({ name: 'Shape Provider', typeClass: 'Object' })));
        Shape.Provider = Provider;
        var Representation3D = /** @class */ (function (_super) {
            Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Representation3D, _super);
            function Representation3D() {
                return _super !== null && _super.apply(this, arguments) || this;
            }
            return Representation3D;
        }(CreateRepresentation3D({ name: 'Shape 3D' })));
        Shape.Representation3D = Representation3D;
    })(Shape = PluginStateObject.Shape || (PluginStateObject.Shape = {}));
})(PluginStateObject || (PluginStateObject = {}));
var PluginStateTransform;
(function (PluginStateTransform) {
    PluginStateTransform.CreateBuiltIn = _mol_state__WEBPACK_IMPORTED_MODULE_1__["StateTransformer"].factory('ms-plugin');
    PluginStateTransform.BuiltIn = _mol_state__WEBPACK_IMPORTED_MODULE_1__["StateTransformer"].builderFactory('ms-plugin');
})(PluginStateTransform || (PluginStateTransform = {}));
//# sourceMappingURL=objects.js.map

/***/ }),
/* 9 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ ChunkedArray; });
__webpack_require__.d(__webpack_exports__, "o", function() { return /* reexport */ makeBuckets; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ EquivalenceClasses; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* reexport */ hash1; });
__webpack_require__.d(__webpack_exports__, "i", function() { return /* reexport */ hash2; });
__webpack_require__.d(__webpack_exports__, "j", function() { return /* reexport */ hash3; });
__webpack_require__.d(__webpack_exports__, "k", function() { return /* reexport */ hash4; });
__webpack_require__.d(__webpack_exports__, "m", function() { return /* reexport */ hashString; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* reexport */ cantorPairing; });
__webpack_require__.d(__webpack_exports__, "l", function() { return /* reexport */ hashFnv32a; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ sort["a" /* arraySwap */]; });
__webpack_require__.d(__webpack_exports__, "q", function() { return /* reexport */ sort["c" /* sortArray */]; });
__webpack_require__.d(__webpack_exports__, "p", function() { return /* reexport */ sort["b" /* sort */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ array["a" /* arrayFind */]; });
__webpack_require__.d(__webpack_exports__, "n", function() { return /* reexport */ array["d" /* iterableToArray */]; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* reexport */ array["c" /* createRangeArray */]; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ array["b" /* arrayPickIndices */]; });

// UNUSED EXPORTS: EquivalenceClassesImpl, sortedCantorPairing, arrayLess, sortArrayRange, Grouper, groupBy, arrayGetCtor

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/chunked-array.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * from https://github.com/dsehnal/CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var ChunkedArray;
(function (ChunkedArray) {
    function is(x) {
        return x.creator && x.chunkSize;
    }
    ChunkedArray.is = is;
    function allocateNext(array) {
        var nextSize = array.growBy * array.elementSize;
        array.currentSize = nextSize;
        array.currentIndex = 0;
        array.currentChunk = new array.ctor(nextSize);
        array.allocatedSize += nextSize;
        array.chunks[array.chunks.length] = array.currentChunk;
    }
    function add4(array, x, y, z, w) {
        if (array.currentIndex >= array.currentSize)
            allocateNext(array);
        var c = array.currentChunk;
        c[array.currentIndex++] = x;
        c[array.currentIndex++] = y;
        c[array.currentIndex++] = z;
        c[array.currentIndex++] = w;
        return array.elementCount++;
    }
    ChunkedArray.add4 = add4;
    function add3(array, x, y, z) {
        if (array.currentIndex >= array.currentSize)
            allocateNext(array);
        var c = array.currentChunk;
        c[array.currentIndex++] = x;
        c[array.currentIndex++] = y;
        c[array.currentIndex++] = z;
        return array.elementCount++;
    }
    ChunkedArray.add3 = add3;
    function add2(array, x, y) {
        if (array.currentIndex >= array.currentSize)
            allocateNext(array);
        var c = array.currentChunk;
        c[array.currentIndex++] = x;
        c[array.currentIndex++] = y;
        return array.elementCount++;
    }
    ChunkedArray.add2 = add2;
    function add(array, x) {
        if (array.currentIndex >= array.currentSize)
            allocateNext(array);
        array.currentChunk[array.currentIndex++] = x;
        return array.elementCount++;
    }
    ChunkedArray.add = add;
    function addRepeat(array, n, x) {
        for (var i = 0; i < n; i++) {
            if (array.currentIndex >= array.currentSize)
                allocateNext(array);
            array.currentChunk[array.currentIndex++] = x;
            array.elementCount++;
        }
        return array.elementCount;
    }
    ChunkedArray.addRepeat = addRepeat;
    function addMany(array, data) {
        var elementSize = array.elementSize;
        for (var i = 0, _i = data.length; i < _i; i += elementSize) {
            if (array.currentIndex >= array.currentSize)
                allocateNext(array);
            var currentChunk = array.currentChunk;
            for (var j = 0; j < elementSize; j++) {
                currentChunk[array.currentIndex++] = data[i + j];
            }
            array.elementCount++;
        }
        return array.elementCount;
    }
    ChunkedArray.addMany = addMany;
    /** If doNotResizeSingleton = true and the data fit into a single chunk, do not resize it. */
    function compact(array, doNotResizeSingleton) {
        if (doNotResizeSingleton === void 0) { doNotResizeSingleton = false; }
        return _compact(array, doNotResizeSingleton);
    }
    ChunkedArray.compact = compact;
    function _compact(array, doNotResizeSingleton) {
        var ctor = array.ctor, chunks = array.chunks, currentIndex = array.currentIndex;
        if (!chunks.length)
            return new ctor(0);
        if (chunks.length === 1) {
            if (doNotResizeSingleton || currentIndex === array.allocatedSize) {
                return chunks[0];
            }
        }
        var size = 0;
        for (var i = 0, _i = chunks.length - 1; i < _i; i++)
            size += chunks[i].length;
        size += array.currentIndex;
        var ret = new ctor(size);
        var offset = 0;
        if (ret.buffer) {
            for (var i = 0, _i = chunks.length - 1; i < _i; i++) {
                ret.set(chunks[i], offset);
                offset += chunks[i].length;
            }
        }
        else {
            for (var i = 0, _i = chunks.length - 1; i < _i; i++) {
                var chunk = chunks[i];
                for (var j = 0, _j = chunk.length; j < _j; j++)
                    ret[offset + j] = chunk[j];
                offset += chunk.length;
            }
        }
        var lastChunk = chunks[chunks.length - 1];
        if (ret.buffer && currentIndex >= array.currentSize) {
            ret.set(lastChunk, offset);
        }
        else {
            for (var j = 0, _j = lastChunk.length; j < _j; j++)
                ret[offset + j] = lastChunk[j];
        }
        return ret;
    }
    ChunkedArray._compact = _compact;
    /**
     * The size of the initial chunk is elementSize * initialCount.
     * Use the provided array as the initial chunk. The size of the array must be divisible by the elementSize.
     */
    function create(ctor, elementSize, chunkSize, initialChunkOrCount) {
        var ret = {
            ctor: ctor,
            elementSize: elementSize,
            growBy: Math.max(1, Math.ceil(chunkSize)),
            allocatedSize: 0,
            elementCount: 0,
            currentSize: 0,
            currentChunk: void 0,
            currentIndex: 0,
            chunks: []
        };
        if (typeof initialChunkOrCount === 'undefined')
            return ret;
        if (typeof initialChunkOrCount === 'number') {
            ret.currentChunk = new ctor(initialChunkOrCount * elementSize);
            ret.allocatedSize = initialChunkOrCount * elementSize;
            ret.currentSize = ret.currentChunk.length;
            ret.chunks[0] = ret.currentChunk;
            return ret;
        }
        var initialChunk = initialChunkOrCount;
        if (initialChunk.length % elementSize !== 0)
            throw new Error('initialChunk length must be a multiple of the element size.');
        ret.currentChunk = initialChunk;
        ret.allocatedSize = initialChunk.length;
        ret.currentSize = initialChunk.length;
        ret.chunks[0] = initialChunk;
        return ret;
    }
    ChunkedArray.create = create;
})(ChunkedArray || (ChunkedArray = {}));

//# sourceMappingURL=chunked-array.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util/sort.js
var sort = __webpack_require__(272);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/buckets.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function sortAsc(bs, i, j) { return bs[i].key < bs[j].key ? -1 : 1; }
function _makeBuckets(indices, getKey, sortBuckets, start, end) {
    var buckets = new Map();
    var bucketList = [];
    var prevKey = getKey(indices[0]);
    var isBucketed = true;
    for (var i = start; i < end; i++) {
        var key = getKey(indices[i]);
        if (buckets.has(key)) {
            buckets.get(key).count++;
            if (prevKey !== key)
                isBucketed = false;
        }
        else {
            var bucket = { key: key, count: 1, offset: i };
            buckets.set(key, bucket);
            bucketList[bucketList.length] = bucket;
        }
        prevKey = key;
    }
    var bucketOffsets = new Int32Array(bucketList.length + 1);
    bucketOffsets[bucketList.length] = end;
    var sorted = true;
    if (sortBuckets) {
        for (var i = 1, _i = bucketList.length; i < _i; i++) {
            if (bucketList[i - 1].key > bucketList[i].key) {
                sorted = false;
                break;
            }
        }
    }
    if (isBucketed && sorted) {
        for (var i = 0; i < bucketList.length; i++)
            bucketOffsets[i] = bucketList[i].offset;
        return bucketOffsets;
    }
    if (sortBuckets && !sorted) {
        Object(sort["b" /* sort */])(bucketList, 0, bucketList.length, sortAsc, sort["a" /* arraySwap */]);
    }
    var offset = 0;
    for (var i = 0; i < bucketList.length; i++) {
        var b = bucketList[i];
        b.offset = offset;
        offset += b.count;
    }
    var reorderedIndices = new Int32Array(end - start);
    for (var i = start; i < end; i++) {
        var key = getKey(indices[i]);
        var bucket = buckets.get(key);
        reorderedIndices[bucket.offset++] = indices[i];
    }
    for (var i = 0, _i = reorderedIndices.length; i < _i; i++) {
        indices[i + start] = reorderedIndices[i];
    }
    bucketOffsets[0] = start;
    for (var i = 1; i < bucketList.length; i++)
        bucketOffsets[i] = bucketList[i - 1].offset + start;
    return bucketOffsets;
}
/**
 * Reorders indices so that the same keys are next to each other, [start, end)
 * Returns the offsets of buckets. So that [offsets[i], offsets[i + 1]) determines the range.
 */
function makeBuckets(indices, getKey, options) {
    var s = (options && options.start) || 0;
    var e = (options && options.end) || indices.length;
    if (e - s <= 0)
        throw new Error('Can only bucket non-empty collections.');
    return _makeBuckets(indices, getKey, !!(options && options.sort), s, e);
}
//# sourceMappingURL=buckets.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/equivalence-classes.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var EquivalenceClassesImpl = /** @class */ (function () {
    function EquivalenceClassesImpl(getHash, areEqual) {
        this.getHash = getHash;
        this.areEqual = areEqual;
        this.id = 0;
        this.byHash = new Map();
        this.groups = [];
    }
    EquivalenceClassesImpl.prototype.createGroup = function (key, value) {
        var id = this.id++;
        var keys = [key];
        this.groups[id] = keys;
        return { id: id, keys: keys, value: value };
    };
    // Return the group representative.
    EquivalenceClassesImpl.prototype.add = function (key, a) {
        var hash = this.getHash(a);
        if (this.byHash.has(hash)) {
            var groups = this.byHash.get(hash);
            for (var i = 0, _i = groups.length; i < _i; i++) {
                var group_1 = groups[i];
                if (this.areEqual(a, group_1.value)) {
                    group_1.keys[group_1.keys.length] = key;
                    return group_1.value;
                }
            }
            var group = this.createGroup(key, a);
            groups[groups.length] = group;
            return group.value;
        }
        else {
            var group = this.createGroup(key, a);
            this.byHash.set(hash, [group]);
            return group.value;
        }
    };
    return EquivalenceClassesImpl;
}());

function EquivalenceClasses(getHash, areEqual) {
    return new EquivalenceClassesImpl(getHash, areEqual);
}
//# sourceMappingURL=equivalence-classes.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/hash-functions.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// from http://burtleburtle.net/bob/hash/integer.html
function hash1(i) {
    var a = i ^ (i >> 4);
    a = (a ^ 0xdeadbeef) + (a << 5);
    a = a ^ (a >> 11);
    return a;
}
function hash2(i, j) {
    var a = 23;
    a = (31 * a + i) | 0;
    a = (31 * a + j) | 0;
    a = a ^ (a >> 4);
    a = (a ^ 0xdeadbeef) + (a << 5);
    a = a ^ (a >> 11);
    return a;
}
function hash3(i, j, k) {
    var a = 23;
    a = (31 * a + i) | 0;
    a = (31 * a + j) | 0;
    a = (31 * a + k) | 0;
    a = a ^ (a >> 4);
    a = (a ^ 0xdeadbeef) + (a << 5);
    a = a ^ (a >> 11);
    return a;
}
function hash4(i, j, k, l) {
    var a = 23;
    a = (31 * a + i) | 0;
    a = (31 * a + j) | 0;
    a = (31 * a + k) | 0;
    a = (31 * a + l) | 0;
    a = a ^ (a >> 4);
    a = (a ^ 0xdeadbeef) + (a << 5);
    a = a ^ (a >> 11);
    return a;
}
function hashString(s) {
    var h = 0;
    for (var i = 0, l = s.length; i < l; i++) {
        h = (h << 5) - h + s.charCodeAt(i++) | 0;
    }
    return h;
}
/**
 * A unique number for each pair of integers
 * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
 */
function cantorPairing(a, b) {
    return (a + b) * (a + b + 1) / 2 + b;
}
/**
 * A unique number for each sorted pair of integers
 * Biggest representable pair is (67108863, 67108863) (limit imposed by Number.MAX_SAFE_INTEGER)
 */
function sortedCantorPairing(a, b) {
    return a < b ? cantorPairing(a, b) : cantorPairing(b, a);
}
/**
 * 32 bit FNV-1a hash, see http://isthe.com/chongo/tech/comp/fnv/
 */
function hashFnv32a(array) {
    var hval = 0x811c9dc5;
    for (var i = 0, il = array.length; i < il; ++i) {
        hval ^= array[i];
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }
    return hval >>> 0;
}
//# sourceMappingURL=hash-functions.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/grouping.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var GroupingImpl = /** @class */ (function () {
    function GroupingImpl(getKey) {
        this.getKey = getKey;
        this.map = new Map();
        this.keys = [];
        this.groups = [];
    }
    GroupingImpl.prototype.add = function (a) {
        var key = this.getKey(a);
        if (!!this.map.has(key)) {
            var group = this.map.get(key);
            group[group.length] = a;
        }
        else {
            var group = [a];
            this.map.set(key, group);
            this.keys[this.keys.length] = key;
            this.groups[this.groups.length] = group;
        }
    };
    GroupingImpl.prototype.getGrouping = function () {
        return { keys: this.keys, groups: this.groups, map: this.map };
    };
    return GroupingImpl;
}());
function Grouper(getKey) {
    return new GroupingImpl(getKey);
}
function groupBy(values, getKey) {
    var gs = Grouper(getKey);
    if (db["Column"].is(values)) {
        var v = values.value;
        for (var i = 0, _i = values.rowCount; i < _i; i++)
            gs.add(v(i));
    }
    else {
        for (var i = 0, _i = values.length; i < _i; i++)
            gs.add(values[i]);
    }
    return gs.getGrouping();
}
//# sourceMappingURL=grouping.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util/array.js
var array = __webpack_require__(338);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







//# sourceMappingURL=util.js.map

/***/ }),
/* 10 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MolScriptBuilder", function() { return MolScriptBuilder; });
/* harmony import */ var _symbol_table__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(12);
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var MolScriptBuilder;
(function (MolScriptBuilder) {
    MolScriptBuilder.core = _symbol_table__WEBPACK_IMPORTED_MODULE_0__[/* MolScriptSymbolTable */ "a"].core;
    MolScriptBuilder.struct = _symbol_table__WEBPACK_IMPORTED_MODULE_0__[/* MolScriptSymbolTable */ "a"].structureQuery;
    MolScriptBuilder.internal = _symbol_table__WEBPACK_IMPORTED_MODULE_0__[/* MolScriptSymbolTable */ "a"].internal;
    /** Atom-name constructor */
    function atomName(s) { return MolScriptBuilder.struct.type.atomName([s]); }
    MolScriptBuilder.atomName = atomName;
    /** Element-symbol constructor */
    function es(s) { return MolScriptBuilder.struct.type.elementSymbol([s]); }
    MolScriptBuilder.es = es;
    /** List constructor */
    function list() {
        var xs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            xs[_i] = arguments[_i];
        }
        return MolScriptBuilder.core.type.list(xs);
    }
    MolScriptBuilder.list = list;
    /** Set constructor */
    function set() {
        var xs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            xs[_i] = arguments[_i];
        }
        return MolScriptBuilder.core.type.set(xs);
    }
    MolScriptBuilder.set = set;
    /** RegEx constructor */
    function re(pattern, flags) { return MolScriptBuilder.core.type.regex([pattern, flags]); }
    MolScriptBuilder.re = re;
    /** Function constructor */
    function fn(x) { return MolScriptBuilder.core.ctrl.fn([x]); }
    MolScriptBuilder.fn = fn;
    function evaluate(x) { return MolScriptBuilder.core.ctrl.eval([x]); }
    MolScriptBuilder.evaluate = evaluate;
    var _acp = MolScriptBuilder.struct.atomProperty.core, _ammp = MolScriptBuilder.struct.atomProperty.macromolecular, _atp = MolScriptBuilder.struct.atomProperty.topology;
    /** atom core property */
    function acp(p) { return _acp[p](); }
    MolScriptBuilder.acp = acp;
    ;
    /** atom topology property */
    function atp(p) { return _atp[p](); }
    MolScriptBuilder.atp = atp;
    ;
    /** atom macromolecular property */
    function ammp(p) { return _ammp[p](); }
    MolScriptBuilder.ammp = ammp;
    ;
    var _aps = MolScriptBuilder.struct.atomSet.propertySet;
    /** atom core property set */
    function acpSet(p) { return _aps([acp(p)]); }
    MolScriptBuilder.acpSet = acpSet;
    ;
    /** atom topology property set */
    function atpSet(p) { return _aps([atp(p)]); }
    MolScriptBuilder.atpSet = atpSet;
    ;
    /** atom macromolecular property set */
    function ammpSet(p) { return _aps([ammp(p)]); }
    MolScriptBuilder.ammpSet = ammpSet;
    ;
})(MolScriptBuilder || (MolScriptBuilder = {}));
//# sourceMappingURL=builder.js.map

/***/ }),
/* 11 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "i", function() { return /* reexport */ fillGridDim; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* reexport */ symmetry_operator["a" /* SymmetryOperator */]; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ construction_Spacegroup; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* reexport */ construction_SpacegroupCell; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ Result; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ GridLookup3D; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ box3d["a" /* Box3D */]; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* reexport */ sphere3d["a" /* Sphere3D */]; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ axes3d_Axes3D; });

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/common.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function fillGridDim(length, start, step) {
    var a = new Float32Array(length);
    for (var i = 0; i < a.length; i++) {
        a[i] = start + (step * i);
    }
    return a;
}
//# sourceMappingURL=common.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/symmetry-operator.js
var symmetry_operator = __webpack_require__(136);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/spacegroup/tables.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var TransformData = [
    [1.0, 0.0, 0.0, 0.0],
    [0.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 0.0],
    [-1.0, 0.0, 0.0, 0.0],
    [0.0, -1.0, 0.0, 0.0],
    [0.0, 0.0, -1.0, 0.0],
    [0.0, 1.0, 0.0, 0.5],
    [1.0, 0.0, 0.0, 0.5],
    [-1.0, 0.0, 0.0, 0.5],
    [0.0, 0.0, 1.0, 0.5],
    [0.0, -1.0, 0.0, 0.5],
    [0.0, 0.0, -1.0, 0.5],
    [1.0, 0.0, 0.0, 0.25],
    [0.0, -1.0, 0.0, 0.25],
    [0.0, 0.0, 1.0, 0.25],
    [-1.0, 0.0, 0.0, 0.25],
    [0.0, 1.0, 0.0, 0.25],
    [0.0, -1.0, 0.0, 0.75],
    [0.0, 0.0, 1.0, 0.75],
    [0.0, 1.0, 0.0, 0.75],
    [1.0, 0.0, 0.0, 0.75],
    [-1.0, 0.0, 0.0, 0.75],
    [0.0, 0.0, -1.0, 0.25],
    [0.0, 0.0, -1.0, 0.75],
    [1.0, -1.0, 0.0, 0.0],
    [-1.0, 1.0, 0.0, 0.0],
    [0.0, 0.0, 1.0, 1 / 3],
    [0.0, 0.0, 1.0, 2 / 3],
    [1.0, 0.0, 0.0, 2 / 3],
    [0.0, 1.0, 0.0, 1 / 3],
    [0.0, -1.0, 0.0, 2 / 3],
    [1.0, -1.0, 0.0, 1 / 3],
    [-1.0, 1.0, 0.0, 2 / 3],
    [-1.0, 0.0, 0.0, 1 / 3],
    [1.0, 0.0, 0.0, 1 / 3],
    [0.0, 1.0, 0.0, 2 / 3],
    [0.0, -1.0, 0.0, 1 / 3],
    [1.0, -1.0, 0.0, 2 / 3],
    [-1.0, 1.0, 0.0, 1 / 3],
    [-1.0, 0.0, 0.0, 2 / 3],
    [0.0, 0.0, -1.0, 1 / 3],
    [0.0, 0.0, -1.0, 2 / 3],
    [0.0, 0.0, 1.0, 5 / 6],
    [0.0, 0.0, 1.0, 1 / 6],
    [0.0, 0.0, -1.0, 5 / 6],
    [0.0, 0.0, -1.0, 1 / 6],
];
var OperatorData = [
    [0, 1, 2],
    [3, 4, 5],
    [3, 1, 5],
    [3, 6, 5],
    [7, 6, 2],
    [8, 6, 5],
    [0, 4, 2],
    [0, 4, 9],
    [7, 10, 2],
    [7, 10, 9],
    [0, 10, 2],
    [8, 10, 5],
    [3, 1, 11],
    [3, 6, 11],
    [0, 10, 9],
    [8, 6, 11],
    [3, 4, 2],
    [0, 4, 5],
    [3, 4, 9],
    [7, 10, 5],
    [8, 4, 9],
    [8, 10, 9],
    [8, 10, 2],
    [0, 6, 9],
    [3, 10, 9],
    [0, 10, 11],
    [7, 1, 9],
    [8, 1, 11],
    [7, 4, 11],
    [7, 6, 9],
    [7, 10, 11],
    [3, 10, 2],
    [8, 1, 5],
    [0, 4, 11],
    [3, 1, 2],
    [3, 1, 9],
    [7, 4, 2],
    [8, 1, 2],
    [8, 1, 9],
    [3, 6, 9],
    [7, 4, 9],
    [8, 6, 2],
    [8, 6, 9],
    [3, 6, 2],
    [12, 13, 14],
    [15, 16, 14],
    [12, 17, 18],
    [15, 19, 18],
    [20, 13, 18],
    [21, 16, 18],
    [20, 17, 14],
    [21, 19, 14],
    [0, 1, 5],
    [8, 10, 11],
    [7, 6, 11],
    [7, 6, 5],
    [8, 4, 2],
    [7, 4, 5],
    [7, 1, 5],
    [7, 1, 11],
    [0, 10, 5],
    [0, 1, 11],
    [0, 6, 11],
    [0, 6, 5],
    [3, 10, 11],
    [8, 4, 11],
    [15, 13, 22],
    [12, 16, 22],
    [15, 17, 23],
    [12, 19, 23],
    [21, 13, 23],
    [20, 16, 23],
    [21, 17, 22],
    [20, 19, 22],
    [4, 0, 2],
    [1, 3, 2],
    [4, 0, 14],
    [1, 3, 18],
    [4, 0, 9],
    [1, 3, 9],
    [4, 0, 18],
    [1, 3, 14],
    [10, 7, 9],
    [6, 8, 9],
    [4, 7, 14],
    [6, 3, 18],
    [10, 0, 18],
    [1, 8, 14],
    [1, 3, 5],
    [4, 0, 5],
    [6, 8, 11],
    [10, 7, 11],
    [1, 3, 11],
    [4, 0, 11],
    [10, 7, 2],
    [6, 8, 2],
    [3, 10, 22],
    [7, 1, 23],
    [8, 4, 23],
    [0, 6, 22],
    [1, 0, 5],
    [4, 3, 5],
    [1, 0, 23],
    [4, 3, 22],
    [10, 7, 14],
    [6, 8, 18],
    [8, 6, 22],
    [7, 10, 23],
    [4, 3, 11],
    [1, 0, 11],
    [1, 0, 22],
    [4, 3, 23],
    [10, 7, 18],
    [6, 8, 14],
    [8, 6, 23],
    [7, 10, 22],
    [6, 7, 11],
    [10, 8, 11],
    [8, 1, 23],
    [0, 10, 22],
    [3, 6, 22],
    [7, 4, 23],
    [4, 3, 2],
    [1, 0, 2],
    [10, 8, 2],
    [6, 7, 2],
    [4, 3, 9],
    [1, 0, 9],
    [10, 8, 9],
    [6, 7, 9],
    [4, 8, 14],
    [6, 0, 18],
    [10, 3, 18],
    [1, 7, 14],
    [4, 8, 18],
    [6, 0, 14],
    [10, 3, 14],
    [1, 7, 18],
    [6, 7, 5],
    [10, 8, 5],
    [6, 8, 5],
    [10, 7, 5],
    [8, 1, 22],
    [0, 10, 23],
    [3, 6, 23],
    [7, 4, 22],
    [4, 24, 2],
    [25, 3, 2],
    [4, 24, 26],
    [25, 3, 27],
    [4, 24, 27],
    [25, 3, 26],
    [28, 29, 26],
    [30, 31, 26],
    [32, 33, 26],
    [34, 35, 27],
    [36, 37, 27],
    [38, 39, 27],
    [2, 0, 1],
    [1, 2, 0],
    [1, 25, 5],
    [24, 0, 5],
    [39, 36, 40],
    [35, 38, 40],
    [37, 34, 40],
    [33, 30, 41],
    [29, 32, 41],
    [31, 28, 41],
    [5, 3, 4],
    [4, 5, 3],
    [25, 1, 5],
    [0, 24, 5],
    [24, 4, 5],
    [3, 25, 5],
    [4, 3, 41],
    [25, 1, 40],
    [24, 4, 41],
    [3, 25, 40],
    [4, 3, 40],
    [25, 1, 41],
    [24, 4, 40],
    [3, 25, 41],
    [35, 34, 40],
    [37, 36, 40],
    [39, 38, 40],
    [29, 28, 41],
    [31, 30, 41],
    [33, 32, 41],
    [3, 5, 4],
    [5, 4, 3],
    [25, 1, 2],
    [0, 24, 2],
    [24, 4, 2],
    [3, 25, 2],
    [25, 1, 9],
    [0, 24, 9],
    [24, 4, 9],
    [3, 25, 9],
    [30, 33, 26],
    [32, 29, 26],
    [28, 31, 26],
    [36, 39, 27],
    [38, 35, 27],
    [34, 37, 27],
    [0, 2, 1],
    [2, 1, 0],
    [30, 33, 42],
    [32, 29, 42],
    [28, 31, 42],
    [36, 39, 43],
    [38, 35, 43],
    [34, 37, 43],
    [7, 9, 6],
    [9, 6, 7],
    [25, 1, 11],
    [0, 24, 11],
    [24, 4, 11],
    [3, 25, 11],
    [35, 34, 44],
    [37, 36, 44],
    [39, 38, 44],
    [29, 28, 45],
    [31, 30, 45],
    [33, 32, 45],
    [8, 11, 10],
    [11, 10, 8],
    [1, 25, 2],
    [24, 0, 2],
    [1, 25, 42],
    [24, 0, 43],
    [1, 25, 43],
    [24, 0, 42],
    [1, 25, 27],
    [24, 0, 26],
    [1, 25, 26],
    [24, 0, 27],
    [1, 25, 9],
    [24, 0, 9],
    [4, 24, 5],
    [25, 3, 5],
    [4, 24, 11],
    [25, 3, 11],
    [1, 0, 40],
    [4, 3, 44],
    [0, 24, 45],
    [1, 0, 41],
    [4, 3, 45],
    [0, 24, 44],
    [0, 24, 40],
    [0, 24, 41],
    [2, 3, 4],
    [5, 3, 1],
    [5, 0, 4],
    [4, 2, 3],
    [1, 5, 3],
    [4, 5, 0],
    [2, 7, 6],
    [2, 8, 10],
    [5, 8, 6],
    [5, 7, 10],
    [1, 9, 7],
    [4, 9, 8],
    [1, 11, 8],
    [4, 11, 7],
    [9, 0, 6],
    [9, 3, 10],
    [11, 3, 6],
    [11, 0, 10],
    [6, 2, 7],
    [10, 2, 8],
    [6, 5, 8],
    [10, 5, 7],
    [9, 7, 1],
    [9, 8, 4],
    [11, 8, 1],
    [11, 7, 4],
    [6, 9, 0],
    [10, 9, 3],
    [6, 11, 3],
    [10, 11, 0],
    [9, 7, 6],
    [9, 8, 10],
    [11, 8, 6],
    [11, 7, 10],
    [6, 9, 7],
    [10, 9, 8],
    [6, 11, 8],
    [10, 11, 7],
    [2, 3, 10],
    [5, 8, 1],
    [11, 0, 4],
    [10, 2, 3],
    [1, 5, 8],
    [4, 11, 0],
    [5, 0, 1],
    [2, 0, 4],
    [2, 3, 1],
    [1, 5, 0],
    [4, 2, 0],
    [1, 2, 3],
    [11, 8, 10],
    [11, 7, 6],
    [9, 7, 10],
    [9, 8, 6],
    [10, 11, 8],
    [6, 11, 7],
    [10, 9, 7],
    [6, 9, 8],
    [5, 8, 10],
    [5, 7, 6],
    [2, 7, 10],
    [2, 8, 6],
    [4, 11, 8],
    [1, 11, 7],
    [4, 9, 7],
    [1, 9, 8],
    [11, 3, 10],
    [11, 0, 6],
    [9, 0, 10],
    [9, 3, 6],
    [10, 5, 8],
    [6, 5, 7],
    [10, 2, 7],
    [6, 2, 8],
    [11, 8, 4],
    [11, 7, 1],
    [9, 7, 4],
    [9, 8, 1],
    [10, 11, 3],
    [6, 11, 0],
    [10, 9, 0],
    [6, 9, 3],
    [22, 15, 13],
    [22, 12, 16],
    [14, 12, 13],
    [14, 15, 16],
    [13, 22, 15],
    [16, 22, 12],
    [13, 14, 12],
    [16, 14, 15],
    [22, 21, 17],
    [22, 20, 19],
    [14, 20, 17],
    [14, 21, 19],
    [13, 23, 21],
    [16, 23, 20],
    [13, 18, 20],
    [16, 18, 21],
    [23, 15, 17],
    [23, 12, 19],
    [18, 12, 17],
    [18, 15, 19],
    [17, 22, 21],
    [19, 22, 20],
    [17, 14, 20],
    [19, 14, 21],
    [23, 21, 13],
    [23, 20, 16],
    [18, 20, 13],
    [18, 21, 16],
    [17, 23, 15],
    [19, 23, 12],
    [17, 18, 12],
    [19, 18, 15],
    [5, 0, 6],
    [2, 7, 4],
    [9, 3, 1],
    [6, 5, 0],
    [4, 2, 7],
    [1, 9, 3],
    [0, 2, 4],
    [3, 2, 1],
    [0, 5, 1],
    [2, 1, 3],
    [2, 4, 0],
    [5, 1, 0],
    [7, 9, 10],
    [8, 9, 6],
    [7, 11, 6],
    [9, 6, 8],
    [9, 10, 7],
    [11, 6, 7],
    [1, 7, 11],
    [4, 8, 11],
    [1, 8, 9],
    [4, 7, 9],
    [0, 9, 10],
    [3, 9, 6],
    [3, 11, 10],
    [0, 11, 6],
    [2, 6, 8],
    [2, 10, 7],
    [5, 6, 7],
    [5, 10, 8],
    [6, 0, 11],
    [10, 3, 11],
    [6, 3, 9],
    [10, 0, 9],
    [7, 2, 10],
    [8, 2, 6],
    [8, 5, 10],
    [7, 5, 6],
    [9, 1, 8],
    [9, 4, 7],
    [11, 1, 7],
    [11, 4, 8],
    [7, 9, 4],
    [8, 9, 1],
    [8, 11, 4],
    [7, 11, 1],
    [9, 6, 3],
    [9, 10, 0],
    [11, 6, 0],
    [11, 10, 3],
    [19, 12, 23],
    [13, 15, 22],
    [16, 21, 18],
    [17, 20, 14],
    [20, 14, 17],
    [21, 18, 16],
    [15, 22, 13],
    [12, 23, 19],
    [18, 16, 21],
    [14, 17, 20],
    [23, 19, 12],
    [22, 13, 15],
    [19, 20, 22],
    [13, 21, 23],
    [16, 15, 14],
    [17, 12, 18],
    [20, 18, 13],
    [21, 14, 19],
    [15, 23, 17],
    [12, 22, 16],
    [18, 19, 15],
    [14, 13, 12],
    [23, 16, 20],
    [22, 17, 21],
    [16, 12, 22],
    [17, 15, 23],
    [19, 21, 14],
    [13, 20, 18],
    [12, 14, 13],
    [15, 18, 19],
    [21, 22, 17],
    [20, 23, 16],
    [14, 16, 15],
    [18, 17, 12],
    [22, 19, 20],
    [23, 13, 21],
    [16, 20, 23],
    [17, 21, 22],
    [19, 15, 18],
    [13, 12, 14],
    [12, 18, 17],
    [15, 14, 16],
    [21, 23, 13],
    [20, 22, 19],
    [14, 19, 21],
    [18, 13, 20],
    [22, 16, 12],
    [23, 17, 15],
    [19, 12, 22],
    [17, 21, 23],
    [16, 15, 18],
    [13, 20, 14],
    [20, 14, 13],
    [15, 18, 16],
    [21, 23, 17],
    [12, 22, 19],
    [18, 16, 15],
    [14, 13, 20],
    [22, 19, 12],
    [23, 17, 21],
    [3, 2, 4],
    [3, 5, 1],
    [0, 5, 4],
    [2, 4, 3],
    [5, 1, 3],
    [5, 4, 0],
    [1, 7, 9],
    [4, 8, 9],
    [1, 8, 11],
    [4, 7, 11],
    [0, 9, 6],
    [3, 9, 10],
    [3, 11, 6],
    [0, 11, 10],
    [2, 6, 7],
    [2, 10, 8],
    [5, 6, 8],
    [5, 10, 7],
    [6, 0, 9],
    [10, 3, 9],
    [6, 3, 11],
    [10, 0, 11],
    [7, 2, 6],
    [8, 2, 10],
    [8, 5, 6],
    [7, 5, 10],
    [9, 1, 7],
    [9, 4, 8],
    [11, 1, 8],
    [11, 4, 7],
    [7, 9, 1],
    [8, 9, 4],
    [8, 11, 1],
    [7, 11, 4],
    [9, 6, 0],
    [9, 10, 3],
    [11, 6, 3],
    [11, 10, 0],
    [8, 9, 10],
    [8, 11, 6],
    [7, 11, 10],
    [9, 10, 8],
    [11, 6, 8],
    [11, 10, 7],
    [6, 0, 2],
    [10, 3, 2],
    [6, 3, 5],
    [10, 0, 5],
    [7, 2, 1],
    [8, 2, 4],
    [8, 5, 1],
    [7, 5, 4],
    [9, 1, 0],
    [9, 4, 3],
    [11, 1, 3],
    [11, 4, 0],
    [1, 7, 2],
    [4, 8, 2],
    [1, 8, 5],
    [4, 7, 5],
    [0, 9, 1],
    [3, 9, 4],
    [3, 11, 1],
    [0, 11, 4],
    [2, 6, 0],
    [2, 10, 3],
    [5, 6, 3],
    [5, 10, 0],
    [0, 2, 6],
    [3, 2, 10],
    [3, 5, 6],
    [0, 5, 10],
    [2, 1, 7],
    [2, 4, 8],
    [5, 1, 8],
    [5, 4, 7],
    [16, 12, 14],
    [13, 21, 18],
    [19, 15, 23],
    [17, 20, 22],
    [12, 14, 16],
    [21, 18, 13],
    [15, 23, 19],
    [20, 22, 17],
    [14, 16, 12],
    [18, 13, 21],
    [23, 19, 15],
    [22, 17, 20],
    [19, 20, 18],
    [17, 15, 14],
    [16, 21, 22],
    [13, 12, 23],
    [20, 18, 19],
    [15, 14, 17],
    [21, 22, 16],
    [12, 23, 13],
    [18, 19, 20],
    [14, 17, 15],
    [22, 16, 21],
    [23, 13, 12],
    [6, 0, 5],
    [10, 3, 5],
    [6, 3, 2],
    [10, 0, 2],
    [7, 2, 4],
    [8, 2, 1],
    [8, 5, 4],
    [7, 5, 1],
    [9, 1, 3],
    [9, 4, 0],
    [11, 1, 0],
    [11, 4, 3],
    [1, 7, 5],
    [4, 8, 5],
    [1, 8, 2],
    [4, 7, 2],
    [0, 9, 4],
    [3, 9, 1],
    [3, 11, 4],
    [0, 11, 1],
    [2, 6, 3],
    [2, 10, 0],
    [5, 6, 0],
    [5, 10, 3],
    [0, 2, 10],
    [3, 2, 6],
    [3, 5, 10],
    [0, 5, 6],
    [2, 1, 8],
    [2, 4, 7],
    [5, 1, 7],
    [5, 4, 8],
    [21, 17, 23],
    [20, 16, 22],
    [12, 13, 18],
    [15, 19, 14],
    [23, 21, 17],
    [22, 20, 16],
    [18, 12, 13],
    [14, 15, 19],
    [17, 23, 21],
    [16, 22, 20],
    [13, 18, 12],
    [19, 14, 15],
    [21, 13, 22],
    [20, 19, 23],
    [12, 17, 14],
    [15, 16, 18],
    [23, 15, 13],
    [22, 12, 19],
    [18, 20, 17],
    [14, 21, 16],
    [17, 22, 15],
    [16, 23, 12],
    [13, 14, 20],
    [19, 18, 21],
    [15, 17, 22],
    [12, 16, 23],
    [20, 13, 14],
    [21, 19, 18],
    [22, 21, 13],
    [23, 20, 19],
    [14, 12, 17],
    [18, 15, 16],
    [13, 23, 15],
    [19, 22, 12],
    [17, 18, 20],
    [16, 14, 21],
    [15, 13, 23],
    [12, 19, 22],
    [20, 17, 18],
    [21, 16, 14],
    [22, 15, 17],
    [23, 12, 16],
    [14, 20, 13],
    [18, 21, 19],
    [13, 22, 21],
    [19, 23, 20],
    [17, 14, 12],
    [16, 18, 15],
    [6, 5, 3],
    [4, 9, 3],
    [9, 3, 4],
    [5, 7, 4],
    [4, 5, 7],
    [5, 3, 6],
];
var GroupData = [
    [0],
    [0, 1],
    [0, 2],
    [0, 3],
    [0, 2, 4, 5],
    [0, 6],
    [0, 7],
    [0, 6, 4, 8],
    [0, 7, 4, 9],
    [0, 6, 2, 1],
    [0, 3, 1, 10],
    [0, 6, 2, 1, 4, 8, 5, 11],
    [0, 12, 1, 7],
    [0, 1, 13, 14],
    [0, 12, 1, 7, 4, 15, 11, 9],
    [0, 16, 2, 17],
    [0, 18, 12, 17],
    [0, 16, 5, 19],
    [0, 20, 13, 19],
    [0, 18, 12, 17, 4, 21, 15, 19],
    [0, 16, 2, 17, 4, 22, 5, 19],
    [0, 16, 2, 17, 23, 24, 13, 25, 26, 20, 27, 28, 4, 22, 5, 19],
    [0, 16, 17, 2, 29, 21, 30, 15],
    [0, 20, 13, 19, 29, 31, 32, 33],
    [0, 16, 6, 34],
    [0, 18, 7, 34],
    [0, 16, 7, 35],
    [0, 16, 36, 37],
    [0, 18, 36, 38],
    [0, 16, 14, 39],
    [0, 20, 40, 34],
    [0, 16, 8, 41],
    [0, 18, 8, 42],
    [0, 16, 9, 42],
    [0, 16, 6, 34, 4, 22, 8, 41],
    [0, 18, 7, 34, 4, 21, 9, 41],
    [0, 16, 7, 35, 4, 22, 9, 42],
    [0, 16, 6, 34, 23, 24, 14, 39],
    [0, 16, 10, 43, 23, 24, 7, 35],
    [0, 16, 36, 37, 23, 24, 9, 42],
    [0, 16, 8, 41, 23, 24, 40, 38],
    [0, 16, 6, 34, 23, 24, 14, 39, 26, 20, 40, 38, 4, 22, 8, 41],
    [0, 16, 44, 45, 23, 24, 46, 47, 26, 20, 48, 49, 4, 22, 50, 51],
    [0, 16, 6, 34, 29, 21, 9, 42],
    [0, 16, 8, 41, 29, 21, 7, 35],
    [0, 16, 36, 37, 29, 21, 14, 39],
    [0, 16, 2, 17, 1, 52, 6, 34],
    [0, 16, 2, 17, 53, 54, 9, 42],
    [0, 16, 12, 33, 1, 52, 7, 35],
    [0, 16, 2, 17, 11, 55, 8, 41],
    [0, 56, 2, 57, 1, 58, 6, 37],
    [0, 56, 15, 25, 1, 58, 9, 39],
    [0, 20, 27, 17, 1, 59, 40, 34],
    [0, 56, 12, 28, 1, 58, 7, 38],
    [0, 16, 5, 19, 1, 52, 8, 41],
    [0, 22, 13, 28, 1, 55, 14, 38],
    [0, 18, 13, 60, 1, 61, 14, 43],
    [0, 16, 15, 30, 1, 52, 9, 42],
    [0, 16, 5, 19, 11, 55, 6, 34],
    [0, 21, 12, 19, 1, 54, 7, 41],
    [0, 20, 13, 19, 1, 59, 14, 41],
    [0, 20, 3, 30, 1, 59, 10, 42],
    [0, 18, 12, 17, 1, 61, 7, 34, 4, 21, 15, 19, 11, 54, 9, 41],
    [0, 24, 13, 17, 1, 62, 14, 34, 4, 20, 27, 19, 11, 59, 40, 41],
    [0, 16, 2, 17, 1, 52, 6, 34, 4, 22, 5, 19, 11, 55, 8, 41],
    [0, 16, 12, 33, 1, 52, 7, 35, 4, 22, 15, 30, 11, 55, 9, 42],
    [0, 31, 3, 17, 1, 63, 10, 34, 4, 56, 32, 19, 11, 58, 36, 41],
    [0, 22, 2, 19, 64, 59, 14, 38, 4, 16, 5, 17, 65, 62, 40, 39],
    [0, 16, 2, 17, 1, 52, 6, 34, 23, 24, 13, 25, 64, 62, 14, 39, 26, 20, 27, 28, 65, 59, 40, 38, 4, 22, 5, 19, 11, 55, 8, 41],
    [0, 16, 2, 17, 66, 67, 44, 45, 23, 24, 13, 25, 68, 69, 46, 47, 26, 20, 27, 28, 70, 71, 48, 49, 4, 22, 5, 19, 72, 73, 50, 51],
    [0, 16, 2, 17, 1, 52, 6, 34, 29, 21, 15, 30, 53, 54, 9, 42],
    [0, 16, 5, 19, 1, 52, 8, 41, 29, 21, 12, 33, 53, 54, 7, 35],
    [0, 20, 13, 19, 1, 59, 14, 41, 29, 31, 32, 33, 53, 63, 36, 35],
    [0, 31, 3, 17, 1, 63, 10, 34, 29, 20, 27, 30, 53, 59, 40, 42],
    [0, 16, 74, 75],
    [0, 18, 76, 77],
    [0, 16, 78, 79],
    [0, 18, 80, 81],
    [0, 16, 74, 75, 29, 21, 82, 83],
    [0, 21, 84, 85, 29, 16, 86, 87],
    [0, 16, 88, 89],
    [0, 16, 88, 89, 29, 21, 90, 91],
    [0, 16, 74, 75, 1, 52, 88, 89],
    [0, 16, 78, 79, 1, 52, 92, 93],
    [0, 16, 94, 95, 11, 55, 88, 89],
    [0, 16, 82, 83, 53, 54, 88, 89],
    [0, 16, 74, 75, 1, 52, 88, 89, 29, 21, 82, 83, 53, 54, 90, 91],
    [0, 21, 84, 85, 96, 97, 88, 91, 29, 16, 86, 87, 98, 99, 90, 89],
    [0, 16, 74, 75, 2, 17, 100, 101],
    [0, 16, 94, 95, 5, 19, 100, 101],
    [0, 18, 76, 77, 2, 33, 102, 103],
    [0, 18, 104, 105, 106, 107, 100, 108],
    [0, 16, 78, 79, 2, 17, 109, 108],
    [0, 16, 82, 83, 15, 30, 100, 101],
    [0, 18, 80, 81, 2, 33, 110, 111],
    [0, 18, 112, 113, 114, 115, 100, 108],
    [0, 16, 74, 75, 2, 17, 100, 101, 29, 21, 82, 83, 15, 30, 116, 117],
    [0, 21, 84, 85, 118, 119, 116, 101, 29, 16, 86, 87, 120, 121, 100, 117],
    [0, 16, 74, 75, 6, 34, 122, 123],
    [0, 16, 74, 75, 8, 41, 124, 125],
    [0, 16, 78, 79, 7, 35, 122, 123],
    [0, 16, 82, 83, 9, 42, 122, 123],
    [0, 16, 74, 75, 7, 35, 126, 127],
    [0, 16, 74, 75, 9, 42, 128, 129],
    [0, 16, 78, 79, 6, 34, 126, 127],
    [0, 16, 78, 79, 8, 41, 128, 129],
    [0, 16, 74, 75, 6, 34, 122, 123, 29, 21, 82, 83, 9, 42, 128, 129],
    [0, 16, 74, 75, 7, 35, 126, 127, 29, 21, 82, 83, 8, 41, 124, 125],
    [0, 21, 84, 85, 6, 42, 130, 131, 29, 16, 86, 87, 9, 34, 132, 133],
    [0, 21, 84, 85, 7, 41, 134, 135, 29, 16, 86, 87, 8, 35, 136, 137],
    [0, 16, 89, 88, 2, 17, 122, 123],
    [0, 16, 89, 88, 12, 33, 126, 127],
    [0, 16, 89, 88, 5, 19, 124, 125],
    [0, 16, 89, 88, 15, 30, 128, 129],
    [0, 16, 88, 89, 6, 34, 100, 101],
    [0, 16, 89, 88, 7, 35, 109, 108],
    [0, 16, 89, 88, 8, 41, 138, 139],
    [0, 16, 89, 88, 9, 42, 116, 117],
    [0, 16, 89, 88, 6, 34, 100, 101, 29, 21, 91, 90, 9, 42, 116, 117],
    [0, 16, 89, 88, 7, 35, 109, 108, 29, 21, 91, 90, 8, 41, 138, 139],
    [0, 16, 89, 88, 2, 17, 122, 123, 29, 21, 91, 90, 15, 30, 128, 129],
    [0, 16, 89, 88, 118, 121, 132, 131, 29, 21, 91, 90, 120, 119, 130, 133],
    [0, 16, 74, 75, 2, 17, 100, 101, 1, 52, 88, 89, 6, 34, 122, 123],
    [0, 16, 74, 75, 12, 33, 109, 108, 1, 52, 88, 89, 7, 35, 126, 127],
    [0, 16, 74, 75, 2, 17, 100, 101, 11, 55, 140, 141, 8, 41, 124, 125],
    [0, 16, 74, 75, 2, 17, 100, 101, 53, 54, 90, 91, 9, 42, 128, 129],
    [0, 16, 74, 75, 5, 19, 138, 139, 1, 52, 88, 89, 8, 41, 124, 125],
    [0, 16, 74, 75, 15, 30, 116, 117, 1, 52, 88, 89, 9, 42, 128, 129],
    [0, 16, 94, 95, 5, 19, 100, 101, 11, 55, 88, 89, 6, 34, 124, 125],
    [0, 16, 94, 95, 15, 30, 109, 108, 11, 55, 88, 89, 7, 35, 128, 129],
    [0, 16, 78, 79, 2, 17, 109, 108, 1, 52, 92, 93, 6, 34, 126, 127],
    [0, 16, 78, 79, 12, 33, 100, 101, 1, 52, 92, 93, 7, 35, 122, 123],
    [0, 16, 82, 83, 12, 33, 138, 139, 53, 54, 88, 89, 8, 41, 126, 127],
    [0, 16, 82, 83, 2, 17, 116, 117, 53, 54, 88, 89, 9, 42, 122, 123],
    [0, 16, 78, 79, 5, 19, 116, 117, 1, 52, 92, 93, 8, 41, 128, 129],
    [0, 16, 82, 83, 15, 30, 100, 101, 1, 52, 90, 91, 9, 42, 122, 123],
    [0, 16, 82, 83, 15, 30, 100, 101, 53, 54, 88, 89, 6, 34, 128, 129],
    [0, 16, 82, 83, 5, 19, 109, 108, 53, 54, 88, 89, 7, 35, 124, 125],
    [0, 16, 74, 75, 2, 17, 100, 101, 1, 52, 88, 89, 6, 34, 122, 123, 29, 21, 82, 83, 15, 30, 116, 117, 53, 54, 90, 91, 9, 42, 128, 129],
    [0, 16, 74, 75, 12, 33, 109, 108, 1, 52, 88, 89, 7, 35, 126, 127, 29, 21, 82, 83, 5, 19, 138, 139, 53, 54, 90, 91, 8, 41, 124, 125],
    [0, 21, 84, 85, 118, 119, 116, 101, 96, 97, 88, 91, 9, 34, 132, 133, 29, 16, 86, 87, 120, 121, 100, 117, 98, 99, 90, 89, 6, 42, 130, 131],
    [0, 21, 84, 85, 142, 143, 138, 108, 96, 97, 88, 91, 8, 35, 136, 137, 29, 16, 86, 87, 144, 145, 109, 139, 98, 99, 90, 89, 7, 41, 134, 135],
    [0, 146, 147],
    [0, 148, 149],
    [0, 150, 151],
    [0, 146, 147, 152, 153, 154, 155, 156, 157],
    [0, 158, 159],
    [0, 146, 147, 1, 160, 161],
    [0, 146, 147, 1, 160, 161, 152, 153, 154, 162, 163, 164, 155, 156, 157, 165, 166, 167],
    [0, 158, 159, 1, 168, 169],
    [0, 146, 147, 101, 170, 171],
    [0, 146, 147, 100, 172, 173],
    [0, 148, 149, 174, 175, 171],
    [0, 148, 149, 100, 176, 177],
    [0, 150, 151, 178, 179, 171],
    [0, 150, 151, 100, 180, 181],
    [0, 146, 147, 100, 172, 173, 152, 153, 154, 182, 183, 184, 155, 156, 157, 185, 186, 187],
    [0, 158, 159, 101, 188, 189],
    [0, 146, 147, 122, 190, 191],
    [0, 146, 147, 123, 192, 193],
    [0, 146, 147, 126, 194, 195],
    [0, 146, 147, 127, 196, 197],
    [0, 146, 147, 122, 190, 191, 152, 153, 154, 198, 199, 200, 155, 156, 157, 201, 202, 203],
    [0, 158, 159, 123, 204, 205],
    [0, 146, 147, 126, 194, 195, 152, 153, 154, 206, 207, 208, 155, 156, 157, 209, 210, 211],
    [0, 158, 159, 129, 212, 213],
    [0, 146, 147, 101, 170, 171, 1, 160, 161, 123, 192, 193],
    [0, 146, 147, 108, 214, 215, 1, 160, 161, 127, 196, 197],
    [0, 146, 147, 100, 172, 173, 1, 160, 161, 122, 190, 191],
    [0, 146, 147, 109, 216, 217, 1, 160, 161, 126, 194, 195],
    [0, 146, 147, 100, 172, 173, 1, 160, 161, 122, 190, 191, 152, 153, 154, 182, 183, 184, 162, 163, 164, 198, 199, 200, 155, 156, 157, 185, 186, 187, 165, 166, 167, 201, 202, 203],
    [0, 158, 159, 101, 188, 189, 1, 168, 169, 123, 204, 205],
    [0, 146, 147, 109, 216, 217, 1, 160, 161, 126, 194, 195, 152, 153, 154, 218, 219, 220, 162, 163, 164, 206, 207, 208, 155, 156, 157, 221, 222, 223, 165, 166, 167, 209, 210, 211],
    [0, 158, 159, 117, 224, 225, 1, 168, 169, 129, 212, 213],
    [0, 146, 147, 16, 226, 227],
    [0, 148, 149, 18, 228, 229],
    [0, 150, 151, 18, 230, 231],
    [0, 150, 151, 16, 232, 233],
    [0, 148, 149, 16, 234, 235],
    [0, 146, 147, 18, 236, 237],
    [0, 146, 147, 52, 238, 239],
    [0, 146, 147, 16, 226, 227, 1, 160, 161, 52, 238, 239],
    [0, 146, 147, 18, 236, 237, 1, 160, 161, 61, 240, 241],
    [0, 146, 147, 16, 226, 227, 100, 172, 173, 101, 170, 171],
    [0, 148, 149, 18, 228, 229, 242, 172, 181, 243, 214, 244],
    [0, 150, 151, 18, 230, 231, 245, 172, 177, 246, 214, 247],
    [0, 150, 151, 16, 232, 233, 245, 172, 177, 174, 170, 248],
    [0, 148, 149, 16, 234, 235, 242, 172, 181, 178, 170, 249],
    [0, 146, 147, 18, 236, 237, 100, 172, 173, 108, 214, 215],
    [0, 146, 147, 16, 226, 227, 122, 190, 191, 123, 192, 193],
    [0, 146, 147, 16, 226, 227, 126, 194, 195, 127, 196, 197],
    [0, 146, 147, 18, 236, 237, 126, 194, 195, 123, 192, 193],
    [0, 146, 147, 18, 236, 237, 122, 190, 191, 127, 196, 197],
    [0, 146, 147, 52, 238, 239, 122, 190, 191, 101, 170, 171],
    [0, 146, 147, 61, 240, 241, 126, 194, 195, 101, 170, 171],
    [0, 146, 147, 52, 238, 239, 100, 172, 173, 123, 192, 193],
    [0, 146, 147, 61, 240, 241, 100, 172, 173, 127, 196, 197],
    [0, 146, 147, 16, 226, 227, 100, 172, 173, 101, 170, 171, 1, 160, 161, 52, 239, 238, 122, 190, 191, 123, 192, 193],
    [0, 146, 147, 16, 226, 227, 109, 216, 217, 108, 214, 215, 1, 160, 161, 52, 239, 238, 126, 194, 195, 127, 196, 197],
    [0, 146, 147, 18, 236, 237, 109, 216, 217, 101, 170, 171, 1, 160, 161, 61, 241, 240, 126, 194, 195, 123, 192, 193],
    [0, 146, 147, 18, 236, 237, 100, 172, 173, 108, 214, 215, 1, 160, 161, 61, 241, 240, 122, 190, 191, 127, 196, 197],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 29, 21, 15, 30, 280, 281, 282, 283, 284, 285, 286, 287],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 29, 31, 32, 33, 280, 288, 289, 290, 284, 291, 292, 293],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 53, 54, 9, 42, 300, 301, 302, 303, 304, 305, 306, 307],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 64, 62, 14, 39, 308, 309, 310, 311, 312, 313, 314, 315, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 65, 59, 40, 38, 316, 317, 318, 319, 320, 321, 322, 323, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 11, 55, 8, 41, 324, 325, 326, 327, 328, 329, 330, 331],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 66, 67, 44, 45, 332, 333, 334, 335, 336, 337, 338, 339, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 68, 69, 46, 47, 340, 341, 342, 343, 344, 345, 346, 347, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 70, 71, 48, 49, 348, 349, 350, 351, 352, 353, 354, 355, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 72, 73, 50, 51, 356, 357, 358, 359, 360, 361, 362, 363],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 29, 21, 15, 30, 280, 281, 282, 283, 284, 285, 286, 287, 53, 54, 9, 42, 300, 301, 302, 303, 304, 305, 306, 307],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 1, 59, 14, 41, 168, 325, 318, 311, 169, 313, 330, 323],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 1, 59, 14, 41, 168, 325, 318, 311, 169, 313, 330, 323, 29, 31, 32, 33, 280, 288, 289, 290, 284, 291, 292, 293, 53, 63, 36, 35, 300, 364, 365, 366, 304, 367, 368, 369],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 138, 139, 95, 94, 406, 407, 408, 409, 410, 411, 412, 413],
    [0, 24, 5, 28, 158, 265, 258, 275, 159, 277, 270, 263, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 23, 16, 27, 19, 256, 273, 251, 267, 260, 269, 278, 255, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 26, 22, 13, 17, 264, 250, 274, 259, 268, 261, 254, 279, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 4, 20, 2, 25, 272, 257, 266, 252, 276, 253, 262, 271, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 29, 21, 15, 30, 280, 281, 282, 283, 284, 285, 286, 287, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 450, 415, 440, 429, 454, 431, 420, 445, 458, 447, 436, 425],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 29, 31, 32, 33, 280, 288, 289, 290, 284, 291, 292, 293, 450, 415, 440, 429, 454, 431, 420, 445, 458, 447, 436, 425],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 123, 122, 88, 89, 204, 474, 475, 476, 205, 477, 478, 479],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 123, 122, 88, 89, 204, 474, 475, 476, 205, 477, 478, 479, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 125, 124, 140, 141, 504, 505, 506, 507, 508, 509, 510, 511],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 123, 122, 88, 89, 204, 474, 475, 476, 205, 477, 478, 479, 29, 21, 15, 30, 280, 281, 282, 283, 284, 285, 286, 287, 129, 128, 90, 91, 212, 512, 513, 514, 213, 515, 516, 517],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 129, 128, 90, 91, 212, 512, 513, 514, 213, 515, 516, 517],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 129, 128, 90, 91, 212, 512, 513, 514, 213, 515, 516, 517, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 127, 126, 92, 93, 542, 543, 544, 545, 546, 547, 548, 549],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 29, 31, 32, 33, 280, 288, 289, 290, 284, 291, 292, 293, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 122, 123, 89, 88, 475, 476, 204, 474, 479, 478, 477, 205],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 53, 54, 9, 42, 300, 301, 302, 303, 304, 305, 306, 307, 128, 129, 91, 90, 513, 514, 212, 512, 517, 516, 515, 213],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 128, 129, 91, 90, 513, 514, 212, 512, 517, 516, 515, 213],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225, 53, 54, 9, 42, 300, 301, 302, 303, 304, 305, 306, 307, 122, 123, 89, 88, 475, 476, 204, 474, 479, 478, 477, 205],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 122, 123, 89, 88, 475, 476, 204, 474, 479, 478, 477, 205, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 64, 62, 14, 39, 308, 309, 310, 311, 312, 313, 314, 315, 481, 480, 483, 482, 486, 487, 484, 485, 491, 490, 489, 488, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 65, 59, 40, 38, 316, 317, 318, 319, 320, 321, 322, 323, 493, 492, 495, 494, 498, 499, 496, 497, 503, 502, 501, 500, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 138, 139, 95, 94, 406, 407, 408, 409, 410, 411, 412, 413, 11, 55, 8, 41, 324, 325, 326, 327, 328, 329, 330, 331, 124, 125, 141, 140, 506, 507, 504, 505, 511, 510, 509, 508],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 128, 129, 91, 90, 513, 514, 212, 512, 517, 516, 515, 213, 23, 24, 13, 25, 256, 257, 258, 259, 260, 261, 262, 263, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 64, 62, 14, 39, 308, 309, 310, 311, 312, 313, 314, 315, 519, 518, 521, 520, 524, 525, 522, 523, 529, 528, 527, 526, 26, 20, 27, 28, 264, 265, 266, 267, 268, 269, 270, 271, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 65, 59, 40, 38, 316, 317, 318, 319, 320, 321, 322, 323, 531, 530, 533, 532, 536, 537, 534, 535, 541, 540, 539, 538, 4, 22, 5, 19, 272, 273, 274, 275, 276, 277, 278, 279, 109, 108, 79, 78, 598, 599, 600, 601, 602, 603, 604, 605, 11, 55, 8, 41, 324, 325, 326, 327, 328, 329, 330, 331, 126, 127, 93, 92, 544, 545, 542, 543, 549, 548, 547, 546],
    [0, 24, 5, 28, 158, 265, 258, 275, 159, 277, 270, 263, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 66, 69, 50, 49, 332, 349, 342, 359, 336, 361, 354, 347, 493, 123, 483, 140, 498, 507, 204, 485, 503, 490, 509, 205, 23, 16, 27, 19, 256, 273, 251, 267, 260, 269, 278, 255, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 68, 67, 48, 51, 340, 357, 334, 351, 344, 353, 362, 339, 124, 480, 89, 494, 506, 499, 484, 474, 511, 478, 501, 488, 26, 22, 13, 17, 264, 250, 274, 259, 268, 261, 254, 279, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 70, 73, 46, 45, 348, 333, 358, 343, 352, 345, 338, 363, 122, 492, 141, 482, 475, 487, 496, 505, 479, 510, 489, 500, 4, 20, 2, 25, 272, 257, 266, 252, 276, 253, 262, 271, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 72, 71, 44, 47, 356, 341, 350, 335, 360, 337, 346, 355, 481, 125, 495, 88, 486, 476, 504, 497, 491, 502, 477, 508],
    [0, 24, 5, 28, 158, 265, 258, 275, 159, 277, 270, 263, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 531, 129, 521, 92, 536, 545, 212, 523, 541, 528, 547, 213, 23, 16, 27, 19, 256, 273, 251, 267, 260, 269, 278, 255, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 126, 518, 91, 532, 544, 537, 522, 512, 549, 516, 539, 526, 26, 22, 13, 17, 264, 250, 274, 259, 268, 261, 254, 279, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 128, 530, 93, 520, 513, 525, 534, 543, 517, 548, 527, 538, 4, 20, 2, 25, 272, 257, 266, 252, 276, 253, 262, 271, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 519, 127, 533, 90, 524, 514, 542, 535, 529, 540, 515, 546],
    [0, 16, 2, 17, 158, 250, 251, 252, 159, 253, 254, 255, 100, 101, 75, 74, 370, 371, 188, 372, 373, 374, 375, 189, 1, 52, 6, 34, 168, 294, 295, 296, 169, 297, 298, 299, 122, 123, 89, 88, 475, 476, 204, 474, 479, 478, 477, 205, 29, 21, 15, 30, 280, 281, 282, 283, 284, 285, 286, 287, 116, 117, 83, 82, 376, 377, 224, 378, 379, 380, 381, 225, 53, 54, 9, 42, 300, 301, 302, 303, 304, 305, 306, 307, 128, 129, 91, 90, 513, 514, 212, 512, 517, 516, 515, 213],
    [0, 20, 13, 19, 158, 273, 266, 259, 159, 261, 278, 271, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 1, 59, 14, 41, 168, 325, 318, 311, 169, 313, 330, 323, 551, 550, 553, 552, 556, 557, 554, 555, 561, 560, 559, 558, 29, 31, 32, 33, 280, 288, 289, 290, 284, 291, 292, 293, 450, 415, 440, 429, 454, 431, 420, 445, 458, 447, 436, 425, 53, 63, 36, 35, 300, 364, 365, 366, 304, 367, 368, 369, 563, 562, 565, 564, 568, 569, 566, 567, 573, 572, 571, 570],
    [0, 16],
    [0, 18],
    [0, 16, 26, 20],
    [0, 2, 23, 13],
    [0, 3, 4, 32],
    [0, 2, 29, 15],
    [0, 3, 29, 27],
    [0, 52],
    [0, 63],
    [0, 52, 26, 59],
    [0, 63, 26, 54],
    [0, 52, 16, 1],
    [0, 18, 1, 61],
    [0, 52, 16, 1, 26, 59, 20, 65],
    [0, 31, 1, 63],
    [0, 1, 24, 62],
    [0, 15, 1, 9],
    // X,Y,Z
    // -X+1/2,Y+1/2,-Z+1/2
    // -X,-Y,-Z
    // X+1/2,-Y+1/2,Z+1/2
    [0, 5, 1, 8],
    // X,Y,Z
    // -X+1/2,Y+1/2,-Z
    // -X,-Y,-Z
    // X+1/2,-Y+1/2,Z
    [0, 31, 1, 63, 26, 21, 65, 54],
    [0, 2, 57, 56],
    [0, 60, 3, 16],
    [0, 22, 57, 3],
    [0, 2, 28, 20],
    [0, 17, 13, 24],
    [0, 20, 19, 13, 4, 24, 17, 27],
    [0, 22, 57, 3, 4, 16, 60, 32],
    [0, 22, 57, 3, 23, 20, 30, 12, 26, 24, 33, 15, 4, 16, 60, 32],
    [0, 22, 57, 3, 29, 18, 27, 25],
    [0, 22, 3, 57, 1, 55, 10, 37],
    [0, 22, 385, 396, 3, 57, 109, 117],
    [0, 22, 57, 3, 159, 279, 654, 655, 158, 274, 656, 657, 29, 18, 25, 27, 284, 658, 262, 269, 280, 659, 257, 267],
];
var SpacegroupNameToIndexMap = {
    'P 1': 0,
    'P -1': 1,
    'P 1 2 1': 2,
    'P 1 21 1': 3,
    'C 1 2 1': 4,
    'P 1 m 1': 5,
    'P 1 c 1': 6,
    'C 1 m 1': 7,
    'C 1 c 1': 8,
    'P 1 2/m 1': 9,
    'P 1 21/m 1': 10,
    'C 1 2/m 1': 11,
    'P 1 2/c 1': 12,
    'P 1 21/c 1': 13,
    'C 1 2/c 1': 14,
    'P 2 2 2': 15,
    'P 2 2 21': 16,
    'P 21 21 2': 17,
    'P 21 21 21': 18,
    'C 2 2 21': 19,
    'C 2 2 2': 20,
    'F 2 2 2': 21,
    'I 2 2 2': 22,
    'I 21 21 21': 23,
    'P m m 2': 24,
    'P m c 21': 25,
    'P c c 2': 26,
    'P m a 2': 27,
    'P c a 21': 28,
    'P n c 2': 29,
    'P m n 21': 30,
    'P b a 2': 31,
    'P n a 21': 32,
    'P n n 2': 33,
    'C m m 2': 34,
    'C m c 21': 35,
    'C c c 2': 36,
    'A m m 2': 37,
    'A b m 2': 38,
    'A m a 2': 39,
    'A b a 2': 40,
    'F m m 2': 41,
    'F d d 2': 42,
    'I m m 2': 43,
    'I b a 2': 44,
    'I m a 2': 45,
    'P 2/m 2/m 2/m': 46,
    'P m m m': 46,
    'P 2/n 2/n 2/n': 47,
    'P n n n': 47,
    'P 2/c 2/c 2/m': 48,
    'P c c m': 48,
    'P 2/b 2/a 2/n': 49,
    'P b a n': 49,
    'P 21/m 2/m 2/a': 50,
    'P m m a': 50,
    'P 2/n 21/n 2/a': 51,
    'P n n a': 51,
    'P 2/m 2/n 21/a': 52,
    'P m n a': 52,
    'P 21/c 2/c 2/a': 53,
    'P c c a': 53,
    'P 21/b 21/a 2/m': 54,
    'P b a m': 54,
    'P 21/c 21/c 2/n': 55,
    'P c c n': 55,
    'P 2/b 21/c 21/m': 56,
    'P b c m': 56,
    'P 21/n 21/n 2/m': 57,
    'P n n m': 57,
    'P 21/m 21/m 2/n': 58,
    'P m m n': 58,
    'P 21/b 2/c 21/n': 59,
    'P b c n': 59,
    'P 21/b 21/c 21/a': 60,
    'P b c a': 60,
    'P 21/n 21/m 21/a': 61,
    'P n m a': 61,
    'C 2/m 2/c 21/m': 62,
    'C m c m': 62,
    'C 2/m 2/c 21/a': 63,
    'C m c a': 63,
    'C 2/m 2/m 2/m': 64,
    'C m m m': 64,
    'C 2/c 2/c 2/m': 65,
    'C c c m': 65,
    'C 2/m 2/m 2/a': 66,
    'C m m a': 66,
    'C 2/c 2/c 2/a': 67,
    'C c c a': 67,
    'F 2/m 2/m 2/m': 68,
    'F m m m': 68,
    'F 2/d 2/d 2/d': 69,
    'F d d d': 69,
    'I 2/m 2/m 2/m': 70,
    'I m m m': 70,
    'I 2/b 2/a 2/m': 71,
    'I b a m': 71,
    'I 21/b 21/c 21/a': 72,
    'I b c a': 72,
    'I 21/m 21/m 21/a': 73,
    'I m m a': 73,
    'P 4': 74,
    'P 41': 75,
    'P 42': 76,
    'P 43': 77,
    'I 4': 78,
    'I 41': 79,
    'P -4': 80,
    'I -4': 81,
    'P 4/m': 82,
    'P 42/m': 83,
    'P 4/n': 84,
    'P 42/n': 85,
    'I 4/m': 86,
    'I 41/a': 87,
    'P 4 2 2': 88,
    'P 4 21 2': 89,
    'P 41 2 2': 90,
    'P 41 21 2': 91,
    'P 42 2 2': 92,
    'P 42 21 2': 93,
    'P 43 2 2': 94,
    'P 43 21 2': 95,
    'I 4 2 2': 96,
    'I 41 2 2': 97,
    'P 4 m m': 98,
    'P 4 b m': 99,
    'P 42 c m': 100,
    'P 42 n m': 101,
    'P 4 c c': 102,
    'P 4 n c': 103,
    'P 42 m c': 104,
    'P 42 b c': 105,
    'I 4 m m': 106,
    'I 4 c m': 107,
    'I 41 m d': 108,
    'I 41 c d': 109,
    'P -4 2 m': 110,
    'P -4 2 c': 111,
    'P -4 21 m': 112,
    'P -4 21 c': 113,
    'P -4 m 2': 114,
    'P -4 c 2': 115,
    'P -4 b 2': 116,
    'P -4 n 2': 117,
    'I -4 m 2': 118,
    'I -4 c 2': 119,
    'I -4 2 m': 120,
    'I -4 2 d': 121,
    'P 4/m 2/m 2/m': 122,
    'P4/m m m': 122,
    'P 4/m 2/c 2/c': 123,
    'P4/m c c': 123,
    'P 4/n 2/b 2/m': 124,
    'P4/n b m': 124,
    'P 4/n 2/n 2/c': 125,
    'P4/n n c': 125,
    'P 4/m 21/b 2/m': 126,
    'P4/m b m': 126,
    'P 4/m 21/n 2/c': 127,
    'P4/m n c': 127,
    'P 4/n 21/m 2/m': 128,
    'P4/n m m': 128,
    'P 4/n 2/c 2/c': 129,
    'P4/n c c': 129,
    'P 42/m 2/m 2/c': 130,
    'P42/m m c': 130,
    'P 42/m 2/c 2/m': 131,
    'P42/m c m': 131,
    'P 42/n 2/b 2/c': 132,
    'P42/n b c': 132,
    'P 42/n 2/n 2/m': 133,
    'P42/n n m': 133,
    'P 42/m 21/b 2/c': 134,
    'P42/m b c': 134,
    'P 42/m 21/n 2/m': 135,
    'P42/m n m': 135,
    'P 42/n 21/m 2/c': 136,
    'P42/n m c': 136,
    'P 42/n 21/c 2/m': 137,
    'P42/n c m': 137,
    'I 4/m 2/m 2/m': 138,
    'I4/m m m': 138,
    'I 4/m 2/c 2/m': 139,
    'I4/m c m': 139,
    'I 41/a 2/m 2/d': 140,
    'I41/a m d': 140,
    'I 41/a 2/c 2/d': 141,
    'I41/a c d': 141,
    'P 3': 142,
    'P 31': 143,
    'P 32': 144,
    'H 3': 145,
    'R 3': 146,
    'P -3': 147,
    'H -3': 148,
    'R -3': 149,
    'P 3 1 2': 150,
    'P 3 2 1': 151,
    'P 31 1 2': 152,
    'P 31 2 1': 153,
    'P 32 1 2': 154,
    'P 32 2 1': 155,
    'H 3 2': 156,
    'R 3 2': 157,
    'P 3 m 1': 158,
    'P 3 1 m': 159,
    'P 3 c 1': 160,
    'P 3 1 c': 161,
    'H 3 m': 162,
    'R 3 m': 163,
    'H 3 c': 164,
    'R 3 c': 165,
    'P -3 1 2/m': 166,
    'P -3 1 m': 166,
    'P -3 1 2/c': 167,
    'P -3 1 c': 167,
    'P -3 2/m 1': 168,
    'P -3 m 1': 168,
    'P -3 2/c 1': 169,
    'P -3 c 1': 169,
    'H -3 2/m': 170,
    'H -3 m': 170,
    'R -3 2/m': 171,
    'R -3 m': 171,
    'H -3 2/c': 172,
    'H -3 c': 172,
    'R -3 2/c': 173,
    'R -3 c': 173,
    'P 6': 174,
    'P 61': 175,
    'P 65': 176,
    'P 62': 177,
    'P 64': 178,
    'P 63': 179,
    'P -6': 180,
    'P 6/m': 181,
    'P 63/m': 182,
    'P 6 2 2': 183,
    'P 61 2 2': 184,
    'P 65 2 2': 185,
    'P 62 2 2': 186,
    'P 64 2 2': 187,
    'P 63 2 2': 188,
    'P 6 m m': 189,
    'P 6 c c': 190,
    'P 63 c m': 191,
    'P 63 m c': 192,
    'P -6 m 2': 193,
    'P -6 c 2': 194,
    'P -6 2 m': 195,
    'P -6 2 c': 196,
    'P 6/m 2/m 2/m': 197,
    'P 6/m m m': 197,
    'P 6/m 2/c 2/c': 198,
    'P 6/m c c': 198,
    'P 63/m 2/c 2/m': 199,
    'P 63/m c m': 199,
    'P 63/m 2/m 2/c': 200,
    'P 63/m m c': 200,
    'P 2 3': 201,
    'F 2 3': 202,
    'I 2 3': 203,
    'P 21 3': 204,
    'I 21 3': 205,
    'P 2/m -3': 206,
    'P m -3': 206,
    'P 2/n -3': 207,
    'P n -3': 207,
    'F 2/m -3': 208,
    'F m -3': 208,
    'F 2/d -3': 209,
    'F d -3': 209,
    'I 2/m -3': 210,
    'I m -3': 210,
    'P 21/a -3': 211,
    'P a -3': 211,
    'I 21/a -3': 212,
    'I a -3': 212,
    'P 4 3 2': 213,
    'P 42 3 2': 214,
    'F 4 3 2': 215,
    'F 41 3 2': 216,
    'I 4 3 2': 217,
    'P 43 3 2': 218,
    'P 41 3 2': 219,
    'I 41 3 2': 220,
    'P -4 3 m': 221,
    'F -4 3 m': 222,
    'I -4 3 m': 223,
    'P -4 3 n': 224,
    'F -4 3 c': 225,
    'I -4 3 d': 226,
    'P 4/m -3 2/m': 227,
    'P m -3 m': 227,
    'P 4/n -3 2/n': 228,
    'P n -3 n': 228,
    'P 42/m -3 2/n': 229,
    'P m -3 n': 229,
    'P 42/n -3 2/m': 230,
    'P n -3 m': 230,
    'F 4/m -3 2/m': 231,
    'F m -3 m': 231,
    'F 4/m -3 2/c': 232,
    'F m -3 c': 232,
    'F 41/d -3 2/m': 233,
    'F d -3 m': 233,
    'F 41/d -3 2/c': 234,
    'F d -3 c': 234,
    'I 4/m -3 2/m': 235,
    'I m -3 m': 235,
    'I 41/a -3 2/d': 236,
    'I a -3 d': 236,
    'P 1 1 2': 237,
    'P 1 1 21': 238,
    'B 1 1 2': 239,
    'B 2': 239,
    'A 1 2 1': 240,
    'C 1 21 1': 241,
    'I 1 2 1': 242,
    'I 2': 242,
    'I 1 21 1': 243,
    'P 1 1 m': 244,
    'P 1 1 b': 245,
    'B 1 1 m': 246,
    'B 1 1 b': 247,
    'P 1 1 2/m': 248,
    'P 1 1 21/m': 249,
    'B 1 1 2/m': 250,
    'P 1 1 2/b': 251,
    'P 1 1 21/b': 252,
    'P 1 21/n 1': 253,
    'P 1 21/a 1': 254,
    'B 1 1 2/b': 255,
    'P 21 2 2': 256,
    'P 2 21 2': 257,
    'P 21 21 2 (a)': 258,
    'P 21 2 21': 259,
    'P 2 21 21': 260,
    'C 2 2 21a)': 261,
    'C 2 2 2a': 262,
    'F 2 2 2a': 263,
    'I 2 2 2a': 264,
    'P 21/m 21/m 2/n a': 265,
    'P 42 21 2a': 266,
    'I 2 3a': 267,
};
function getSpacegroupIndexFromNumber(num) {
    // 38 spacegroup variants as given CCP4s symop.lib
    switch (num) {
        case 1146: return 146;
        case 1148: return 149;
        case 1155: return 157;
        case 1160: return 163;
        case 1161: return 165;
        case 1166: return 171;
        case 1167: return 173;
        case 1003: return 237; // 'P 1 1 2'  !(dyad along z)
        case 1004: return 238; // 'P 1 1 21'  !(unique axis c)
        case 1005: return 239; // 'B 1 1 2' 'B 2'
        case 2005: return 240; // 'A 1 2 1'
        case 3005: return 241; // 'C 1 21 1' ! (Origin on screw at 1/4X)
        case 4005: return 242; // 'I 1 2 1' 'I 2' !!! GJK @ 2003-06-02
        case 5005: return 243; // 'I 1 21 1'
        case 1006: return 244; // 'P 1 1 m'
        case 1007: return 245; // 'P 1 1 b'
        case 1008: return 246; // 'B 1 1 m'
        case 1009: return 247; // 'B 1 1 b'
        case 1010: return 248; // 'P 1 1 2/m'
        case 1011: return 249; // 'P 1 1 21/m'
        case 1012: return 250; // 'B 1 1 2/m'
        case 1013: return 251; // 'P 1 1 2/b'
        case 1014: return 252; // 'P 1 1 21/b'
        case 2014: return 253; // 'P 1 21/n 1'
        case 3014: return 254; // 'P 1 21/a 1'
        case 1015: return 255; // 'B 1 1 2/b'
        case 1017: return 256; // 'P 21 2 2' !(unique axis a)
        case 2017: return 257; // 'P 2 21 2' !(unique axis b)
        case 1018: return 258; // 'P 21 21 2 (a)' ! origin on 21 21, shift (1/4,1/4,0)
        case 2018: return 259; // 'P 21 2 21'  !(unique axis b)
        case 3018: return 260; // 'P 2 21 21'  !(unique axis a)
        case 1020: return 261; // 'C 2 2 21a)' ! P212121 with C centring, shift(1/4,0,0)
        case 1021: return 262; // 'C 2 2 2a'  ! C21212a origin on 21 21
        case 1022: return 263; // 'F 2 2 2a' ! same as 1018 with face centring  shift (1/4,0,0)
        case 1023: return 264; // 'I 2 2 2a'  ! as 1018 with origin shift (1/4,1/4,1/4)
        case 1059: return 265; // 'P 21/m 21/m 2/n a'
        case 1094: return 266; // 'P 42 21 2a' ! (as P21212a) origin on 21 21 ie Shift 1/4,1/4,1/4
        case 1197: return 267; // 'I 2 3a' ! Expansion of 1023 which is an expansion of 1018
    }
    var offset = 0;
    if (num > 146)
        ++offset;
    if (num > 148)
        ++offset;
    if (num > 155)
        ++offset;
    if (num > 160)
        ++offset;
    if (num > 161)
        ++offset;
    if (num > 166)
        ++offset;
    if (num > 167)
        ++offset;
    return num - 1 + offset;
}
function getSpacegroupNumberFromIndex(idx) {
    if (idx < 146)
        return idx + 1;
    if (idx === 146)
        return 1146;
    if (idx < 149)
        return idx + 1 - 1;
    if (idx === 149)
        return 1148;
    if (idx < 157)
        return idx + 1 - 2;
    if (idx === 157)
        return 1155;
    if (idx < 163)
        return idx + 1 - 3;
    if (idx === 163)
        return 1160;
    if (idx < 165)
        return idx + 1 - 4;
    if (idx === 165)
        return 1161;
    if (idx < 171)
        return idx + 1 - 5;
    if (idx === 171)
        return 1166;
    if (idx < 173)
        return idx + 1 - 6;
    if (idx === 173)
        return 1167;
    if (idx < 237)
        return idx + 1 - 7;
    if (idx === 237)
        return 1003;
    if (idx === 238)
        return 1004;
    if (idx === 239)
        return 1005;
    if (idx === 240)
        return 2005;
    if (idx === 241)
        return 3005;
    if (idx === 242)
        return 4005;
    if (idx === 243)
        return 5005;
    if (idx === 244)
        return 1006;
    if (idx === 245)
        return 1007;
    if (idx === 246)
        return 1008;
    if (idx === 247)
        return 1009;
    if (idx === 248)
        return 1010;
    if (idx === 249)
        return 1011;
    if (idx === 250)
        return 1012;
    if (idx === 251)
        return 1013;
    if (idx === 252)
        return 1014;
    if (idx === 253)
        return 2014;
    if (idx === 254)
        return 3014;
    if (idx === 255)
        return 1015;
    if (idx === 256)
        return 1017;
    if (idx === 257)
        return 2017;
    if (idx === 258)
        return 1018;
    if (idx === 259)
        return 2018;
    if (idx === 260)
        return 3018;
    if (idx === 261)
        return 1020;
    if (idx === 262)
        return 1021;
    if (idx === 263)
        return 1022;
    if (idx === 264)
        return 1023;
    if (idx === 265)
        return 1059;
    if (idx === 266)
        return 1094;
    if (idx === 267)
        return 1197;
    throw new Error("unknown spacegroup index '" + idx + "'");
}
/** Maps spacegroup index to Hermann-Mauguin spacegroup name */
var SpacegroupName = (function () {
    var names = Object.create(null);
    for (var _i = 0, _a = Object.keys(SpacegroupNameToIndexMap); _i < _a.length; _i++) {
        var n = _a[_i];
        names[SpacegroupNameToIndexMap[n]] = n;
    }
    return names;
}());
/** Maps spacegroup index to spacegroup number from International Tables for Crystallography */
var SpacegroupNumber = (function () {
    var numbers = Object.create(null);
    for (var _i = 0, _a = Object.keys(SpacegroupNameToIndexMap); _i < _a.length; _i++) {
        var n = _a[_i];
        var idx = SpacegroupNameToIndexMap[n];
        numbers[idx] = getSpacegroupNumberFromIndex(idx);
    }
    return numbers;
}());
/** return -1 if the spacegroup does not exist */
function getSpacegroupIndex(nameOrNumber) {
    var index = typeof nameOrNumber === 'number'
        ? getSpacegroupIndexFromNumber(nameOrNumber)
        : SpacegroupNameToIndexMap[nameOrNumber];
    if (typeof index === 'undefined' || typeof SpacegroupName[index] === 'undefined')
        return -1;
    return index;
}
//# sourceMappingURL=tables.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/spacegroup/construction.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var construction_SpacegroupCell;
(function (SpacegroupCell) {
    /** Create a 'P 1' with cellsize [1, 1, 1] */
    SpacegroupCell.Zero = create('P 1', linear_algebra["Vec3"].create(1, 1, 1), linear_algebra["Vec3"].create(Math.PI / 2, Math.PI / 2, Math.PI / 2));
    /** True if 'P 1' with cellsize [1, 1, 1] */
    function isZero(cell) {
        if (!cell)
            return true;
        return cell.index === 0 && cell.size[0] === 1 && cell.size[1] === 1 && cell.size[1] === 1;
    }
    SpacegroupCell.isZero = isZero;
    /** Returns Zero cell if the spacegroup does not exist */
    function create(nameOrNumber, size, anglesInRadians) {
        var index = getSpacegroupIndex(nameOrNumber);
        if (index < 0) {
            console.warn("Unknown spacegroup '" + nameOrNumber + "', returning a 'P 1' with cellsize [1, 1, 1]");
            return SpacegroupCell.Zero;
        }
        var volume = size[0] * size[1] * size[2];
        var alpha = anglesInRadians[0];
        var beta = anglesInRadians[1];
        var gamma = anglesInRadians[2];
        var xScale = size[0], yScale = size[1], zScale = size[2];
        var z1 = Math.cos(beta);
        var z2 = (Math.cos(alpha) - Math.cos(beta) * Math.cos(gamma)) / Math.sin(gamma);
        var z3 = Math.sqrt(1.0 - z1 * z1 - z2 * z2);
        var x = [xScale, 0.0, 0.0];
        var y = [Math.cos(gamma) * yScale, Math.sin(gamma) * yScale, 0.0];
        var z = [z1 * zScale, z2 * zScale, z3 * zScale];
        var fromFractional = linear_algebra["Mat4"].ofRows([
            [x[0], y[0], z[0], 0],
            [0, y[1], z[1], 0],
            [0, 0, z[2], 0],
            [0, 0, 0, 1.0]
        ]);
        var toFractional = linear_algebra["Mat4"].invert(linear_algebra["Mat4"].zero(), fromFractional);
        return { index: index, size: size, volume: volume, anglesInRadians: anglesInRadians, toFractional: toFractional, fromFractional: fromFractional };
    }
    SpacegroupCell.create = create;
})(construction_SpacegroupCell || (construction_SpacegroupCell = {}));
var construction_Spacegroup;
(function (Spacegroup) {
    /** P1 with [1, 1, 1] cell */
    Spacegroup.ZeroP1 = create(construction_SpacegroupCell.Zero);
    function create(cell) {
        var operators = GroupData[cell.index].map(function (i) { return getOperatorMatrix(OperatorData[i]); });
        var name = SpacegroupName[cell.index];
        var num = SpacegroupNumber[cell.index];
        return { name: name, num: num, cell: cell, operators: operators };
    }
    Spacegroup.create = create;
    var _ijkVec = Object(linear_algebra["Vec3"])();
    var _tempMat = Object(linear_algebra["Mat4"])();
    function setOperatorMatrix(spacegroup, index, i, j, k, target) {
        linear_algebra["Vec3"].set(_ijkVec, i, j, k);
        linear_algebra["Mat4"].fromTranslation(_tempMat, _ijkVec);
        return linear_algebra["Mat4"].mul(target, linear_algebra["Mat4"].mul(target, linear_algebra["Mat4"].mul(target, spacegroup.cell.fromFractional, _tempMat), spacegroup.operators[index]), spacegroup.cell.toFractional);
    }
    Spacegroup.setOperatorMatrix = setOperatorMatrix;
    function getSymmetryOperator(spacegroup, spgrOp, i, j, k) {
        var operator = setOperatorMatrix(spacegroup, spgrOp, i, j, k, linear_algebra["Mat4"].zero());
        return symmetry_operator["a" /* SymmetryOperator */].create(spgrOp + 1 + "_" + (5 + i) + (5 + j) + (5 + k), operator, { hkl: linear_algebra["Vec3"].create(i, j, k), spgrOp: spgrOp });
    }
    Spacegroup.getSymmetryOperator = getSymmetryOperator;
    var _translationRef = Object(linear_algebra["Vec3"])();
    var _translationRefSymop = Object(linear_algebra["Vec3"])();
    var _translationSymop = Object(linear_algebra["Vec3"])();
    function setOperatorMatrixRef(spacegroup, index, i, j, k, ref, target) {
        linear_algebra["Vec3"].set(_ijkVec, i, j, k);
        linear_algebra["Vec3"].floor(_translationRef, ref);
        linear_algebra["Mat4"].copy(target, spacegroup.operators[index]);
        linear_algebra["Vec3"].floor(_translationRefSymop, linear_algebra["Vec3"].transformMat4(_translationRefSymop, ref, target));
        linear_algebra["Mat4"].getTranslation(_translationSymop, target);
        linear_algebra["Vec3"].sub(_translationSymop, _translationSymop, _translationRefSymop);
        linear_algebra["Vec3"].add(_translationSymop, _translationSymop, _translationRef);
        linear_algebra["Vec3"].add(_translationSymop, _translationSymop, _ijkVec);
        linear_algebra["Mat4"].setTranslation(target, _translationSymop);
        linear_algebra["Mat4"].mul(target, spacegroup.cell.fromFractional, target);
        linear_algebra["Mat4"].mul(target, target, spacegroup.cell.toFractional);
        return target;
    }
    Spacegroup.setOperatorMatrixRef = setOperatorMatrixRef;
    /**
     * Get Symmetry operator for transformation around the given
     * reference point `ref` in fractional coordinates
     */
    function getSymmetryOperatorRef(spacegroup, spgrOp, i, j, k, ref) {
        var operator = setOperatorMatrixRef(spacegroup, spgrOp, i, j, k, ref, linear_algebra["Mat4"].zero());
        return symmetry_operator["a" /* SymmetryOperator */].create(spgrOp + 1 + "_" + (5 + i) + (5 + j) + (5 + k), operator, { hkl: linear_algebra["Vec3"].create(i, j, k), spgrOp: spgrOp });
    }
    Spacegroup.getSymmetryOperatorRef = getSymmetryOperatorRef;
    function getOperatorMatrix(ids) {
        var r1 = TransformData[ids[0]];
        var r2 = TransformData[ids[1]];
        var r3 = TransformData[ids[2]];
        return linear_algebra["Mat4"].ofRows([r1, r2, r3, [0, 0, 0, 1]]);
    }
    function getOperatorXyz(op) {
        return [
            formatElement(getRotation(op[0], op[4], op[8]), getShift(op[12])),
            formatElement(getRotation(op[1], op[5], op[9]), getShift(op[13])),
            formatElement(getRotation(op[2], op[6], op[10]), getShift(op[14]))
        ].join(',');
    }
    Spacegroup.getOperatorXyz = getOperatorXyz;
    function getRotation(x, y, z) {
        var r = [];
        if (x > 0)
            r.push('+X');
        else if (x < 0)
            r.push('-X');
        if (y > 0)
            r.push('+Y');
        else if (y < 0)
            r.push('-Y');
        if (z > 0)
            r.push('+Z');
        else if (z < 0)
            r.push('-Z');
        if (r.length === 1) {
            return r[0].charAt(0) === '+' ? r[0].substr(1) : r[0];
        }
        if (r.length === 2) {
            var s0 = r[0].charAt(0);
            var s1 = r[1].charAt(0);
            if (s0 === '+')
                return "" + r[0].substr(1) + r[1];
            if (s1 === '+')
                return "" + r[1].substr(1) + r[0];
        }
        throw new Error("unknown rotation '" + r + "', " + x + " " + y + " " + z);
    }
    function getShift(s) {
        switch (s) {
            case 1 / 2: return '1/2';
            case 1 / 4: return '1/4';
            case 3 / 4: return '3/4';
            case 1 / 3: return '1/3';
            case 2 / 3: return '2/3';
            case 1 / 6: return '1/6';
            case 5 / 6: return '5/6';
        }
        return '';
    }
    function formatElement(rotation, shift) {
        if (shift === '')
            return rotation;
        if (rotation.length > 2)
            return rotation + "+" + shift;
        return rotation.charAt(0) === '-' ? "" + shift + rotation : shift + "+" + rotation;
    }
})(construction_Spacegroup || (construction_Spacegroup = {}));

//# sourceMappingURL=construction.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/lookup3d/common.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var Result;
(function (Result) {
    function add(result, index, distSq) {
        result.squaredDistances[result.count] = distSq;
        result.indices[result.count++] = index;
    }
    Result.add = add;
    function reset(result) {
        result.count = 0;
    }
    Result.reset = reset;
    function create() {
        return { count: 0, indices: [], squaredDistances: [] };
    }
    Result.create = create;
    function copy(out, result) {
        for (var i = 0; i < result.count; ++i) {
            out.indices[i] = result.indices[i];
            out.squaredDistances[i] = result.squaredDistances[i];
        }
        out.count = result.count;
        return out;
    }
    Result.copy = copy;
})(Result || (Result = {}));
//# sourceMappingURL=common.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/primitives/box3d.js
var box3d = __webpack_require__(230);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/lookup3d/grid.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function GridLookup3D(data, boundary, cellSizeOrCount) {
    return new GridLookup3DImpl(data, boundary, cellSizeOrCount);
}

var GridLookup3DImpl = /** @class */ (function () {
    function GridLookup3DImpl(data, boundary, cellSizeOrCount) {
        var structure = build(data, boundary, cellSizeOrCount);
        this.ctx = createContext(structure);
        this.boundary = { box: structure.boundingBox, sphere: structure.boundingSphere };
        this.buckets = { offset: structure.bucketOffset, count: structure.bucketCounts, array: structure.bucketArray };
        this.result = this.ctx.result;
    }
    GridLookup3DImpl.prototype.find = function (x, y, z, radius) {
        this.ctx.x = x;
        this.ctx.y = y;
        this.ctx.z = z;
        this.ctx.radius = radius;
        this.ctx.isCheck = false;
        query(this.ctx);
        return this.ctx.result;
    };
    GridLookup3DImpl.prototype.check = function (x, y, z, radius) {
        this.ctx.x = x;
        this.ctx.y = y;
        this.ctx.z = z;
        this.ctx.radius = radius;
        this.ctx.isCheck = true;
        return query(this.ctx);
    };
    return GridLookup3DImpl;
}());
function _build(state) {
    var expandedBox = state.expandedBox, _a = state.size, sX = _a[0], sY = _a[1], sZ = _a[2], _b = state.data, px = _b.x, py = _b.y, pz = _b.z, radius = _b.radius, indices = _b.indices, elementCount = state.elementCount, delta = state.delta;
    var n = sX * sY * sZ;
    var _c = expandedBox.min, minX = _c[0], minY = _c[1], minZ = _c[2];
    var maxRadius = 0;
    var bucketCount = 0;
    var grid = new Uint32Array(n);
    var bucketIndex = new Int32Array(elementCount);
    for (var t = 0; t < elementCount; t++) {
        var i = mol_data_int["OrderedSet"].getAt(indices, t);
        var x = Math.floor((px[i] - minX) / delta[0]);
        var y = Math.floor((py[i] - minY) / delta[1]);
        var z = Math.floor((pz[i] - minZ) / delta[2]);
        var idx = (((x * sY) + y) * sZ) + z;
        if ((grid[idx] += 1) === 1) {
            bucketCount += 1;
        }
        bucketIndex[t] = idx;
    }
    if (radius) {
        for (var t = 0; t < elementCount; t++) {
            var i = mol_data_int["OrderedSet"].getAt(indices, t);
            if (radius[i] > maxRadius)
                maxRadius = radius[i];
        }
    }
    var bucketCounts = new Int32Array(bucketCount);
    for (var i = 0, j = 0; i < n; i++) {
        var c = grid[i];
        if (c > 0) {
            grid[i] = j + 1;
            bucketCounts[j] = c;
            j += 1;
        }
    }
    var bucketOffset = new Uint32Array(bucketCount);
    for (var i = 1; i < bucketCount; ++i) {
        bucketOffset[i] += bucketOffset[i - 1] + bucketCounts[i - 1];
    }
    var bucketFill = new Int32Array(bucketCount);
    var bucketArray = new Int32Array(elementCount);
    for (var i = 0; i < elementCount; i++) {
        var bucketIdx = grid[bucketIndex[i]];
        if (bucketIdx > 0) {
            var k = bucketIdx - 1;
            bucketArray[bucketOffset[k] + bucketFill[k]] = i;
            bucketFill[k] += 1;
        }
    }
    return {
        size: state.size,
        bucketArray: bucketArray,
        bucketCounts: bucketCounts,
        bucketOffset: bucketOffset,
        grid: grid,
        delta: delta,
        min: state.expandedBox.min,
        data: state.data,
        maxRadius: maxRadius,
        expandedBox: state.expandedBox,
        boundingBox: state.boundingBox,
        boundingSphere: state.boundingSphere
    };
}
function build(data, boundary, cellSizeOrCount) {
    // need to expand the grid bounds to avoid rounding errors
    var expandedBox = box3d["a" /* Box3D */].expand(box3d["a" /* Box3D */].empty(), boundary.box, linear_algebra["Vec3"].create(0.5, 0.5, 0.5));
    var indices = data.indices;
    var S = box3d["a" /* Box3D */].size(linear_algebra["Vec3"].zero(), expandedBox);
    var delta, size;
    var elementCount = mol_data_int["OrderedSet"].size(indices);
    var cellCount = typeof cellSizeOrCount === 'number' ? cellSizeOrCount : 32;
    var cellSize = Array.isArray(cellSizeOrCount) && cellSizeOrCount;
    if (cellSize) {
        size = [Math.ceil(S[0] / cellSize[0]), Math.ceil(S[1] / cellSize[1]), Math.ceil(S[2] / cellSize[2])];
        delta = cellSize;
    }
    else if (elementCount > 0) {
        // size of the box
        // required "grid volume" so that each cell contains on average 'cellCount' elements.
        var V = Math.ceil(elementCount / cellCount);
        var f = Math.pow(V / (S[0] * S[1] * S[2]), 1 / 3);
        size = [Math.ceil(S[0] * f), Math.ceil(S[1] * f), Math.ceil(S[2] * f)];
        delta = [S[0] / size[0], S[1] / size[1], S[2] / size[2]];
    }
    else {
        delta = S;
        size = [1, 1, 1];
    }
    var inputData = {
        x: data.x,
        y: data.y,
        z: data.z,
        indices: indices,
        radius: data.radius
    };
    var state = {
        size: size,
        data: inputData,
        expandedBox: expandedBox,
        boundingBox: boundary.box,
        boundingSphere: boundary.sphere,
        elementCount: elementCount,
        delta: delta
    };
    return _build(state);
}
function createContext(grid) {
    return { grid: grid, x: 0.1, y: 0.1, z: 0.1, radius: 0.1, result: Result.create(), isCheck: false };
}
function query(ctx) {
    var _a = ctx.grid, min = _a.min, _b = _a.size, sX = _b[0], sY = _b[1], sZ = _b[2], bucketOffset = _a.bucketOffset, bucketCounts = _a.bucketCounts, bucketArray = _a.bucketArray, grid = _a.grid, _c = _a.data, px = _c.x, py = _c.y, pz = _c.z, indices = _c.indices, radius = _c.radius, delta = _a.delta, maxRadius = _a.maxRadius;
    var inputRadius = ctx.radius, isCheck = ctx.isCheck, x = ctx.x, y = ctx.y, z = ctx.z, result = ctx.result;
    var r = inputRadius + maxRadius;
    var rSq = r * r;
    Result.reset(result);
    var loX = Math.max(0, Math.floor((x - r - min[0]) / delta[0]));
    var loY = Math.max(0, Math.floor((y - r - min[1]) / delta[1]));
    var loZ = Math.max(0, Math.floor((z - r - min[2]) / delta[2]));
    var hiX = Math.min(sX - 1, Math.floor((x + r - min[0]) / delta[0]));
    var hiY = Math.min(sY - 1, Math.floor((y + r - min[1]) / delta[1]));
    var hiZ = Math.min(sZ - 1, Math.floor((z + r - min[2]) / delta[2]));
    if (loX > hiX || loY > hiY || loZ > hiZ)
        return false;
    for (var ix = loX; ix <= hiX; ix++) {
        for (var iy = loY; iy <= hiY; iy++) {
            for (var iz = loZ; iz <= hiZ; iz++) {
                var bucketIdx = grid[(((ix * sY) + iy) * sZ) + iz];
                if (bucketIdx === 0)
                    continue;
                var k = bucketIdx - 1;
                var offset = bucketOffset[k];
                var count = bucketCounts[k];
                var end = offset + count;
                for (var i = offset; i < end; i++) {
                    var idx = mol_data_int["OrderedSet"].getAt(indices, bucketArray[i]);
                    var dx = px[idx] - x;
                    var dy = py[idx] - y;
                    var dz = pz[idx] - z;
                    var distSq = dx * dx + dy * dy + dz * dz;
                    if (distSq <= rSq) {
                        if (maxRadius > 0 && Math.sqrt(distSq) - radius[idx] > inputRadius)
                            continue;
                        if (isCheck)
                            return true;
                        Result.add(result, bucketArray[i], distSq);
                    }
                }
            }
        }
    }
    return result.count > 0;
}
//# sourceMappingURL=grid.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/primitives/sphere3d.js
var sphere3d = __webpack_require__(274);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/primitives/axes3d.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function axes3d_Axes3D() {
    return axes3d_Axes3D.empty();
}
(function (Axes3D) {
    function create(origin, dirA, dirB, dirC) { return { origin: origin, dirA: dirA, dirB: dirB, dirC: dirC }; }
    Axes3D.create = create;
    function empty() { return { origin: Object(linear_algebra["Vec3"])(), dirA: Object(linear_algebra["Vec3"])(), dirB: Object(linear_algebra["Vec3"])(), dirC: Object(linear_algebra["Vec3"])() }; }
    Axes3D.empty = empty;
    function copy(out, a) {
        linear_algebra["Vec3"].copy(out.origin, a.origin);
        linear_algebra["Vec3"].copy(out.dirA, a.dirA);
        linear_algebra["Vec3"].copy(out.dirB, a.dirB);
        linear_algebra["Vec3"].copy(out.dirC, a.dirC);
        return out;
    }
    Axes3D.copy = copy;
    function clone(a) {
        return copy(empty(), a);
    }
    Axes3D.clone = clone;
    /** Get size of each direction */
    function size(size, axes) {
        return linear_algebra["Vec3"].set(size, linear_algebra["Vec3"].magnitude(axes.dirA) * 2, linear_algebra["Vec3"].magnitude(axes.dirB) * 2, linear_algebra["Vec3"].magnitude(axes.dirC) * 2);
    }
    Axes3D.size = size;
    var tmpSizeV = Object(linear_algebra["Vec3"])();
    /** Get volume of the oriented box wrapping the axes */
    function volume(axes) {
        size(tmpSizeV, axes);
        return tmpSizeV[0] * tmpSizeV[1] * tmpSizeV[2];
    }
    Axes3D.volume = volume;
    function normalize(out, a) {
        linear_algebra["Vec3"].copy(out.origin, a.origin);
        linear_algebra["Vec3"].normalize(out.dirA, a.dirA);
        linear_algebra["Vec3"].normalize(out.dirB, a.dirB);
        linear_algebra["Vec3"].normalize(out.dirC, a.dirC);
        return out;
    }
    Axes3D.normalize = normalize;
    var tmpTransformMat3 = linear_algebra["Mat3"].zero();
    /** Transform axes with a Mat4 */
    function transform(out, a, m) {
        linear_algebra["Vec3"].transformMat4(out.origin, a.origin, m);
        var n = linear_algebra["Mat3"].directionTransform(tmpTransformMat3, m);
        linear_algebra["Vec3"].transformMat3(out.dirA, a.dirA, n);
        linear_algebra["Vec3"].transformMat3(out.dirB, a.dirB, n);
        linear_algebra["Vec3"].transformMat3(out.dirC, a.dirC, n);
        return out;
    }
    Axes3D.transform = transform;
})(axes3d_Axes3D || (axes3d_Axes3D = {}));

//# sourceMappingURL=axes3d.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








//# sourceMappingURL=geometry.js.map

/***/ }),
/* 12 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ MolScriptSymbolTable; });

// UNUSED EXPORTS: SymbolList, SymbolMap

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table/core.js
var core = __webpack_require__(202);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table/structure-query.js
var structure_query = __webpack_require__(219);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/type.js
var type = __webpack_require__(15);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol.js
var symbol = __webpack_require__(18);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/helpers.js
var helpers = __webpack_require__(42);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table/internal.js
/**
 * Copyright (c) 2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var generator = {
    '@header': 'Generators',
    bundleElement: Object(helpers["b" /* symbol */])(symbol["b" /* Arguments */].Dictionary({
        // TODO: should we use more universal unit keys? (i.e. based on chain and "operator name")
        groupedUnits: Object(symbol["a" /* Argument */])(type["a" /* default */].Any),
        set: Object(symbol["a" /* Argument */])(type["a" /* default */].Any),
        ranges: Object(symbol["a" /* Argument */])(type["a" /* default */].Any) // SortedArray<UnitIndex>
    }), type["a" /* default */].Any),
    bundle: Object(helpers["b" /* symbol */])(symbol["b" /* Arguments */].Dictionary({
        elements: Object(symbol["a" /* Argument */])(type["a" /* default */].Any) // BundleElement[]
    }), structure_query["a" /* Types */].ElementSelectionQuery, 'A selection with single structure containing represented by the bundle.'),
    // Use with caution as this is not "state saveable"
    // This query should never be used in any State Transform!
    current: Object(helpers["b" /* symbol */])(symbol["b" /* Arguments */].None, structure_query["a" /* Types */].ElementSelectionQuery, 'Current selection provided by the query context. Avoid using this in State Transforms.')
};
/* harmony default export */ var internal = ({
    '@header': 'Internal Queries',
    generator: generator
});
//# sourceMappingURL=internal.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table.js
/**
 * Copyright (c) 2017 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var MolScriptSymbolTable = { core: core["b" /* default */], structureQuery: structure_query["b" /* default */], internal: internal };
Object(helpers["a" /* normalizeTable */])(MolScriptSymbolTable);
var SymbolList = Object(helpers["c" /* symbolList */])(MolScriptSymbolTable);
var SymbolMap = (function () {
    var map = Object.create(null);
    for (var _i = 0, SymbolList_1 = SymbolList; _i < SymbolList_1.length; _i++) {
        var s = SymbolList_1[_i];
        map[s.id] = s;
    }
    return map;
})();

//# sourceMappingURL=symbol-table.js.map

/***/ }),
/* 13 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StateObject", function() { return /* reexport */ object_StateObject; });
__webpack_require__.d(__webpack_exports__, "StateObjectCell", function() { return /* reexport */ StateObjectCell; });
__webpack_require__.d(__webpack_exports__, "StateObjectTracker", function() { return /* reexport */ object_StateObjectTracker; });
__webpack_require__.d(__webpack_exports__, "StateObjectSelector", function() { return /* reexport */ StateObjectSelector; });
__webpack_require__.d(__webpack_exports__, "StateObjectRef", function() { return /* reexport */ StateObjectRef; });
__webpack_require__.d(__webpack_exports__, "StateTree", function() { return /* reexport */ immutable_StateTree; });
__webpack_require__.d(__webpack_exports__, "TransientTree", function() { return /* reexport */ transient_TransientTree; });
__webpack_require__.d(__webpack_exports__, "State", function() { return /* reexport */ state_State; });
__webpack_require__.d(__webpack_exports__, "StateBuilder", function() { return /* reexport */ builder_StateBuilder; });
__webpack_require__.d(__webpack_exports__, "StateSelection", function() { return /* reexport */ selection_StateSelection; });
__webpack_require__.d(__webpack_exports__, "StateTransformer", function() { return /* reexport */ mol_state_transformer["a" /* StateTransformer */]; });
__webpack_require__.d(__webpack_exports__, "StateTransform", function() { return /* reexport */ mol_state_transform["a" /* StateTransform */]; });
__webpack_require__.d(__webpack_exports__, "StateAction", function() { return /* reexport */ mol_state_action["a" /* StateAction */]; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/object.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var object_StateObject;
(function (StateObject) {
    function factory() {
        return function (type) { return create(type); };
    }
    StateObject.factory = factory;
    function create(type) {
        var _a;
        return _a = /** @class */ (function () {
                function O(data, props) {
                    this.data = data;
                    this.id = mol_util["c" /* UUID */].create22();
                    this.type = type;
                    this.label = props && props.label || type.name;
                    this.description = props && props.description;
                }
                O.is = function (obj) { return !!obj && type === obj.type; };
                return O;
            }()),
            _a.type = type,
            _a;
    }
    StateObject.create = create;
    function hasTag(o, t) {
        if (!o.tags)
            return false;
        for (var _i = 0, _a = o.tags; _i < _a.length; _i++) {
            var s = _a[_i];
            if (s === t)
                return true;
        }
        return false;
    }
    StateObject.hasTag = hasTag;
    /** A special object indicating a transformer result has no value. */
    StateObject.Null = {
        id: mol_util["c" /* UUID */].create22(),
        type: { name: 'Null', typeClass: 'Null' },
        data: void 0,
        label: 'Null'
    };
})(object_StateObject || (object_StateObject = {}));
var StateObjectCell;
(function (StateObjectCell) {
    function is(o) {
        var c = o;
        return !!c && !!c.transform && !!c.parent && !!c.status;
    }
    StateObjectCell.is = is;
    function resolve(state, refOrCellOrSelector) {
        var ref = typeof refOrCellOrSelector === 'string'
            ? refOrCellOrSelector
            : StateObjectCell.is(refOrCellOrSelector)
                ? refOrCellOrSelector.transform.ref
                : refOrCellOrSelector.ref;
        return state.cells.get(ref);
    }
    StateObjectCell.resolve = resolve;
})(StateObjectCell || (StateObjectCell = {}));
// TODO: improve the API?
var object_StateObjectTracker = /** @class */ (function () {
    function StateObjectTracker(state) {
        this.state = state;
        this.version = '';
    }
    StateObjectTracker.prototype.setQuery = function (sel) {
        this.query = selection_StateSelection.compile(sel);
    };
    StateObjectTracker.prototype.update = function () {
        var cell = this.state.select(this.query)[0];
        var version = cell ? cell.transform.version : void 0;
        var changed = this.cell !== cell || this.version !== version;
        this.cell = cell;
        this.version = version || '';
        this.data = cell && cell.obj ? cell.obj.data : void 0;
        return changed;
    };
    return StateObjectTracker;
}());

var StateObjectSelector = /** @class */ (function () {
    function StateObjectSelector(ref, state) {
        this.ref = ref;
        this.state = state;
    }
    Object.defineProperty(StateObjectSelector.prototype, "cell", {
        get: function () {
            var _a;
            return (_a = this.state) === null || _a === void 0 ? void 0 : _a.cells.get(this.ref);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StateObjectSelector.prototype, "obj", {
        get: function () {
            var _a, _b;
            return (_b = (_a = this.state) === null || _a === void 0 ? void 0 : _a.cells.get(this.ref)) === null || _b === void 0 ? void 0 : _b.obj;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StateObjectSelector.prototype, "data", {
        get: function () {
            var _a;
            return (_a = this.obj) === null || _a === void 0 ? void 0 : _a.data;
        },
        enumerable: false,
        configurable: true
    });
    StateObjectSelector.prototype.update = function (params, builder) {
        if (!this.state)
            throw new Error("To use update() from StateObjectSelector, 'state' must be defined.");
        if (!builder)
            builder = this.state.build();
        (builder || this.state.build()).to(this).update(params);
        return builder;
    };
    /** Checks if the object exists. If not throw an error. */
    StateObjectSelector.prototype.checkValid = function () {
        if (!this.state) {
            throw new Error('Unassigned State.');
        }
        var cell = this.cell;
        if (!cell) {
            throw new Error("Not created at all. Did you await/then the corresponding state update?");
        }
        if (cell.status === 'ok')
            return true;
        if (cell.status === 'error')
            throw new Error(cell.errorText);
        if (cell.obj === object_StateObject.Null)
            throw new Error('The object is Null.');
        throw new Error("Unresolved. Did you await/then the corresponding state update?");
    };
    Object.defineProperty(StateObjectSelector.prototype, "isOk", {
        get: function () {
            var cell = this.cell;
            return cell && cell.status === 'ok' && cell.obj !== object_StateObject.Null;
        },
        enumerable: false,
        configurable: true
    });
    return StateObjectSelector;
}());

var StateObjectRef;
(function (StateObjectRef) {
    function resolveRef(ref) {
        var _a;
        if (!ref)
            return;
        if (typeof ref === 'string')
            return ref;
        if (StateObjectCell.is(ref))
            return ref.transform.ref;
        return (_a = ref.cell) === null || _a === void 0 ? void 0 : _a.transform.ref;
    }
    StateObjectRef.resolveRef = resolveRef;
    function resolve(state, ref) {
        if (!ref)
            return;
        if (StateObjectCell.is(ref))
            return ref;
        if (typeof ref === 'string')
            return state.cells.get(ref);
        return ref.cell;
    }
    StateObjectRef.resolve = resolve;
    function resolveAndCheck(state, ref) {
        var cell = resolve(state, ref);
        if (!cell || !cell.obj || cell.status !== 'ok')
            return;
        return cell;
    }
    StateObjectRef.resolveAndCheck = resolveAndCheck;
})(StateObjectRef || (StateObjectRef = {}));
//# sourceMappingURL=object.js.map
// EXTERNAL MODULE: ./node_modules/immutable/dist/immutable.js
var immutable = __webpack_require__(102);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/transform.js
var mol_state_transform = __webpack_require__(76);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/tree/transient.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var transient_TransientTree = /** @class */ (function () {
    function TransientTree(tree) {
        this.tree = tree;
        this.transforms = this.tree.transforms;
        this.children = this.tree.children;
        this.dependencies = this.tree.dependencies;
        this.changedNodes = false;
        this.changedChildren = false;
        this.changedDependencies = false;
        this._childMutations = void 0;
        this._dependencyMutations = void 0;
        this._stateUpdates = void 0;
    }
    Object.defineProperty(TransientTree.prototype, "childMutations", {
        get: function () {
            if (this._childMutations)
                return this._childMutations;
            this._childMutations = new Map();
            return this._childMutations;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(TransientTree.prototype, "dependencyMutations", {
        get: function () {
            if (this._dependencyMutations)
                return this._dependencyMutations;
            this._dependencyMutations = new Map();
            return this._dependencyMutations;
        },
        enumerable: false,
        configurable: true
    });
    TransientTree.prototype.changeNodes = function () {
        if (this.changedNodes)
            return;
        this.changedNodes = true;
        this.transforms = this.transforms.asMutable();
    };
    TransientTree.prototype.changeChildren = function () {
        if (this.changedChildren)
            return;
        this.changedChildren = true;
        this.children = this.children.asMutable();
    };
    TransientTree.prototype.changeDependencies = function () {
        if (this.changedDependencies)
            return;
        this.changedDependencies = true;
        this.dependencies = this.dependencies.asMutable();
    };
    Object.defineProperty(TransientTree.prototype, "root", {
        get: function () { return this.transforms.get(mol_state_transform["a" /* StateTransform */].RootRef); },
        enumerable: false,
        configurable: true
    });
    TransientTree.prototype.asTransient = function () {
        return this.asImmutable().asTransient();
    };
    TransientTree.prototype.addChild = function (parent, child) {
        this.changeChildren();
        if (this.childMutations.has(parent)) {
            this.childMutations.get(parent).add(child);
        }
        else {
            var set = this.children.get(parent).asMutable();
            set.add(child);
            this.children.set(parent, set);
            this.childMutations.set(parent, set);
        }
    };
    TransientTree.prototype.removeChild = function (parent, child) {
        this.changeChildren();
        if (this.childMutations.has(parent)) {
            this.childMutations.get(parent).remove(child);
        }
        else {
            var set = this.children.get(parent).asMutable();
            set.remove(child);
            this.children.set(parent, set);
            this.childMutations.set(parent, set);
        }
    };
    TransientTree.prototype.clearRoot = function () {
        var parent = mol_state_transform["a" /* StateTransform */].RootRef;
        if (this.children.get(parent).size === 0)
            return;
        this.changeChildren();
        var set = Object(immutable["OrderedSet"])();
        this.children.set(parent, set);
        this.childMutations.set(parent, set);
    };
    TransientTree.prototype.mutateDependency = function (parent, child, action) {
        var set = this.dependencyMutations.get(parent);
        if (!set) {
            var src = this.dependencies.get(parent);
            if (!src && action === 'remove')
                return;
            this.changeDependencies();
            set = src ? src.asMutable() : Object(immutable["OrderedSet"])().asMutable();
            this.dependencyMutations.set(parent, set);
            this.dependencies.set(parent, set);
        }
        if (action === 'add') {
            set.add(child);
        }
        else {
            set.remove(child);
        }
    };
    TransientTree.prototype.changeParent = function (ref, newParent) {
        ensurePresent(this.transforms, ref);
        var old = this.transforms.get(ref);
        this.removeChild(old.parent, ref);
        this.addChild(newParent, ref);
        this.changeNodes();
        this.transforms.set(ref, mol_state_transform["a" /* StateTransform */].withParent(old, newParent));
    };
    TransientTree.prototype.add = function (transform) {
        var ref = transform.ref;
        if (this.transforms.has(transform.ref)) {
            var node = this.transforms.get(transform.ref);
            if (node.parent !== transform.parent)
                alreadyPresent(transform.ref);
        }
        var children = this.children.get(transform.parent);
        if (!children)
            parentNotPresent(transform.parent);
        if (!children.has(transform.ref)) {
            this.addChild(transform.parent, transform.ref);
        }
        if (!this.children.has(transform.ref)) {
            if (!this.changedChildren) {
                this.changedChildren = true;
                this.children = this.children.asMutable();
            }
            this.children.set(transform.ref, Object(immutable["OrderedSet"])());
        }
        this.changeNodes();
        this.transforms.set(ref, transform);
        if (transform.dependsOn) {
            for (var _i = 0, _a = transform.dependsOn; _i < _a.length; _i++) {
                var d = _a[_i];
                this.mutateDependency(d, ref, 'add');
            }
        }
        return this;
    };
    /** Calls Transform.definition.params.areEqual if available, otherwise uses shallowEqual to check if the params changed */
    TransientTree.prototype.setParams = function (ref, params) {
        ensurePresent(this.transforms, ref);
        var transform = this.transforms.get(ref);
        // TODO: should this be here?
        if (Object(object["d" /* shallowEqual */])(transform.params, params)) {
            return false;
        }
        if (!this.changedNodes) {
            this.changedNodes = true;
            this.transforms = this.transforms.asMutable();
        }
        this.transforms.set(transform.ref, mol_state_transform["a" /* StateTransform */].withParams(transform, params));
        return true;
    };
    /** Calls Transform.definition.params.areEqual if available, otherwise uses shallowEqual to check if the params changed */
    TransientTree.prototype.setTags = function (ref, tags) {
        ensurePresent(this.transforms, ref);
        var transform = this.transforms.get(ref);
        var withTags = mol_state_transform["a" /* StateTransform */].withParams(transform, tags);
        // TODO: should this be here?
        if (Object(array["arrayEqual"])(transform.tags, withTags.tags)) {
            return false;
        }
        if (!this.changedNodes) {
            this.changedNodes = true;
            this.transforms = this.transforms.asMutable();
        }
        this.transforms.set(transform.ref, withTags);
        return true;
    };
    TransientTree.prototype.assignState = function (ref, state) {
        ensurePresent(this.transforms, ref);
        var old = this.transforms.get(ref);
        if (this._stateUpdates && this._stateUpdates.has(ref)) {
            mol_state_transform["a" /* StateTransform */].assignState(old.state, state);
            return old;
        }
        else {
            if (!this._stateUpdates)
                this._stateUpdates = new Set();
            this._stateUpdates.add(old.ref);
            this.changeNodes();
            var updated = mol_state_transform["a" /* StateTransform */].withState(old, state);
            this.transforms.set(ref, updated);
            return updated;
        }
    };
    TransientTree.prototype.remove = function (ref) {
        var node = this.transforms.get(ref);
        if (!node)
            return [];
        var st = immutable_StateTree.subtreePostOrder(this, node);
        if (ref === mol_state_transform["a" /* StateTransform */].RootRef) {
            st.pop();
            if (st.length === 0)
                return st;
            this.clearRoot();
        }
        else {
            if (st.length === 0)
                return st;
            this.removeChild(node.parent, node.ref);
        }
        this.changeNodes();
        this.changeChildren();
        for (var _i = 0, st_1 = st; _i < st_1.length; _i++) {
            var n = st_1[_i];
            this.transforms.delete(n.ref);
            this.children.delete(n.ref);
            if (this._childMutations)
                this._childMutations.delete(n.ref);
        }
        var depRemoves = [];
        for (var _a = 0, st_2 = st; _a < st_2.length; _a++) {
            var n = st_2[_a];
            if (n.dependsOn) {
                for (var _b = 0, _c = n.dependsOn; _b < _c.length; _b++) {
                    var d = _c[_b];
                    if (!this.transforms.has(d))
                        continue;
                    this.mutateDependency(d, n.ref, 'remove');
                }
            }
            if (this.dependencies.has(n.ref)) {
                var deps = this.dependencies.get(n.ref).toArray();
                this.changeDependencies();
                this.dependencies.delete(n.ref);
                if (this._dependencyMutations)
                    this._dependencyMutations.delete(n.ref);
                for (var _d = 0, deps_1 = deps; _d < deps_1.length; _d++) {
                    var dep = deps_1[_d];
                    if (!this.transforms.has(dep))
                        continue;
                    for (var _e = 0, _f = this.remove(dep); _e < _f.length; _e++) {
                        var del = _f[_e];
                        depRemoves[depRemoves.length] = del;
                    }
                }
            }
        }
        for (var _g = 0, depRemoves_1 = depRemoves; _g < depRemoves_1.length; _g++) {
            var dep = depRemoves_1[_g];
            st[st.length] = dep;
        }
        return st;
    };
    TransientTree.prototype.asImmutable = function () {
        if (!this.changedNodes && !this.changedChildren && !this._childMutations)
            return this.tree;
        if (this._childMutations)
            this._childMutations.forEach(fixChildMutations, this.children);
        if (this._dependencyMutations)
            this._dependencyMutations.forEach(fixDependencyMutations, this.dependencies);
        return immutable_StateTree.create(this.changedNodes ? this.transforms.asImmutable() : this.transforms, this.changedChildren ? this.children.asImmutable() : this.children, this.changedDependencies ? this.dependencies.asImmutable() : this.dependencies);
    };
    return TransientTree;
}());
function fixChildMutations(m, k) {
    this.set(k, m.asImmutable());
}
function fixDependencyMutations(m, k) {
    if (m.size === 0)
        this.delete(k);
    else
        this.set(k, m.asImmutable());
}
function alreadyPresent(ref) {
    throw new Error("Transform '" + ref + "' is already present in the tree.");
}
function parentNotPresent(ref) {
    throw new Error("Parent '" + ref + "' must be present in the tree.");
}
function ensurePresent(nodes, ref) {
    if (!nodes.has(ref)) {
        throw new Error("Node '" + ref + "' is not present in the tree.");
    }
}
//# sourceMappingURL=transient.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/tree/immutable.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var immutable_StateTree;
(function (StateTree) {
    var Impl = /** @class */ (function () {
        function Impl(transforms, children, dependencies) {
            this.transforms = transforms;
            this.children = children;
            this.dependencies = dependencies;
        }
        Object.defineProperty(Impl.prototype, "root", {
            get: function () { return this.transforms.get(mol_state_transform["a" /* StateTransform */].RootRef); },
            enumerable: false,
            configurable: true
        });
        Impl.prototype.asTransient = function () {
            return new transient_TransientTree(this);
        };
        return Impl;
    }());
    /**
     * Create an instance of an immutable tree.
     */
    function createEmpty(customRoot) {
        var root = customRoot || mol_state_transform["a" /* StateTransform */].createRoot();
        return create(Object(immutable["Map"])([[root.ref, root]]), Object(immutable["Map"])([[root.ref, Object(immutable["OrderedSet"])()]]), Object(immutable["Map"])());
    }
    StateTree.createEmpty = createEmpty;
    function create(nodes, children, dependencies) {
        return new Impl(nodes, children, dependencies);
    }
    StateTree.create = create;
    function _postOrderFunc(c) { _doPostOrder(this, this.tree.transforms.get(c)); }
    function _doPostOrder(ctx, root) {
        var children = ctx.tree.children.get(root.ref);
        if (children && children.size) {
            children.forEach(_postOrderFunc, ctx);
        }
        ctx.f(root, ctx.tree, ctx.state);
    }
    /**
     * Visit all nodes in a subtree in "post order", meaning leafs get visited first.
     */
    function doPostOrder(tree, root, state, f) {
        var ctx = { tree: tree, state: state, f: f };
        _doPostOrder(ctx, root);
        return ctx.state;
    }
    StateTree.doPostOrder = doPostOrder;
    function _preOrderFunc(c) { _doPreOrder(this, this.tree.transforms.get(c)); }
    function _doPreOrder(ctx, root) {
        var ret = ctx.f(root, ctx.tree, ctx.state);
        if (typeof ret === 'boolean' && !ret)
            return;
        var children = ctx.tree.children.get(root.ref);
        if (children && children.size) {
            children.forEach(_preOrderFunc, ctx);
        }
    }
    /**
     * Visit all nodes in a subtree in "pre order", meaning leafs get visited last.
     * If the visitor function returns false, the visiting for that branch is interrupted.
     */
    function doPreOrder(tree, root, state, f) {
        var ctx = { tree: tree, state: state, f: f };
        _doPreOrder(ctx, root);
        return ctx.state;
    }
    StateTree.doPreOrder = doPreOrder;
    function _subtree(n, _, subtree) { subtree.push(n); }
    /**
     * Get all nodes in a subtree, leafs come first.
     */
    function subtreePostOrder(tree, root) {
        return doPostOrder(tree, root, [], _subtree);
    }
    StateTree.subtreePostOrder = subtreePostOrder;
    function _visitNodeToJson(node, tree, ctx) {
        // const children: Ref[] = [];
        // tree.children.get(node.ref).forEach(_visitChildToJson as any, children);
        ctx.push(mol_state_transform["a" /* StateTransform */].toJSON(node));
    }
    function toJSON(tree) {
        var transforms = [];
        doPreOrder(tree, tree.root, transforms, _visitNodeToJson);
        return { transforms: transforms };
    }
    StateTree.toJSON = toJSON;
    function fromJSON(data) {
        var nodes = Object(immutable["Map"])().asMutable();
        var children = Object(immutable["Map"])().asMutable();
        var dependencies = Object(immutable["Map"])().asMutable();
        for (var _i = 0, _a = data.transforms; _i < _a.length; _i++) {
            var t = _a[_i];
            var transform = mol_state_transform["a" /* StateTransform */].fromJSON(t);
            nodes.set(transform.ref, transform);
            if (!children.has(transform.ref)) {
                children.set(transform.ref, Object(immutable["OrderedSet"])().asMutable());
            }
            if (transform.ref !== transform.parent)
                children.get(transform.parent).add(transform.ref);
        }
        var dependent = new Set();
        for (var _b = 0, _c = data.transforms; _b < _c.length; _b++) {
            var t = _c[_b];
            var ref = t.ref;
            children.set(ref, children.get(ref).asImmutable());
            if (!t.dependsOn)
                continue;
            for (var _d = 0, _e = t.dependsOn; _d < _e.length; _d++) {
                var d = _e[_d];
                dependent.add(d);
                if (!dependencies.has(d)) {
                    dependencies.set(d, Object(immutable["OrderedSet"])([ref]).asMutable());
                }
                else {
                    dependencies.get(d).add(ref);
                }
            }
        }
        dependent.forEach(function (d) {
            dependencies.set(d, dependencies.get(d).asImmutable());
        });
        return create(nodes.asImmutable(), children.asImmutable(), dependencies.asImmutable());
    }
    StateTree.fromJSON = fromJSON;
    function dump(tree) {
        console.log({
            tr: tree.transforms.keySeq().toArray(),
            tr1: tree.transforms.valueSeq().toArray().map(function (t) { return t.ref; }),
            ch: tree.children.keySeq().toArray()
        });
    }
    StateTree.dump = dump;
    function _subtreeHasRef(tree, root, ref) {
        if (root === ref)
            return true;
        var children = tree.children.get(root);
        var it = children.values();
        while (true) {
            var next = it.next();
            if (next.done)
                return false;
            if (_subtreeHasRef(tree, next.value, ref))
                return true;
        }
    }
    /** Check if the subtree with the given root has the provided ref */
    function subtreeHasRef(tree, root, ref) {
        if (!tree.transforms.has(root) || !tree.transforms.has(ref))
            return false;
        return _subtreeHasRef(tree, root, ref);
    }
    StateTree.subtreeHasRef = subtreeHasRef;
    function getDecoratorRoot(tree, ref) {
        var children = tree.children.get(ref);
        if (children.size !== 1)
            return ref;
        var child = tree.transforms.get(children.first());
        if (child.transformer.definition.isDecorator)
            return getDecoratorRoot(tree, child.ref);
        return ref;
    }
    StateTree.getDecoratorRoot = getDecoratorRoot;
})(immutable_StateTree || (immutable_StateTree = {}));
//# sourceMappingURL=immutable.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/tree.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



//# sourceMappingURL=tree.js.map
// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/transformer.js
var mol_state_transformer = __webpack_require__(191);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/state/selection.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var selection_StateSelection;
(function (StateSelection) {
    function select(s, state) {
        return compile(s)(state);
    }
    StateSelection.select = select;
    function compile(s) {
        var selector = s ? s : Generators.root;
        var query;
        if (isBuilder(selector))
            query = selector.compile();
        else if (isObj(selector))
            query = Generators.byValue(selector).compile();
        else if (isQuery(selector))
            query = selector;
        else
            query = Generators.byRef(selector).compile();
        return query;
    }
    StateSelection.compile = compile;
    function isObj(arg) {
        return arg.transform !== void 0 && arg.status !== void 0;
    }
    function isBuilder(arg) {
        return arg.compile !== void 0;
    }
    function isQuery(arg) {
        return typeof arg === 'function';
    }
    var BuilderPrototype = {
        select: function (state) {
            return select(this, state || this.state);
        }
    };
    function registerModifier(name, f) {
        BuilderPrototype[name] = function () {
            var args = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                args[_i] = arguments[_i];
            }
            return f.call.apply(f, Object(tslib_es6["__spreadArrays"])([void 0, this], args));
        };
    }
    function build(compile) {
        return Object.create(BuilderPrototype, { compile: { writable: false, configurable: false, value: compile } });
    }
    var Generators;
    (function (Generators) {
        Generators.root = build(function () { return function (state) { return [state.cells.get(state.tree.root.ref)]; }; });
        function byRef() {
            var refs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                refs[_i] = arguments[_i];
            }
            return build(function () { return function (state) {
                var ret = [];
                for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
                    var ref = refs_1[_i];
                    var n = state.cells.get(ref);
                    if (!n)
                        continue;
                    ret.push(n);
                }
                return ret;
            }; });
        }
        Generators.byRef = byRef;
        function byValue() {
            var objects = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                objects[_i] = arguments[_i];
            }
            return build(function () { return function (state) { return objects; }; });
        }
        Generators.byValue = byValue;
        function rootsOfType(type, root) {
            if (root === void 0) { root = mol_state_transform["a" /* StateTransform */].RootRef; }
            return build(function () { return function (state) {
                var ctx = { roots: [], cells: state.cells, type: type.type };
                immutable_StateTree.doPreOrder(state.tree, state.tree.transforms.get(root), ctx, _findRootsOfType);
                return ctx.roots;
            }; });
        }
        Generators.rootsOfType = rootsOfType;
        function ofType(type, root) {
            if (root === void 0) { root = mol_state_transform["a" /* StateTransform */].RootRef; }
            return build(function () { return function (state) {
                var ctx = { ret: [], cells: state.cells, type: type.type };
                immutable_StateTree.doPreOrder(state.tree, state.tree.transforms.get(root), ctx, _findOfType);
                return ctx.ret;
            }; });
        }
        Generators.ofType = ofType;
        function ofTransformer(t, root) {
            if (root === void 0) { root = mol_state_transform["a" /* StateTransform */].RootRef; }
            return build(function () { return function (state) {
                var ctx = { ret: [], cells: state.cells, t: t };
                immutable_StateTree.doPreOrder(state.tree, state.tree.transforms.get(root), ctx, _findOfTransformer);
                return ctx.ret;
            }; });
        }
        Generators.ofTransformer = ofTransformer;
        function ofTransformerWithError(t, root) {
            if (root === void 0) { root = mol_state_transform["a" /* StateTransform */].RootRef; }
            return build(function () { return function (state) {
                var ctx = { ret: [], cells: state.cells, t: t };
                immutable_StateTree.doPreOrder(state.tree, state.tree.transforms.get(root), ctx, _findOfTransformerWithError);
                return ctx.ret;
            }; });
        }
        Generators.ofTransformerWithError = ofTransformerWithError;
        function _findRootsOfType(n, _, s) {
            var cell = s.cells.get(n.ref);
            if (cell && cell.obj && cell.obj.type === s.type) {
                s.roots.push(cell);
                return false;
            }
            return true;
        }
        function _findOfType(n, _, s) {
            var cell = s.cells.get(n.ref);
            if (cell && cell.obj && cell.obj.type === s.type) {
                s.ret.push(cell);
            }
            return true;
        }
        function _findOfTransformer(n, _, s) {
            var cell = s.cells.get(n.ref);
            if (cell && cell.obj && cell.transform.transformer === s.t) {
                s.ret.push(cell);
            }
            return true;
        }
        function _findOfTransformerWithError(n, _, s) {
            var cell = s.cells.get(n.ref);
            if (cell && cell.status === 'error' && cell.transform.transformer === s.t) {
                s.ret.push(cell);
            }
            return true;
        }
    })(Generators = StateSelection.Generators || (StateSelection.Generators = {}));
    registerModifier('flatMap', flatMap);
    function flatMap(b, f) {
        var q = compile(b);
        return build(function () { return function (state) {
            var ret = [];
            for (var _i = 0, _a = q(state); _i < _a.length; _i++) {
                var n = _a[_i];
                for (var _b = 0, _c = f(n, state); _b < _c.length; _b++) {
                    var m = _c[_b];
                    ret.push(m);
                }
            }
            return ret;
        }; });
    }
    StateSelection.flatMap = flatMap;
    registerModifier('mapObject', mapObject);
    function mapObject(b, f) {
        var q = compile(b);
        return build(function () { return function (state) {
            var ret = [];
            for (var _i = 0, _a = q(state); _i < _a.length; _i++) {
                var n = _a[_i];
                var x = f(n, state);
                if (x)
                    ret.push(x);
            }
            return ret;
        }; });
    }
    StateSelection.mapObject = mapObject;
    registerModifier('unique', unique);
    function unique(b) {
        var q = compile(b);
        return build(function () { return function (state) {
            var set = new Set();
            var ret = [];
            for (var _i = 0, _a = q(state); _i < _a.length; _i++) {
                var n = _a[_i];
                if (!n)
                    continue;
                if (!set.has(n.transform.ref)) {
                    set.add(n.transform.ref);
                    ret.push(n);
                }
            }
            return ret;
        }; });
    }
    StateSelection.unique = unique;
    registerModifier('first', first);
    function first(b) {
        var q = compile(b);
        return build(function () { return function (state) {
            var r = q(state);
            return r.length ? [r[0]] : [];
        }; });
    }
    StateSelection.first = first;
    registerModifier('filter', filter);
    function filter(b, p) { return flatMap(b, function (n) { return p(n) ? [n] : []; }); }
    StateSelection.filter = filter;
    registerModifier('withStatus', withStatus);
    function withStatus(b, s) { return filter(b, function (n) { return n.status === s; }); }
    StateSelection.withStatus = withStatus;
    registerModifier('withTag', withTag);
    function withTag(b, tag) { return filter(b, function (n) { return !!n.transform.tags && n.transform.tags.indexOf(tag) >= 0; }); }
    StateSelection.withTag = withTag;
    registerModifier('subtree', subtree);
    function subtree(b) {
        return flatMap(b, function (n, s) {
            var nodes = [];
            immutable_StateTree.doPreOrder(s.tree, s.tree.transforms.get(n.transform.ref), nodes, function (x, _, ctx) { ctx.push(x.ref); });
            return nodes.map(function (x) { return s.cells.get(x); });
        });
    }
    StateSelection.subtree = subtree;
    registerModifier('children', children);
    function children(b) {
        return flatMap(b, function (n, s) {
            var nodes = [];
            s.tree.children.get(n.transform.ref).forEach(function (c) { return nodes.push(s.cells.get(c)); });
            return nodes;
        });
    }
    StateSelection.children = children;
    registerModifier('ofType', ofType);
    function ofType(b, t) { return filter(b, function (n) { return n.obj ? n.obj.type === t.type : false; }); }
    StateSelection.ofType = ofType;
    registerModifier('ancestorOfType', ancestorOfType);
    function ancestorOfType(b, types) { return unique(mapObject(b, function (n, s) { return findAncestorOfType(s.tree, s.cells, n.transform.ref, types); })); }
    StateSelection.ancestorOfType = ancestorOfType;
    registerModifier('withTransformer', withTransformer);
    function withTransformer(b, t) { return filter(b, function (o) { return o.transform.transformer === t; }); }
    StateSelection.withTransformer = withTransformer;
    registerModifier('rootOfType', rootOfType);
    function rootOfType(b, types) { return unique(mapObject(b, function (n, s) { return findRootOfType(s.tree, s.cells, n.transform.ref, types); })); }
    StateSelection.rootOfType = rootOfType;
    registerModifier('parent', parent);
    function parent(b) { return unique(mapObject(b, function (n, s) { return s.cells.get(s.tree.transforms.get(n.transform.ref).parent); })); }
    StateSelection.parent = parent;
    function findAncestorOfType(tree, cells, root, types) {
        var current = tree.transforms.get(root), len = types.length;
        while (true) {
            current = tree.transforms.get(current.parent);
            var cell = cells.get(current.ref);
            if (!cell.obj)
                return void 0;
            var obj = cell.obj;
            for (var i = 0; i < len; i++) {
                if (obj.type === types[i].type)
                    return cell;
            }
            if (current.ref === mol_state_transform["a" /* StateTransform */].RootRef) {
                return void 0;
            }
        }
    }
    StateSelection.findAncestorOfType = findAncestorOfType;
    function findRootOfType(tree, cells, root, types) {
        var parent, _root = root;
        while (true) {
            var _parent = StateSelection.findAncestorOfType(tree, cells, _root, types);
            if (_parent) {
                parent = _parent;
                _root = _parent.transform.ref;
            }
            else {
                break;
            }
        }
        return parent;
    }
    StateSelection.findRootOfType = findRootOfType;
    function findUniqueTagsInSubtree(tree, root, tags) {
        return immutable_StateTree.doPreOrder(tree, tree.transforms.get(root), { refs: {}, tags: tags }, _findUniqueTagsInSubtree).refs;
    }
    StateSelection.findUniqueTagsInSubtree = findUniqueTagsInSubtree;
    function _findUniqueTagsInSubtree(n, _, s) {
        if (n.tags) {
            for (var _i = 0, _a = n.tags; _i < _a.length; _i++) {
                var t = _a[_i];
                if (!s.tags.has(t))
                    continue;
                s.refs[t] = n.ref;
                break;
            }
        }
        return true;
    }
    function findTagInSubtree(tree, root, tag) {
        return immutable_StateTree.doPreOrder(tree, tree.transforms.get(root), { ref: void 0, tag: tag }, _findTagInSubtree).ref;
    }
    StateSelection.findTagInSubtree = findTagInSubtree;
    function _findTagInSubtree(n, _, s) {
        if (n.tags && n.tags.indexOf(s.tag) >= 0) {
            s.ref = n.ref;
            return false;
        }
        return true;
    }
    function findWithAllTags(tree, root, tags) {
        return immutable_StateTree.doPreOrder(tree, tree.transforms.get(root), { refs: [], tags: tags }, _findWithAllTags).refs;
    }
    StateSelection.findWithAllTags = findWithAllTags;
    function _findWithAllTags(n, _, s) {
        if (n.tags) {
            var len = s.tags.size;
            var found = 0;
            for (var _i = 0, _a = n.tags; _i < _a.length; _i++) {
                var t = _a[_i];
                if (!s.tags.has(t))
                    continue;
                found++;
                if (found === len) {
                    s.refs.push(n);
                    break;
                }
            }
        }
        else if (s.tags.size === 0) {
            s.refs.push(n);
        }
    }
    function tryFindDecorator(state, root, transformer) {
        var t = state.transforms.get(root);
        if (t.transformer === transformer)
            return state.cells.get(root);
        var children = state.tree.children.get(root);
        if (children.size !== 1)
            return;
        var first = children.first();
        if (state.transforms.get(first).transformer.definition.isDecorator)
            return tryFindDecorator(state, first, transformer);
    }
    StateSelection.tryFindDecorator = tryFindDecorator;
})(selection_StateSelection || (selection_StateSelection = {}));

//# sourceMappingURL=selection.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/rx-event-helper.js
var rx_event_helper = __webpack_require__(180);

// EXTERNAL MODULE: ./node_modules/immer/dist/immer.esm.js
var immer_esm = __webpack_require__(151);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/state/builder.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var builder_StateBuilder;
(function (StateBuilder) {
    function buildTree(state) {
        if (!state.state || state.state.tree === state.editInfo.sourceTree) {
            return state.tree.asImmutable();
        }
        // The tree has changed in the meantime, we need to reapply the changes!
        var tree = state.state.tree.asTransient();
        for (var _i = 0, _a = state.actions; _i < _a.length; _i++) {
            var a = _a[_i];
            switch (a.kind) {
                case 'add':
                    tree.add(a.transform);
                    break;
                case 'update':
                    tree.setParams(a.ref, a.params);
                    break;
                case 'delete':
                    tree.remove(a.ref);
                    break;
                case 'insert': {
                    var children = tree.children.get(a.ref).toArray();
                    tree.add(a.transform);
                    for (var _b = 0, children_1 = children; _b < children_1.length; _b++) {
                        var c = children_1[_b];
                        tree.changeParent(c, a.transform.ref);
                    }
                    break;
                }
            }
        }
        state.editInfo.sourceTree = state.tree;
        return tree.asImmutable();
    }
    function is(obj) {
        return !!obj && typeof obj.getTree === 'function';
    }
    StateBuilder.is = is;
    function isTo(obj) {
        return !!obj && typeof obj.getTree === 'function' && typeof obj.ref === 'string';
    }
    StateBuilder.isTo = isTo;
    // type ToFromCell<C extends StateObjectCell> = C extends StateObjectCell<infer A, StateTransform<infer T extends StateTransformer>> ? To<A, any>: never
    var Root = /** @class */ (function () {
        function Root(tree, state) {
            this.state = { state: state, tree: tree.asTransient(), actions: [], editInfo: { applied: false, sourceTree: tree, count: 0, lastUpdate: void 0 } };
        }
        Object.defineProperty(Root.prototype, "editInfo", {
            get: function () { return this.state.editInfo; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Root.prototype, "currentTree", {
            get: function () { return this.state.tree; },
            enumerable: false,
            configurable: true
        });
        Root.prototype.to = function (refOrCellOrSelector) {
            var ref = typeof refOrCellOrSelector === 'string'
                ? refOrCellOrSelector
                : StateObjectCell.is(refOrCellOrSelector)
                    ? refOrCellOrSelector.transform.ref
                    : refOrCellOrSelector.ref;
            return new To(this.state, ref, this);
        };
        Root.prototype.toRoot = function () { return new To(this.state, this.state.tree.root.ref, this); };
        Root.prototype.delete = function (obj) {
            var ref = StateObjectRef.resolveRef(obj);
            if (!ref || !this.state.tree.transforms.has(ref))
                return this;
            this.editInfo.count++;
            this.state.tree.remove(ref);
            this.state.actions.push({ kind: 'delete', ref: ref });
            return this;
        };
        Root.prototype.getTree = function () { return buildTree(this.state); };
        Root.prototype.commit = function (options) {
            if (!this.state.state)
                throw new Error('Cannot commit template tree');
            return this.state.state.runTask(this.state.state.updateTree(this, options));
        };
        return Root;
    }());
    StateBuilder.Root = Root;
    var To = /** @class */ (function () {
        function To(state, ref, root) {
            this.state = state;
            this.root = root;
            this.ref = ref;
            if (!this.state.tree.transforms.has(ref)) {
                throw new Error("Could not find node '" + ref + "'.");
            }
        }
        Object.defineProperty(To.prototype, "editInfo", {
            get: function () { return this.state.editInfo; },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(To.prototype, "selector", {
            get: function () { return new StateObjectSelector(this.ref, this.state.state); },
            enumerable: false,
            configurable: true
        });
        To.prototype.getApplyRoot = function () {
            return immutable_StateTree.getDecoratorRoot(this.state.tree, this.ref);
        };
        /**
         * Apply the transformed to the parent node
         * If no params are specified (params <- undefined), default params are lazily resolved.
         */
        To.prototype.apply = function (tr, params, options) {
            if (tr.definition.isDecorator) {
                return this.insert(tr, params, options);
            }
            var applyRoot = this.getApplyRoot();
            var t = tr.apply(applyRoot, params, options);
            this.state.tree.add(t);
            this.editInfo.count++;
            this.editInfo.lastUpdate = t.ref;
            this.state.actions.push({ kind: 'add', transform: t });
            return new To(this.state, t.ref, this.root);
        };
        /**
         * If the ref is present, the transform is applied.
         * Otherwise a transform with the specifed ref is created.
         */
        To.prototype.applyOrUpdate = function (ref, tr, params, options) {
            if (this.state.tree.transforms.has(ref)) {
                var to = this.to(ref);
                if (params)
                    to.update(params);
                return to;
            }
            else {
                return this.apply(tr, params, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, options), { ref: ref }));
            }
        };
        /**
         * Apply the transformed to the parent node
         * If no params are specified (params <- undefined), default params are lazily resolved.
         * The transformer cannot be a decorator to be able to use this.
         */
        To.prototype.applyOrUpdateTagged = function (tags, tr, params, options) {
            if (tr.definition.isDecorator) {
                throw new Error("Can't use applyOrUpdateTagged on decorator transformers.");
            }
            var applyRoot = this.getApplyRoot();
            var children = this.state.tree.children.get(applyRoot).values();
            while (true) {
                var child = children.next();
                if (child.done)
                    break;
                var tr_1 = this.state.tree.transforms.get(child.value);
                if (tr_1 && mol_state_transform["a" /* StateTransform */].hasTags(tr_1, tags)) {
                    var to = this.to(child.value);
                    to.updateTagged(params, tagsUnion(tr_1.tags, tags, options && options.tags));
                    return to;
                }
            }
            var t = tr.apply(applyRoot, params, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, options), { tags: tagsUnion(tags, options && options.tags) }));
            this.state.tree.add(t);
            this.editInfo.count++;
            this.editInfo.lastUpdate = t.ref;
            this.state.actions.push({ kind: 'add', transform: t });
            return new To(this.state, t.ref, this.root);
        };
        /**
         * A helper to greate a group-like state object and keep the current type.
         */
        To.prototype.group = function (tr, params, options) {
            return this.apply(tr, params, options);
        };
        /**
         * Inserts a new transform that does not change the object type and move the original children to it.
         */
        To.prototype.insert = function (tr, params, options) {
            // cache the children
            var children = this.state.tree.children.get(this.ref).toArray();
            // add the new node
            var t = tr.apply(this.ref, params, options);
            this.state.tree.add(t);
            // move the original children to the new node
            for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
                var c = children_2[_i];
                this.state.tree.changeParent(c, t.ref);
            }
            this.editInfo.count++;
            this.editInfo.lastUpdate = t.ref;
            this.state.actions.push({ kind: 'insert', ref: this.ref, transform: t });
            return new To(this.state, t.ref, this.root);
        };
        To.prototype.updateTagged = function (params, tags) {
            if (this.state.tree.setParams(this.ref, params) || this.state.tree.setTags(this.ref, tags)) {
                this.editInfo.count++;
                this.editInfo.lastUpdate = this.ref;
                this.state.actions.push({ kind: 'update', ref: this.ref, params: params });
            }
        };
        To.prototype.update = function (paramsOrTransformer, provider) {
            var params;
            if (provider) {
                var old = this.state.tree.transforms.get(this.ref);
                params = Object(immer_esm["b" /* produce */])(old.params, provider);
            }
            else {
                params = typeof paramsOrTransformer === 'function'
                    ? Object(immer_esm["b" /* produce */])(this.state.tree.transforms.get(this.ref).params, paramsOrTransformer)
                    : paramsOrTransformer;
            }
            if (this.state.tree.setParams(this.ref, params)) {
                this.editInfo.count++;
                this.editInfo.lastUpdate = this.ref;
                this.state.actions.push({ kind: 'update', ref: this.ref, params: params });
            }
            return this.root;
        };
        To.prototype.to = function (ref) { return this.root.to(ref); };
        To.prototype.toRoot = function () { return this.root.toRoot(); };
        To.prototype.delete = function (ref) { return this.root.delete(ref); };
        To.prototype.getTree = function () { return buildTree(this.state); };
        /** Returns selector to this node. */
        To.prototype.commit = function (options) {
            if (!this.state.state)
                throw new Error('Cannot commit template tree');
            return this.state.state.runTask(this.state.state.updateTree(this, options));
        };
        return To;
    }());
    StateBuilder.To = To;
})(builder_StateBuilder || (builder_StateBuilder = {}));
function tagsUnion() {
    var arrays = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        arrays[_i] = arguments[_i];
    }
    var set = void 0;
    var ret = [];
    for (var _a = 0, arrays_1 = arrays; _a < arrays_1.length; _a++) {
        var xs = arrays_1[_a];
        if (!xs)
            continue;
        if (!set)
            set = new Set();
        if (typeof xs === 'string') {
            if (set.has(xs))
                continue;
            set.add(xs);
            ret.push(xs);
        }
        else {
            for (var _b = 0, xs_1 = xs; _b < xs_1.length; _b++) {
                var x = xs_1[_b];
                if (set.has(x))
                    continue;
                set.add(x);
                ret.push(x);
            }
        }
    }
    return ret;
}
//# sourceMappingURL=builder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/action/manager.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var manager_StateActionManager = /** @class */ (function () {
    function StateActionManager() {
        this.ev = rx_event_helper["RxEventHelper"].create();
        this.actions = new Map();
        this.fromTypeIndex = new Map();
        this.events = {
            added: this.ev(),
            removed: this.ev(),
        };
    }
    StateActionManager.prototype.add = function (actionOrTransformer) {
        var action = mol_state_transformer["a" /* StateTransformer */].is(actionOrTransformer) ? actionOrTransformer.toAction() : actionOrTransformer;
        if (this.actions.has(action.id))
            return this;
        this.actions.set(action.id, action);
        for (var _i = 0, _a = action.definition.from; _i < _a.length; _i++) {
            var t = _a[_i];
            if (this.fromTypeIndex.has(t.type)) {
                this.fromTypeIndex.get(t.type).push(action);
            }
            else {
                this.fromTypeIndex.set(t.type, [action]);
            }
        }
        this.events.added.next();
        return this;
    };
    StateActionManager.prototype.remove = function (actionOrTransformer) {
        var id = mol_state_transformer["a" /* StateTransformer */].is(actionOrTransformer)
            ? actionOrTransformer.toAction().id
            : mol_util["c" /* UUID */].is(actionOrTransformer)
                ? actionOrTransformer
                : actionOrTransformer.id;
        var action = this.actions.get(id);
        if (!action)
            return this;
        this.actions.delete(id);
        for (var _i = 0, _a = action.definition.from; _i < _a.length; _i++) {
            var t = _a[_i];
            var xs = this.fromTypeIndex.get(t.type);
            if (!xs)
                continue;
            Object(array["arraySetRemove"])(xs, action);
            if (xs.length === 0)
                this.fromTypeIndex.delete(t.type);
        }
        this.events.removed.next();
        return this;
    };
    StateActionManager.prototype.fromCell = function (cell, ctx) {
        var obj = cell.obj;
        if (!obj)
            return [];
        var actions = this.fromTypeIndex.get(obj.type);
        if (!actions)
            return [];
        var hasTest = false;
        for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) {
            var a = actions_1[_i];
            if (a.definition.isApplicable) {
                hasTest = true;
                break;
            }
        }
        if (!hasTest)
            return actions;
        var ret = [];
        for (var _a = 0, actions_2 = actions; _a < actions_2.length; _a++) {
            var a = actions_2[_a];
            if (a.definition.isApplicable) {
                if (a.definition.isApplicable(obj, cell.transform, ctx)) {
                    ret.push(a);
                }
            }
            else {
                ret.push(a);
            }
        }
        return ret;
    };
    StateActionManager.prototype.dispose = function () {
        this.ev.dispose();
    };
    return StateActionManager;
}());
//# sourceMappingURL=manager.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/log-entry.js
var log_entry = __webpack_require__(253);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/tree/spine.js
var spine = __webpack_require__(303);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/async-queue.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var async_queue_AsyncQueue = /** @class */ (function () {
    function AsyncQueue() {
        this.queue = [];
        this.signal = new Subject["a" /* Subject */]();
    }
    Object.defineProperty(AsyncQueue.prototype, "length", {
        get: function () { return this.queue.length; },
        enumerable: false,
        configurable: true
    });
    AsyncQueue.prototype.enqueue = function (v) {
        this.queue.push(v);
        if (this.queue.length === 1)
            return true;
        return this.waitFor(v);
    };
    AsyncQueue.prototype.handled = function (v) {
        Object(array["arrayRemoveInPlace"])(this.queue, v);
        if (this.queue.length > 0) {
            this.signal.next({ v: this.queue[0], stillPresent: true });
        }
    };
    AsyncQueue.prototype.remove = function (v) {
        var rem = Object(array["arrayRemoveInPlace"])(this.queue, v);
        if (rem)
            this.signal.next({ v: v, stillPresent: false });
        return rem;
    };
    AsyncQueue.prototype.waitFor = function (t) {
        var _this = this;
        return new Promise(function (res) {
            var sub = _this.signal.subscribe(function (_a) {
                var v = _a.v, removed = _a.stillPresent;
                if (v === t) {
                    sub.unsubscribe();
                    res(removed);
                }
            });
        });
    };
    return AsyncQueue;
}());

//# sourceMappingURL=async-queue.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/state.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




















var state_State = /** @class */ (function () {
    function State(rootObject, params) {
        this.errorFree = true;
        this.ev = rx_event_helper["RxEventHelper"].create();
        this.globalContext = void 0;
        this.events = {
            cell: {
                stateUpdated: this.ev(),
                created: this.ev(),
                removed: this.ev(),
            },
            object: {
                updated: this.ev(),
                created: this.ev(),
                removed: this.ev()
            },
            log: this.ev(),
            changed: this.ev(),
            historyUpdated: this.ev()
        };
        this.behaviors = {
            currentObject: this.ev.behavior({ state: this, ref: mol_state_transform["a" /* StateTransform */].RootRef }),
            isUpdating: this.ev.behavior(false),
        };
        this.actions = new manager_StateActionManager();
        this.cells = new Map();
        this.spine = new spine["a" /* StateTreeSpine */].Impl(this.cells);
        this.historyCapacity = 5;
        this.history = [];
        this.undoingHistory = false;
        this.inTransaction = false;
        this.inTransactionError = false;
        this._inUpdate = false;
        this.reverted = false;
        this.updateQueue = new async_queue_AsyncQueue();
        this._tree = immutable_StateTree.createEmpty(mol_state_transform["a" /* StateTransform */].createRoot(params && params.rootState)).asTransient();
        var tree = this._tree;
        var root = tree.root;
        this.runTask = params.runTask;
        if ((params === null || params === void 0 ? void 0 : params.historyCapacity) !== void 0)
            this.historyCapacity = params.historyCapacity;
        this.cells.set(root.ref, {
            parent: this,
            transform: root,
            sourceRef: void 0,
            obj: rootObject,
            status: 'ok',
            state: Object(tslib_es6["__assign"])({}, root.state),
            errorText: void 0,
            params: {
                definition: {},
                values: {}
            },
            dependencies: { dependentBy: [], dependsOn: [] },
            cache: {}
        });
        this.globalContext = params && params.globalContext;
    }
    Object.defineProperty(State.prototype, "tree", {
        get: function () { return this._tree; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "transforms", {
        get: function () { return this._tree.transforms; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "current", {
        get: function () { return this.behaviors.currentObject.value.ref; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "root", {
        get: function () { return this.cells.get(this._tree.root.ref); },
        enumerable: false,
        configurable: true
    });
    State.prototype.build = function () { return new builder_StateBuilder.Root(this.tree, this); };
    State.prototype.addHistory = function (tree, label) {
        if (this.historyCapacity === 0)
            return;
        this.history.unshift([tree, label || 'Update']);
        if (this.history.length > this.historyCapacity)
            this.history.pop();
        this.events.historyUpdated.next({ state: this });
    };
    State.prototype.clearHistory = function () {
        if (this.history.length === 0)
            return;
        this.history = [];
        this.events.historyUpdated.next({ state: this });
    };
    Object.defineProperty(State.prototype, "latestUndoLabel", {
        get: function () {
            return this.history.length > 0 ? this.history[0][1] : void 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(State.prototype, "canUndo", {
        get: function () {
            return this.history.length > 0;
        },
        enumerable: false,
        configurable: true
    });
    State.prototype.undo = function () {
        var _this = this;
        return mol_task["b" /* Task */].create('Undo', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var e;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        e = this.history.shift();
                        if (!e)
                            return [2 /*return*/];
                        this.events.historyUpdated.next({ state: this });
                        this.undoingHistory = true;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, this.updateTree(e[0], { canUndo: false }).runInContext(ctx)];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        this.undoingHistory = false;
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); });
    };
    State.prototype.getSnapshot = function () {
        return { tree: immutable_StateTree.toJSON(this._tree) };
    };
    State.prototype.setSnapshot = function (snapshot) {
        var tree = immutable_StateTree.fromJSON(snapshot.tree);
        return this.updateTree(tree);
    };
    State.prototype.setCurrent = function (ref) {
        this.behaviors.currentObject.next({ state: this, ref: ref });
    };
    State.prototype.updateCellState = function (ref, stateOrProvider) {
        var cell = this.cells.get(ref);
        if (!cell)
            return;
        var update = typeof stateOrProvider === 'function' ? stateOrProvider(cell.state) : stateOrProvider;
        if (mol_state_transform["a" /* StateTransform */].assignState(cell.state, update)) {
            cell.transform = this._tree.assignState(cell.transform.ref, update);
            this.events.cell.stateUpdated.next({ state: this, ref: ref, cell: cell });
        }
    };
    State.prototype.dispose = function () {
        this.ev.dispose();
        this.actions.dispose();
    };
    /**
     * Select Cells using the provided selector.
     * @example state.query(StateSelection.Generators.byRef('test').ancestorOfType([type]))
     * @example state.query('test')
     */
    State.prototype.select = function (selector) {
        return selection_StateSelection.select(selector, this);
    };
    /**
     * Select Cells by building a query generated on the fly.
     * @example state.select(q => q.byRef('test').subtree())
     */
    State.prototype.selectQ = function (selector) {
        if (typeof selector === 'string')
            return selection_StateSelection.select(selector, this);
        return selection_StateSelection.select(selector(selection_StateSelection.Generators), this);
    };
    /**
     * Creates a Task that applies the specified StateAction (i.e. must use run* on the result)
     * If no ref is specified, apply to root.
     */
    State.prototype.applyAction = function (action, params, ref) {
        var _this = this;
        if (ref === void 0) { ref = mol_state_transform["a" /* StateTransform */].RootRef; }
        return mol_task["b" /* Task */].create('Apply Action', function (ctx) {
            var cell = _this.cells.get(ref);
            if (!cell)
                throw new Error("'" + ref + "' does not exist.");
            if (cell.status !== 'ok')
                throw new Error("Action cannot be applied to a cell with status '" + cell.status + "'");
            return runTask(action.definition.run({ ref: ref, cell: cell, a: cell.obj, params: params, state: _this }, _this.globalContext), ctx);
        });
    };
    /** Apply series of updates to the state. If any of them fail, revert to the original state. */
    State.prototype.transaction = function (edits, options) {
        var _this = this;
        return mol_task["b" /* Task */].create('State Transaction', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var isNested, snapshot, restored, e_1;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        isNested = this.inTransaction;
                        snapshot = this._tree.asImmutable();
                        restored = false;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 5, 8, 9]);
                        if (!isNested)
                            this.behaviors.isUpdating.next(true);
                        this.inTransaction = true;
                        this.inTransactionError = false;
                        return [4 /*yield*/, edits(ctx)];
                    case 2:
                        _a.sent();
                        if (!this.inTransactionError) return [3 /*break*/, 4];
                        restored = true;
                        return [4 /*yield*/, this.updateTree(snapshot).runInContext(ctx)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4: return [3 /*break*/, 9];
                    case 5:
                        e_1 = _a.sent();
                        if (!!restored) return [3 /*break*/, 7];
                        restored = true;
                        return [4 /*yield*/, this.updateTree(snapshot).runInContext(ctx)];
                    case 6:
                        _a.sent();
                        this.events.log.error(e_1);
                        _a.label = 7;
                    case 7:
                        if (isNested) {
                            this.inTransactionError = true;
                            throw e_1;
                        }
                        return [3 /*break*/, 9];
                    case 8:
                        if (!isNested) {
                            this.inTransaction = false;
                            this.events.changed.next({ state: this, inTransaction: false });
                            this.behaviors.isUpdating.next(false);
                            if (!restored) {
                                if (options === null || options === void 0 ? void 0 : options.canUndo)
                                    this.addHistory(snapshot, typeof options.canUndo === 'string' ? options.canUndo : void 0);
                                else
                                    this.clearHistory();
                            }
                        }
                        return [7 /*endfinally*/];
                    case 9: return [2 /*return*/];
                }
            });
        }); });
    };
    Object.defineProperty(State.prototype, "inUpdate", {
        /**
         * Determines whether the state is currently "inside" updateTree function.
         * This is different from "isUpdating" which wraps entire transactions.
         */
        get: function () { return this._inUpdate; },
        enumerable: false,
        configurable: true
    });
    State.prototype.updateTree = function (tree, options) {
        var _this = this;
        var params = { tree: tree, options: options };
        return mol_task["b" /* Task */].create('Update Tree', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var removed, snapshot, reverted, ret, _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.updateQueue.enqueue(params)];
                    case 1:
                        removed = _b.sent();
                        if (!removed)
                            return [2 /*return*/];
                        this._inUpdate = true;
                        snapshot = (options === null || options === void 0 ? void 0 : options.canUndo) ? this._tree.asImmutable() : void 0;
                        reverted = false;
                        if (!this.inTransaction)
                            this.behaviors.isUpdating.next(true);
                        _b.label = 2;
                    case 2:
                        _b.trys.push([2, , 7, 8]);
                        if (builder_StateBuilder.is(tree)) {
                            if (tree.editInfo.applied)
                                throw new Error('This builder has already been applied. Create a new builder for further state updates');
                            tree.editInfo.applied = true;
                        }
                        this.reverted = false;
                        if (!(options && (options.revertIfAborted || options.revertOnError))) return [3 /*break*/, 4];
                        return [4 /*yield*/, this._revertibleTreeUpdate(taskCtx, params, options)];
                    case 3:
                        _a = _b.sent();
                        return [3 /*break*/, 6];
                    case 4: return [4 /*yield*/, this._updateTree(taskCtx, params)];
                    case 5:
                        _a = _b.sent();
                        _b.label = 6;
                    case 6:
                        ret = _a;
                        reverted = this.reverted;
                        if (ret.ctx.hadError)
                            this.inTransactionError = true;
                        if (!ret.cell)
                            return [2 /*return*/];
                        return [2 /*return*/, new StateObjectSelector(ret.cell.transform.ref, this)];
                    case 7:
                        this._inUpdate = false;
                        this.updateQueue.handled(params);
                        if (!this.inTransaction) {
                            this.behaviors.isUpdating.next(false);
                            if (!(options === null || options === void 0 ? void 0 : options.canUndo)) {
                                if (!this.undoingHistory)
                                    this.clearHistory();
                            }
                            else if (!reverted) {
                                this.addHistory(snapshot, typeof options.canUndo === 'string' ? options.canUndo : void 0);
                            }
                        }
                        return [7 /*endfinally*/];
                    case 8: return [2 /*return*/];
                }
            });
        }); }, function () {
            _this.updateQueue.remove(params);
        });
    };
    State.prototype._revertibleTreeUpdate = function (taskCtx, params, options) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var old, ret, revert;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        old = this.tree;
                        return [4 /*yield*/, this._updateTree(taskCtx, params)];
                    case 1:
                        ret = _a.sent();
                        revert = ((ret.ctx.hadError || ret.ctx.wasAborted) && options.revertOnError) || (ret.ctx.wasAborted && options.revertIfAborted);
                        if (!revert) return [3 /*break*/, 3];
                        this.reverted = true;
                        return [4 /*yield*/, this._updateTree(taskCtx, { tree: old, options: params.options })];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3: return [2 /*return*/, ret];
                }
            });
        });
    };
    State.prototype._updateTree = function (taskCtx, params) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var updated, ctx, cell;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        updated = false;
                        ctx = this.updateTreeAndCreateCtx(params.tree, taskCtx, params.options);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, state_update(ctx)];
                    case 2:
                        updated = _a.sent();
                        if (builder_StateBuilder.isTo(params.tree)) {
                            cell = this.select(params.tree.ref)[0];
                            return [2 /*return*/, { ctx: ctx, cell: cell }];
                        }
                        return [2 /*return*/, { ctx: ctx }];
                    case 3:
                        this.spine.current = undefined;
                        if (updated)
                            this.events.changed.next({ state: this, inTransaction: this.inTransaction });
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    State.prototype.updateTreeAndCreateCtx = function (tree, taskCtx, options) {
        var _tree = (builder_StateBuilder.is(tree) ? tree.getTree() : tree).asTransient();
        var oldTree = this._tree;
        this._tree = _tree;
        var ctx = {
            parent: this,
            editInfo: builder_StateBuilder.is(tree) ? tree.editInfo : void 0,
            errorFree: this.errorFree,
            taskCtx: taskCtx,
            oldTree: oldTree,
            tree: _tree,
            cells: this.cells,
            spine: this.spine,
            results: [],
            options: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, StateUpdateDefaultOptions), options),
            changed: false,
            hadError: false,
            wasAborted: false,
            newCurrent: void 0
        };
        this.errorFree = true;
        return ctx;
    };
    return State;
}());
(function (State) {
    function create(rootObject, params) {
        return new State(rootObject, params);
    }
    State.create = create;
    var ObjectEvent;
    (function (ObjectEvent) {
        function isCell(e, cell) {
            return !!cell && e.ref === cell.transform.ref && e.state === cell.parent;
        }
        ObjectEvent.isCell = isCell;
    })(ObjectEvent = State.ObjectEvent || (State.ObjectEvent = {}));
})(state_State || (state_State = {}));
var StateUpdateDefaultOptions = {
    doNotLogTiming: false,
    doNotUpdateCurrent: true,
    revertIfAborted: false,
    revertOnError: false,
    canUndo: false
};
function state_update(ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var fastTrack, deletes, deletedObjects, roots, current, hasCurrent, _i, deletes_1, d, newCurrent_1, i, cell, _a, deletes_2, d, cell, obj, init, _b, _c, cell, i, d, parent_1, _d, _e, cell, _f, roots_1, root, newCurrent, _g, _h, update_1, transform, current, currentCell;
        return Object(tslib_es6["__generator"])(this, function (_j) {
            switch (_j.label) {
                case 0:
                    fastTrack = !!(ctx.editInfo && ctx.editInfo.count === 1 && ctx.editInfo.lastUpdate && ctx.editInfo.sourceTree === ctx.oldTree);
                    deletedObjects = [];
                    if (fastTrack) {
                        deletes = [];
                        roots = [ctx.editInfo.lastUpdate];
                    }
                    else {
                        // find all nodes that will definitely be deleted.
                        // this is done in "post order", meaning that leaves will be deleted first.
                        deletes = findDeletes(ctx);
                        current = ctx.parent.current;
                        hasCurrent = false;
                        for (_i = 0, deletes_1 = deletes; _i < deletes_1.length; _i++) {
                            d = deletes_1[_i];
                            if (d === current) {
                                hasCurrent = true;
                                break;
                            }
                        }
                        if (hasCurrent) {
                            newCurrent_1 = findNewCurrent(ctx.oldTree, current, deletes, ctx.cells);
                            ctx.parent.setCurrent(newCurrent_1);
                        }
                        for (i = deletes.length - 1; i >= 0; i--) {
                            cell = ctx.cells.get(deletes[i]);
                            if (cell) {
                                dispose(cell.transform, cell.obj, cell === null || cell === void 0 ? void 0 : cell.transform.params, cell.cache, ctx.parent.globalContext);
                            }
                        }
                        for (_a = 0, deletes_2 = deletes; _a < deletes_2.length; _a++) {
                            d = deletes_2[_a];
                            cell = ctx.cells.get(d);
                            if (cell) {
                                cell.parent = void 0;
                                unlinkCell(cell);
                            }
                            obj = cell && cell.obj;
                            ctx.cells.delete(d);
                            deletedObjects.push(obj);
                        }
                        // Find roots where transform version changed or where nodes will be added.
                        roots = findUpdateRoots(ctx.cells, ctx.tree);
                    }
                    init = initCells(ctx, roots);
                    // Notify additions of new cells.
                    for (_b = 0, _c = init.added; _b < _c.length; _b++) {
                        cell = _c[_b];
                        ctx.parent.events.cell.created.next({ state: ctx.parent, ref: cell.transform.ref, cell: cell });
                    }
                    for (i = 0; i < deletes.length; i++) {
                        d = deletes[i];
                        parent_1 = ctx.oldTree.transforms.get(d).parent;
                        ctx.parent.events.object.removed.next({ state: ctx.parent, ref: d, obj: deletedObjects[i] });
                        ctx.parent.events.cell.removed.next({ state: ctx.parent, ref: d, parent: parent_1 });
                    }
                    if (deletedObjects.length)
                        deletedObjects = [];
                    if (init.dependent) {
                        for (_d = 0, _e = init.dependent; _d < _e.length; _d++) {
                            cell = _e[_d];
                            roots.push(cell.transform.ref);
                        }
                    }
                    // Set status of cells that will be updated to 'pending'.
                    initCellStatus(ctx, roots);
                    _f = 0, roots_1 = roots;
                    _j.label = 1;
                case 1:
                    if (!(_f < roots_1.length)) return [3 /*break*/, 4];
                    root = roots_1[_f];
                    return [4 /*yield*/, updateSubtree(ctx, root)];
                case 2:
                    _j.sent();
                    _j.label = 3;
                case 3:
                    _f++;
                    return [3 /*break*/, 1];
                case 4:
                    // Sync cell states
                    if (!ctx.editInfo) {
                        syncNewStates(ctx);
                    }
                    newCurrent = ctx.newCurrent;
                    // Raise object updated events
                    for (_g = 0, _h = ctx.results; _g < _h.length; _g++) {
                        update_1 = _h[_g];
                        if (update_1.action === 'created') {
                            ctx.parent.events.object.created.next({ state: ctx.parent, ref: update_1.ref, obj: update_1.obj });
                            if (!ctx.newCurrent) {
                                transform = ctx.tree.transforms.get(update_1.ref);
                                if (!transform.state.isGhost && update_1.obj !== object_StateObject.Null)
                                    newCurrent = update_1.ref;
                            }
                        }
                        else if (update_1.action === 'updated') {
                            ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update_1.ref, action: 'in-place', obj: update_1.obj });
                        }
                        else if (update_1.action === 'replaced') {
                            ctx.parent.events.object.updated.next({ state: ctx.parent, ref: update_1.ref, action: 'recreate', obj: update_1.obj, oldObj: update_1.oldObj });
                        }
                    }
                    if (newCurrent) {
                        if (!ctx.options.doNotUpdateCurrent)
                            ctx.parent.setCurrent(newCurrent);
                    }
                    else {
                        current = ctx.parent.current;
                        currentCell = ctx.cells.get(current);
                        if (currentCell && (currentCell.obj === object_StateObject.Null
                            || (currentCell.status === 'error' && currentCell.errorText === ParentNullErrorText))) {
                            newCurrent = findNewCurrent(ctx.oldTree, current, [], ctx.cells);
                            ctx.parent.setCurrent(newCurrent);
                        }
                    }
                    return [2 /*return*/, deletes.length > 0 || roots.length > 0 || ctx.changed];
            }
        });
    });
}
function findUpdateRoots(cells, tree) {
    var findState = { roots: [], cells: cells };
    immutable_StateTree.doPreOrder(tree, tree.root, findState, findUpdateRootsVisitor);
    return findState.roots;
}
function findUpdateRootsVisitor(n, _, s) {
    var cell = s.cells.get(n.ref);
    if (!cell || cell.transform.version !== n.version) {
        s.roots.push(n.ref);
        return false;
    }
    if (cell.status === 'error')
        return false;
    // nothing below a Null object can be an update root
    if (cell && cell.obj === object_StateObject.Null)
        return false;
    return true;
}
function checkDeleteVisitor(n, _, ctx) {
    if (!ctx.newTree.transforms.has(n.ref) && ctx.cells.has(n.ref))
        ctx.deletes.push(n.ref);
}
function findDeletes(ctx) {
    var deleteCtx = { newTree: ctx.tree, cells: ctx.cells, deletes: [] };
    immutable_StateTree.doPostOrder(ctx.oldTree, ctx.oldTree.root, deleteCtx, checkDeleteVisitor);
    return deleteCtx.deletes;
}
function syncNewStatesVisitor(n, tree, ctx) {
    var cell = ctx.cells.get(n.ref);
    if (!cell || !mol_state_transform["a" /* StateTransform */].syncState(cell.state, n.state))
        return;
    ctx.parent.events.cell.stateUpdated.next({ state: ctx.parent, ref: n.ref, cell: cell });
}
function syncNewStates(ctx) {
    immutable_StateTree.doPreOrder(ctx.tree, ctx.tree.root, ctx, syncNewStatesVisitor);
}
function setCellStatus(ctx, ref, status, errorText) {
    var cell = ctx.cells.get(ref);
    var changed = cell.status !== status;
    cell.status = status;
    cell.errorText = errorText;
    if (changed)
        ctx.parent.events.cell.stateUpdated.next({ state: ctx.parent, ref: ref, cell: cell });
}
function initCellStatusVisitor(t, _, ctx) {
    ctx.cells.get(t.ref).transform = t;
    setCellStatus(ctx, t.ref, 'pending');
}
function initCellStatus(ctx, roots) {
    for (var _i = 0, roots_2 = roots; _i < roots_2.length; _i++) {
        var root = roots_2[_i];
        immutable_StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), ctx, initCellStatusVisitor);
    }
}
function unlinkCell(cell) {
    for (var _i = 0, _a = cell.dependencies.dependsOn; _i < _a.length; _i++) {
        var other = _a[_i];
        Object(array["arraySetRemove"])(other.dependencies.dependentBy, cell);
    }
}
function addCellsVisitor(transform, _, _a) {
    var ctx = _a.ctx, added = _a.added, visited = _a.visited;
    visited.add(transform.ref);
    if (ctx.cells.has(transform.ref)) {
        return;
    }
    var cell = {
        parent: ctx.parent,
        transform: transform,
        sourceRef: void 0,
        status: 'pending',
        state: Object(tslib_es6["__assign"])({}, transform.state),
        errorText: void 0,
        params: void 0,
        dependencies: { dependentBy: [], dependsOn: [] },
        cache: void 0
    };
    ctx.cells.set(transform.ref, cell);
    added.push(cell);
}
// type LinkCellsCtx = { ctx: UpdateContext, visited: Set<Ref>, dependent: UniqueArray<Ref, StateObjectCell> }
function linkCells(target, ctx) {
    if (!target.transform.dependsOn)
        return;
    for (var _i = 0, _a = target.transform.dependsOn; _i < _a.length; _i++) {
        var ref = _a[_i];
        var t = ctx.tree.transforms.get(ref);
        if (!t) {
            throw new Error("Cannot depend on a non-existent transform.");
        }
        var cell = ctx.cells.get(ref);
        Object(array["arraySetAdd"])(target.dependencies.dependsOn, cell);
        Object(array["arraySetAdd"])(cell.dependencies.dependentBy, target);
    }
}
function initCells(ctx, roots) {
    var initCtx = { ctx: ctx, visited: new Set(), added: [] };
    // Add new cells
    for (var _i = 0, roots_3 = roots; _i < roots_3.length; _i++) {
        var root = roots_3[_i];
        immutable_StateTree.doPreOrder(ctx.tree, ctx.tree.transforms.get(root), initCtx, addCellsVisitor);
    }
    // Update links for newly added cells
    for (var _a = 0, _b = initCtx.added; _a < _b.length; _a++) {
        var cell = _b[_a];
        linkCells(cell, ctx);
    }
    var dependent;
    // Find dependent cells
    initCtx.visited.forEach(function (ref) {
        var cell = ctx.cells.get(ref);
        for (var _i = 0, _a = cell.dependencies.dependentBy; _i < _a.length; _i++) {
            var by = _a[_i];
            if (initCtx.visited.has(by.transform.ref))
                continue;
            if (!dependent)
                dependent = generic["c" /* UniqueArray */].create();
            generic["c" /* UniqueArray */].add(dependent, by.transform.ref, by);
        }
    });
    // TODO: check if dependent cells are all "proper roots"
    return { added: initCtx.added, dependent: dependent ? dependent.array : void 0 };
}
function findNewCurrent(tree, start, deletes, cells) {
    var deleteSet = new Set(deletes);
    return _findNewCurrent(tree, start, deleteSet, cells);
}
function _findNewCurrent(tree, ref, deletes, cells) {
    if (ref === mol_state_transform["a" /* StateTransform */].RootRef)
        return ref;
    var node = tree.transforms.get(ref);
    var siblings = tree.children.get(node.parent).values();
    var prevCandidate = void 0, seenRef = false;
    while (true) {
        var s = siblings.next();
        if (s.done)
            break;
        if (deletes.has(s.value))
            continue;
        var cell = cells.get(s.value);
        if (!cell || cell.status === 'error' || cell.obj === object_StateObject.Null) {
            continue;
        }
        var t = tree.transforms.get(s.value);
        if (t.state.isGhost)
            continue;
        if (s.value === ref) {
            seenRef = true;
            if (!deletes.has(ref))
                prevCandidate = ref;
            continue;
        }
        if (seenRef)
            return t.ref;
        prevCandidate = t.ref;
    }
    if (prevCandidate)
        return prevCandidate;
    return _findNewCurrent(tree, node.parent, deletes, cells);
}
/** Set status and error text of the cell. Remove all existing objects in the subtree. */
function doError(ctx, ref, errorObject, silent) {
    if (!silent) {
        ctx.hadError = true;
        ctx.parent.errorFree = false;
    }
    var cell = ctx.cells.get(ref);
    if (errorObject) {
        ctx.wasAborted = ctx.wasAborted || mol_task["b" /* Task */].isAbort(errorObject);
        var message = '' + errorObject;
        setCellStatus(ctx, ref, 'error', message);
        if (!silent)
            ctx.parent.events.log.next({ type: 'error', timestamp: new Date(), message: message });
    }
    else {
        cell.params = void 0;
    }
    if (cell.obj) {
        var obj = cell.obj;
        cell.obj = void 0;
        cell.cache = void 0;
        ctx.parent.events.object.removed.next({ state: ctx.parent, ref: ref, obj: obj });
    }
    // remove the objects in the child nodes if they exist
    var children = ctx.tree.children.get(ref).values();
    while (true) {
        var next = children.next();
        if (next.done)
            return;
        doError(ctx, next.value, void 0, silent);
    }
}
var ParentNullErrorText = 'Parent is null';
function updateSubtree(ctx, root) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var isNull, start, update_2, time, e_2, children, next;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    setCellStatus(ctx, root, 'processing');
                    isNull = false;
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    start = Object(now["b" /* now */])();
                    return [4 /*yield*/, updateNode(ctx, root)];
                case 2:
                    update_2 = _a.sent();
                    time = Object(now["b" /* now */])() - start;
                    if (update_2.action !== 'none')
                        ctx.changed = true;
                    setCellStatus(ctx, root, 'ok');
                    ctx.results.push(update_2);
                    if (update_2.action === 'created') {
                        isNull = update_2.obj === object_StateObject.Null;
                        if (!isNull && !ctx.options.doNotLogTiming)
                            ctx.parent.events.log.next(log_entry["a" /* LogEntry */].info("Created " + update_2.obj.label + " in " + Object(now["a" /* formatTimespan */])(time) + "."));
                    }
                    else if (update_2.action === 'updated') {
                        isNull = update_2.obj === object_StateObject.Null;
                        if (!isNull && !ctx.options.doNotLogTiming)
                            ctx.parent.events.log.next(log_entry["a" /* LogEntry */].info("Updated " + update_2.obj.label + " in " + Object(now["a" /* formatTimespan */])(time) + "."));
                    }
                    else if (update_2.action === 'replaced') {
                        isNull = update_2.obj === object_StateObject.Null;
                        if (!isNull && !ctx.options.doNotLogTiming)
                            ctx.parent.events.log.next(log_entry["a" /* LogEntry */].info("Updated " + update_2.obj.label + " in " + Object(now["a" /* formatTimespan */])(time) + "."));
                    }
                    return [3 /*break*/, 4];
                case 3:
                    e_2 = _a.sent();
                    ctx.changed = true;
                    if (!ctx.hadError)
                        ctx.newCurrent = root;
                    doError(ctx, root, e_2, false);
                    if (!debug["b" /* isProductionMode */])
                        console.error(e_2);
                    return [2 /*return*/];
                case 4:
                    children = ctx.tree.children.get(root).values();
                    _a.label = 5;
                case 5:
                    if (false) {}
                    next = children.next();
                    if (next.done)
                        return [2 /*return*/];
                    if (!isNull) return [3 /*break*/, 6];
                    doError(ctx, next.value, void 0, true);
                    return [3 /*break*/, 8];
                case 6: return [4 /*yield*/, updateSubtree(ctx, next.value)];
                case 7:
                    _a.sent();
                    _a.label = 8;
                case 8: return [3 /*break*/, 5];
                case 9: return [2 /*return*/];
            }
        });
    });
}
function resolveParams(ctx, transform, src) {
    var prms = transform.transformer.definition.params;
    var definition = prms ? prms(src, ctx.parent.globalContext) : {};
    var defaultValues = param_definition["ParamDefinition"].getDefaultValues(definition);
    transform.params = transform.params
        ? Object(object["a" /* assignIfUndefined */])(transform.params, defaultValues)
        : defaultValues;
    return { definition: definition, values: transform.params };
}
function updateNode(ctx, currentRef) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var oldTree, tree, current, transform, parentCell, parent, params, obj, oldParams, oldCache, newParams, updateKind, _a, _b, oldObj, newObj;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    oldTree = ctx.oldTree, tree = ctx.tree;
                    current = ctx.cells.get(currentRef);
                    transform = current.transform;
                    // special case for Root
                    if (current.transform.ref === mol_state_transform["a" /* StateTransform */].RootRef) {
                        return [2 /*return*/, { action: 'none' }];
                    }
                    parentCell = transform.transformer.definition.from.length === 0
                        ? ctx.cells.get(current.transform.parent)
                        : selection_StateSelection.findAncestorOfType(tree, ctx.cells, currentRef, transform.transformer.definition.from);
                    if (!parentCell) {
                        throw new Error("No suitable parent found for '" + currentRef + "'");
                    }
                    ctx.spine.current = current;
                    parent = parentCell.obj;
                    current.sourceRef = parentCell.transform.ref;
                    params = resolveParams(ctx, transform, parent);
                    if (!(!oldTree.transforms.has(currentRef) || !current.params)) return [3 /*break*/, 2];
                    current.params = params;
                    return [4 /*yield*/, createObject(ctx, current, transform.transformer, parent, params.values)];
                case 1:
                    obj = _c.sent();
                    updateTag(obj, transform);
                    current.obj = obj;
                    return [2 /*return*/, { ref: currentRef, action: 'created', obj: obj }];
                case 2:
                    oldParams = current.params.values;
                    oldCache = current.cache;
                    newParams = params.values;
                    current.params = params;
                    if (!(!!current.obj && current.obj !== object_StateObject.Null)) return [3 /*break*/, 4];
                    return [4 /*yield*/, updateObject(ctx, current, transform.transformer, parent, current.obj, oldParams, newParams)];
                case 3:
                    _a = _c.sent();
                    return [3 /*break*/, 5];
                case 4:
                    _a = mol_state_transformer["a" /* StateTransformer */].UpdateResult.Recreate;
                    _c.label = 5;
                case 5:
                    updateKind = _a;
                    _b = updateKind;
                    switch (_b) {
                        case mol_state_transformer["a" /* StateTransformer */].UpdateResult.Recreate: return [3 /*break*/, 6];
                        case mol_state_transformer["a" /* StateTransformer */].UpdateResult.Updated: return [3 /*break*/, 8];
                        case mol_state_transformer["a" /* StateTransformer */].UpdateResult.Null: return [3 /*break*/, 9];
                    }
                    return [3 /*break*/, 10];
                case 6:
                    oldObj = current.obj;
                    dispose(transform, oldObj, oldParams, oldCache, ctx.parent.globalContext);
                    return [4 /*yield*/, createObject(ctx, current, transform.transformer, parent, newParams)];
                case 7:
                    newObj = _c.sent();
                    updateTag(newObj, transform);
                    current.obj = newObj;
                    return [2 /*return*/, { ref: currentRef, action: 'replaced', oldObj: oldObj, obj: newObj }];
                case 8:
                    updateTag(current.obj, transform);
                    return [2 /*return*/, { ref: currentRef, action: 'updated', obj: current.obj }];
                case 9:
                    {
                        dispose(transform, current.obj, oldParams, oldCache, ctx.parent.globalContext);
                        current.obj = object_StateObject.Null;
                        return [2 /*return*/, { ref: currentRef, action: 'updated', obj: current.obj }];
                    }
                    _c.label = 10;
                case 10: return [2 /*return*/, { action: 'none' }];
            }
        });
    });
}
function dispose(transform, b, params, cache, globalContext) {
    var _a, _b;
    (_b = (_a = transform.transformer.definition).dispose) === null || _b === void 0 ? void 0 : _b.call(_a, {
        b: b !== object_StateObject.Null ? b : void 0,
        params: params,
        cache: cache
    }, globalContext);
}
function updateTag(obj, transform) {
    if (!obj || obj === object_StateObject.Null)
        return;
    obj.tags = transform.tags;
}
function runTask(t, ctx) {
    if (typeof t.runInContext === 'function')
        return t.runInContext(ctx);
    return t;
}
function resolveDependencies(cell) {
    if (cell.dependencies.dependsOn.length === 0)
        return void 0;
    var deps = Object.create(null);
    for (var _i = 0, _a = cell.dependencies.dependsOn; _i < _a.length; _i++) {
        var dep = _a[_i];
        if (!dep.obj) {
            throw new Error('Unresolved dependency.');
        }
        deps[dep.transform.ref] = dep.obj;
    }
    return deps;
}
function createObject(ctx, cell, transformer, a, params) {
    if (!cell.cache)
        cell.cache = Object.create(null);
    return runTask(transformer.definition.apply({ a: a, params: params, cache: cell.cache, spine: ctx.spine, dependencies: resolveDependencies(cell) }, ctx.parent.globalContext), ctx.taskCtx);
}
function updateObject(ctx, cell, transformer, a, b, oldParams, newParams) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            if (!transformer.definition.update) {
                return [2 /*return*/, mol_state_transformer["a" /* StateTransformer */].UpdateResult.Recreate];
            }
            if (!cell.cache)
                cell.cache = Object.create(null);
            return [2 /*return*/, runTask(transformer.definition.update({ a: a, oldParams: oldParams, b: b, newParams: newParams, cache: cell.cache, spine: ctx.spine, dependencies: resolveDependencies(cell) }, ctx.parent.globalContext), ctx.taskCtx)];
        });
    });
}
//# sourceMappingURL=state.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/action.js
var mol_state_action = __webpack_require__(340);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-state/index.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */








//# sourceMappingURL=index.js.map

/***/ }),
/* 14 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Icon", function() { return Icon; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UnionSvg", function() { return UnionSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubtractSvg", function() { return SubtractSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IntersectSvg", function() { return IntersectSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetSvg", function() { return SetSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoleculeSvg", function() { return MoleculeSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CubeOutlineSvg", function() { return CubeOutlineSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CursorDefaultOutlineSvg", function() { return CursorDefaultOutlineSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FileOutlineSvg", function() { return FileOutlineSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PencilRulerSvg", function() { return PencilRulerSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AccountTreeOutlinedSvg", function() { return AccountTreeOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AddSvg", function() { return AddSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowDownwardSvg", function() { return ArrowDownwardSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowDropDownSvg", function() { return ArrowDropDownSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowRightSvg", function() { return ArrowRightSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ArrowUpwardSvg", function() { return ArrowUpwardSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AutorenewSvg", function() { return AutorenewSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BlurOnSvg", function() { return BlurOnSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BookmarksOutlinedSvg", function() { return BookmarksOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrushSvg", function() { return BrushSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BuildOutlinedSvg", function() { return BuildOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BuildSvg", function() { return BuildSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraOutlinedSvg", function() { return CameraOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CameraSvg", function() { return CameraSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelOutlinedSvg", function() { return CancelOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CancelSvg", function() { return CancelSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CenterFocusStrongSvg", function() { return CenterFocusStrongSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CheckSvg", function() { return CheckSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClearSvg", function() { return ClearSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CloseSvg", function() { return CloseSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CloudUploadSvg", function() { return CloudUploadSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CodeSvg", function() { return CodeSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteOutlinedSvg", function() { return DeleteOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DeleteSvg", function() { return DeleteSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ErrorSvg", function() { return ErrorSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExtensionSvg", function() { return ExtensionSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FlipToFrontSvg", function() { return FlipToFrontSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FullscreenSvg", function() { return FullscreenSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "GetAppSvg", function() { return GetAppSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelpOutlineSvg", function() { return HelpOutlineSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HomeOutlinedSvg", function() { return HomeOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LaunchSvg", function() { return LaunchSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LinearScaleSvg", function() { return LinearScaleSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MoreHorizSvg", function() { return MoreHorizSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigateBeforeSvg", function() { return NavigateBeforeSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NavigateNextSvg", function() { return NavigateNextSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "OpenInBrowserSvg", function() { return OpenInBrowserSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PlayArrowSvg", function() { return PlayArrowSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RefreshSvg", function() { return RefreshSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemoveSvg", function() { return RemoveSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RestoreSvg", function() { return RestoreSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SaveOutlinedSvg", function() { return SaveOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ScatterPlotSvg", function() { return ScatterPlotSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SkipPreviousSvg", function() { return SkipPreviousSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StopSvg", function() { return StopSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SubscriptionsOutlinedSvg", function() { return SubscriptionsOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SwapHorizSvg", function() { return SwapHorizSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TuneSvg", function() { return TuneSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VisibilityOffOutlinedSvg", function() { return VisibilityOffOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VisibilityOutlinedSvg", function() { return VisibilityOutlinedSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "WarningSvg", function() { return WarningSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectionModeSvg", function() { return SelectionModeSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SuperposeAtomsSvg", function() { return SuperposeAtomsSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SuperposeChainsSvg", function() { return SuperposeChainsSvg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SuperpositionSvg", function() { return SuperpositionSvg; });
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_0__);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function Icon(props) {
    if (!props.svg)
        return null;
    return react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("span", { className: "msp-icon msp-material-icon" + (props.inline ? ' msp-icon-inline' : ''), title: props.title, style: props.style },
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"](props.svg, null));
}
//
var circleLeft = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("circle", { r: '6px', id: 'circle-left', cy: '12px', cx: '8px', strokeWidth: '1px' });
var circleRight = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("circle", { r: '6px', id: 'circle-right', cy: '12px', cx: '16px', strokeWidth: '1px' });
var _Union = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("defs", null,
        circleLeft,
        circleRight),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("g", null,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-filled' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right', className: 'msp-shape-filled' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-empty' })));
function UnionSvg() { return _Union; }
var _Subtract = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("defs", null,
        circleLeft,
        circleRight,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("mask", { id: 'mask-left' },
            react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', fill: 'white', stroke: 'white' }),
            react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right', fill: 'black', strokeWidth: '0px', stroke: 'white' }))),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("g", null,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-filled', mask: 'url(#mask-left)' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right', className: 'msp-shape-empty' })));
function SubtractSvg() { return _Subtract; }
var _Intersect = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("defs", null,
        circleLeft,
        circleRight,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("clipPath", { id: 'clip-left' },
            react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right' }))),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("g", null,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-filled', clipPath: 'url(#clip-left)' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-empty' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right', className: 'msp-shape-empty' })));
function IntersectSvg() { return _Intersect; }
var _Set = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("defs", null,
        circleLeft,
        circleRight),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("g", null,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-left', className: 'msp-shape-empty' }),
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("use", { href: '#circle-right', className: 'msp-shape-filled' })));
function SetSvg() { return _Set; }
var _Molecule = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '17px', height: '17px', viewBox: '0 0 299.463 299.463', strokeWidth: '6px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("g", null,
        react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M256.851,173.832v-48.201c22.916-4.918,34.151-30.668,22.556-50.771c-11.547-20.004-39.486-23.251-55.242-5.844 l-41.746-24.106C189.618,22.603,172.861,0,149.734,0c-23.132,0-39.881,22.609-32.685,44.911L75.305,69.016 C59.522,51.586,31.597,54.88,20.061,74.863c-11.63,20.163-0.298,45.862,22.557,50.769v48.2 c-22.821,4.898-34.195,30.591-22.556,50.771c11.529,19.972,39.454,23.285,55.242,5.845l41.746,24.106 c-7.199,22.308,9.559,44.911,32.685,44.911c23.132,0,39.88-22.609,32.685-44.911l41.745-24.106 c15.817,17.469,43.73,14.099,55.242-5.844c0,0,0-0.001,0.001-0.002c4.587-7.953,5.805-17.213,3.431-26.076 C279.392,185.657,269.129,176.461,256.851,173.832z M249.62,72.088c20.568,0,27.428,27.191,10.008,37.239 c-0.003,0.002-0.006,0.003-0.009,0.005c-10.04,5.81-22.85,1.762-27.877-8.475C225.206,87.548,234.938,72.088,249.62,72.088z M149.734,14.4c11.005,0,19.958,8.954,19.958,19.959c0,11.127-9.077,19.958-19.958,19.958c-10.95,0-19.958-8.9-19.958-19.958 C129.776,23.354,138.729,14.4,149.734,14.4z M39.84,109.328c-17.451-10.067-10.534-37.24,10.01-37.24 c15.311,0,24.922,16.653,17.251,29.942C61.681,111.397,49.517,114.925,39.84,109.328z M59.802,224.702 c-9.535,5.503-21.768,2.229-27.268-7.298c-7.639-13.242,1.887-29.945,17.236-29.945c0.013,0,0.027,0,0.04,0 C70.07,187.48,77.49,214.469,59.802,224.702z M149.734,285.062c-11.005,0-19.958-8.954-19.958-19.958 c0-11.127,9.077-19.958,19.958-19.958c10.954,0,19.958,8.903,19.958,19.958C169.693,276.109,160.74,285.062,149.734,285.062z M216.953,217.982l-41.727,24.095c-13.778-15.22-37.459-14.94-50.983,0l-41.728-24.096c6.196-19.289-5.541-39.835-25.498-44.149 V125.63c19.752-4.268,31.762-24.65,25.498-44.149l41.727-24.095c13.629,15.055,37.32,15.093,50.983,0l41.728,24.096 c-6.196,19.29,5.534,39.835,25.498,44.149v48.202C222.61,178.123,210.721,198.581,216.953,217.982z M266.935,217.404 c-5.501,9.528-17.732,12.802-27.261,7.302c-17.682-10.23-10.301-37.247,10.032-37.247 C264.984,187.459,274.602,204.112,266.935,217.404z' })));
function MoleculeSvg() { return _Molecule; }
// The following icons are adapted from https://materialdesignicons.com/ and
// licensed with https://github.com/Templarian/MaterialDesign/blob/master/LICENSE
var _CubeOutline = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24', strokeWidth: '0.1px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: "M21,16.5C21,16.88 20.79,17.21 20.47,17.38L12.57,21.82C12.41,21.94 12.21,22 12,22C11.79,22 11.59,21.94 11.43,21.82L3.53,17.38C3.21,17.21 3,16.88 3,16.5V7.5C3,7.12 3.21,6.79 3.53,6.62L11.43,2.18C11.59,2.06 11.79,2 12,2C12.21,2 12.41,2.06 12.57,2.18L20.47,6.62C20.79,6.79 21,7.12 21,7.5V16.5M12,4.15L6.04,7.5L12,10.85L17.96,7.5L12,4.15M5,15.91L11,19.29V12.58L5,9.21V15.91M19,15.91V9.21L13,12.58V19.29L19,15.91Z" }));
function CubeOutlineSvg() { return _CubeOutline; }
var _CursorDefaultOutline = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M10.07,14.27C10.57,14.03 11.16,14.25 11.4,14.75L13.7,19.74L15.5,18.89L13.19,13.91C12.95,13.41 13.17,12.81 13.67,12.58L13.95,12.5L16.25,12.05L8,5.12V15.9L9.82,14.43L10.07,14.27M13.64,21.97C13.14,22.21 12.54,22 12.31,21.5L10.13,16.76L7.62,18.78C7.45,18.92 7.24,19 7,19A1,1 0 0,1 6,18V3A1,1 0 0,1 7,2C7.24,2 7.47,2.09 7.64,2.23L7.65,2.22L19.14,11.86C19.57,12.22 19.62,12.85 19.27,13.27C19.12,13.45 18.91,13.57 18.7,13.61L15.54,14.23L17.74,18.96C18,19.46 17.76,20.05 17.26,20.28L13.64,21.97Z' }));
function CursorDefaultOutlineSvg() { return _CursorDefaultOutline; }
var _FileOutline = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24', strokeWidth: '0.1px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { fill: 'currentColor', d: 'M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z' }));
function FileOutlineSvg() { return _FileOutline; }
var _PencilRuler = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24', strokeWidth: '0.1px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: "M3 17.25V21H6.75L17.81 9.93L14.06 6.18L3 17.25M22.61 18.36L18.36 22.61L13.16 17.41L14.93 15.64L15.93 16.64L18.4 14.16L19.82 15.58L18.36 17L19.42 18L20.84 16.6L22.61 18.36M6.61 10.83L1.39 5.64L5.64 1.39L7.4 3.16L4.93 5.64L6 6.7L8.46 4.22L9.88 5.64L8.46 7.05L9.46 8.05L6.61 10.83M20.71 7C21.1 6.61 21.1 6 20.71 5.59L18.37 3.29C18 2.9 17.35 2.9 16.96 3.29L15.12 5.12L18.87 8.87L20.71 7Z" }));
function PencilRulerSvg() { return _PencilRuler; }
// The following icons are adapted from https://material-ui.com/components/material-icons/ and
// licensed with https://github.com/mui-org/material-ui/blob/master/LICENSE
var _AccountTreeOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3h7zM7 9H4V5h3v4zm10 6h3v4h-3v-4zm0-10h3v4h-3V5z' }));
function AccountTreeOutlinedSvg() { return _AccountTreeOutlined; }
var _Add = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z' }));
function AddSvg() { return _Add; }
var _ArrowDownward = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z' }));
function ArrowDownwardSvg() { return _ArrowDownward; }
var _ArrowDropDown = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M7 10l5 5 5-5z' }));
function ArrowDropDownSvg() { return _ArrowDropDown; }
var _ArrowRight = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M10 17l5-5-5-5v10z' }));
function ArrowRightSvg() { return _ArrowRight; }
var _ArrowUpward = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z' }));
function ArrowUpwardSvg() { return _ArrowUpward; }
var _Autorenew = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 6v3l4-4-4-4v3c-4.42 0-8 3.58-8 8 0 1.57.46 3.03 1.24 4.26L6.7 14.8c-.45-.83-.7-1.79-.7-2.8 0-3.31 2.69-6 6-6zm6.76 1.74L17.3 9.2c.44.84.7 1.79.7 2.8 0 3.31-2.69 6-6 6v-3l-4 4 4 4v-3c4.42 0 8-3.58 8-8 0-1.57-.46-3.03-1.24-4.26z' }));
function AutorenewSvg() { return _Autorenew; }
var _BlurOn = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6 13c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-8c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm-3 .5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM6 5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm15 5.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM14 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0-3.5c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zm-11 10c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm7 7c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm0-17c.28 0 .5-.22.5-.5s-.22-.5-.5-.5-.5.22-.5.5.22.5.5.5zM10 7c.55 0 1-.45 1-1s-.45-1-1-1-1 .45-1 1 .45 1 1 1zm0 5.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm8 .5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-8c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0-4c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm3 8.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zM14 17c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm0 3.5c-.28 0-.5.22-.5.5s.22.5.5.5.5-.22.5-.5-.22-.5-.5-.5zm-4-12c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0 8.5c-.55 0-1 .45-1 1s.45 1 1 1 1-.45 1-1-.45-1-1-1zm4-4.5c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5zm0-4c-.83 0-1.5.67-1.5 1.5s.67 1.5 1.5 1.5 1.5-.67 1.5-1.5-.67-1.5-1.5-1.5z' }));
function BlurOnSvg() { return _BlurOn; }
var _BookmarksOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M15 7v12.97l-4.21-1.81-.79-.34-.79.34L5 19.97V7h10m4-6H8.99C7.89 1 7 1.9 7 3h10c1.1 0 2 .9 2 2v13l2 1V3c0-1.1-.9-2-2-2zm-4 4H5c-1.1 0-2 .9-2 2v16l7-3 7 3V7c0-1.1-.9-2-2-2z' }));
function BookmarksOutlinedSvg() { return _BookmarksOutlined; }
var _Brush = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34a.9959.9959 0 00-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z' }));
function BrushSvg() { return _Brush; }
var _BuildOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M22.61 18.99l-9.08-9.08c.93-2.34.45-5.1-1.44-7C9.79.61 6.21.4 3.66 2.26L7.5 6.11 6.08 7.52 2.25 3.69C.39 6.23.6 9.82 2.9 12.11c1.86 1.86 4.57 2.35 6.89 1.48l9.11 9.11c.39.39 1.02.39 1.41 0l2.3-2.3c.4-.38.4-1.01 0-1.41zm-3 1.6l-9.46-9.46c-.61.45-1.29.72-2 .82-1.36.2-2.79-.21-3.83-1.25C3.37 9.76 2.93 8.5 3 7.26l3.09 3.09 4.24-4.24-3.09-3.09c1.24-.07 2.49.37 3.44 1.31 1.08 1.08 1.49 2.57 1.24 3.96-.12.71-.42 1.37-.88 1.96l9.45 9.45-.88.89z' }));
function BuildOutlinedSvg() { return _BuildOutlined; }
var _Build = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M22.7 19l-9.1-9.1c.9-2.3.4-5-1.5-6.9-2-2-5-2.4-7.4-1.3L9 6 6 9 1.6 4.7C.4 7.1.9 10.1 2.9 12.1c1.9 1.9 4.6 2.4 6.9 1.5l9.1 9.1c.4.4 1 .4 1.4 0l2.3-2.3c.5-.4.5-1.1.1-1.4z' }));
function BuildSvg() { return _Build; }
var _CameraOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M14.25 2.26l-.08-.04-.01.02C13.46 2.09 12.74 2 12 2 6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10c0-4.75-3.31-8.72-7.75-9.74zM19.41 9h-7.99l2.71-4.7c2.4.66 4.35 2.42 5.28 4.7zM13.1 4.08L10.27 9l-1.15 2L6.4 6.3C7.84 4.88 9.82 4 12 4c.37 0 .74.03 1.1.08zM5.7 7.09L8.54 12l1.15 2H4.26C4.1 13.36 4 12.69 4 12c0-1.85.64-3.55 1.7-4.91zM4.59 15h7.98l-2.71 4.7c-2.4-.67-4.34-2.42-5.27-4.7zm6.31 4.91L14.89 13l2.72 4.7C16.16 19.12 14.18 20 12 20c-.38 0-.74-.04-1.1-.09zm7.4-3l-4-6.91h5.43c.17.64.27 1.31.27 2 0 1.85-.64 3.55-1.7 4.91z' }));
function CameraOutlinedSvg() { return _CameraOutlined; }
var _Camera = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M9.4 10.5l4.77-8.26C13.47 2.09 12.75 2 12 2c-2.4 0-4.6.85-6.32 2.25l3.66 6.35.06-.1zM21.54 9c-.92-2.92-3.15-5.26-6-6.34L11.88 9h9.66zm.26 1h-7.49l.29.5 4.76 8.25C21 16.97 22 14.61 22 12c0-.69-.07-1.35-.2-2zM8.54 12l-3.9-6.75C3.01 7.03 2 9.39 2 12c0 .69.07 1.35.2 2h7.49l-1.15-2zm-6.08 3c.92 2.92 3.15 5.26 6 6.34L12.12 15H2.46zm11.27 0l-3.9 6.76c.7.15 1.42.24 2.17.24 2.4 0 4.6-.85 6.32-2.25l-3.66-6.35-.93 1.6z' }));
function CameraSvg() { return _Camera; }
var _CancelOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3.59-13L12 10.59 8.41 7 7 8.41 10.59 12 7 15.59 8.41 17 12 13.41 15.59 17 17 15.59 13.41 12 17 8.41z' }));
function CancelOutlinedSvg() { return _CancelOutlined; }
var _Cancel = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z' }));
function CancelSvg() { return _Cancel; }
var _CenterFocusStrong = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-7 7H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z' }));
function CenterFocusStrongSvg() { return _CenterFocusStrong; }
var _Check = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z' }));
function CheckSvg() { return _Check; }
var _Clear = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z' }));
function ClearSvg() { return _Clear; }
var _Close = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z' }));
function CloseSvg() { return _Close; }
var _CloudUpload = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z' }));
function CloudUploadSvg() { return _CloudUpload; }
var _Code = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z' }));
function CodeSvg() { return _Code; }
var _DeleteOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M16 9v10H8V9h8m-1.5-6h-5l-1 1H5v2h14V4h-3.5l-1-1zM18 7H6v12c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7z' }));
function DeleteOutlinedSvg() { return _DeleteOutlined; }
var _Delete = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z' }));
function DeleteSvg() { return _Delete; }
var _Error = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z' }));
function ErrorSvg() { return _Error; }
var _Extension = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7 1.49 0 2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z' }));
function ExtensionSvg() { return _Extension; }
var _FlipToFront = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24', strokeWidth: '0.1px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M3 13h2v-2H3v2zm0 4h2v-2H3v2zm2 4v-2H3c0 1.1.89 2 2 2zM3 9h2V7H3v2zm12 12h2v-2h-2v2zm4-18H9c-1.11 0-2 .9-2 2v10c0 1.1.89 2 2 2h10c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 12H9V5h10v10zm-8 6h2v-2h-2v2zm-4 0h2v-2H7v2z' }));
function FlipToFrontSvg() { return _FlipToFront; }
var _Fullscreen = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z' }));
function FullscreenSvg() { return _Fullscreen; }
var _GetApp = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z' }));
function GetAppSvg() { return _GetApp; }
var _HelpOutline = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M11 18h2v-2h-2v2zm1-16C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z' }));
function HelpOutlineSvg() { return _HelpOutline; }
var _HomeOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 5.69l5 4.5V18h-2v-6H9v6H7v-7.81l5-4.5M12 3L2 12h3v8h6v-6h2v6h6v-8h3L12 3z' }));
function HomeOutlinedSvg() { return _HomeOutlined; }
var _Launch = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z' }));
function LaunchSvg() { return _Launch; }
var _LinearScale = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19.5 9.5c-1.03 0-1.9.62-2.29 1.5h-2.92c-.39-.88-1.26-1.5-2.29-1.5s-1.9.62-2.29 1.5H6.79c-.39-.88-1.26-1.5-2.29-1.5C3.12 9.5 2 10.62 2 12s1.12 2.5 2.5 2.5c1.03 0 1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5s1.9-.62 2.29-1.5h2.92c.39.88 1.26 1.5 2.29 1.5 1.38 0 2.5-1.12 2.5-2.5s-1.12-2.5-2.5-2.5z' }));
function LinearScaleSvg() { return _LinearScale; }
var _MoreHoriz = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z' }));
function MoreHorizSvg() { return _MoreHoriz; }
var _NavigateBefore = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z' }));
function NavigateBeforeSvg() { return _NavigateBefore; }
var _NavigateNext = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z' }));
function NavigateNextSvg() { return _NavigateNext; }
var _OpenInBrowser = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h4v-2H5V8h14v10h-4v2h4c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm-7 6l-4 4h3v6h2v-6h3l-4-4z' }));
function OpenInBrowserSvg() { return _OpenInBrowser; }
var _PlayArrow = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M8 5v14l11-7z' }));
function PlayArrowSvg() { return _PlayArrow; }
var _Refresh = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M17.65 6.35C16.2 4.9 14.21 4 12 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08c-.82 2.33-3.04 4-5.65 4-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z' }));
function RefreshSvg() { return _Refresh; }
var _Remove = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M19 13H5v-2h14v2z' }));
function RemoveSvg() { return _Remove; }
var _Restore = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z' }));
function RestoreSvg() { return _Restore; }
var _SaveOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24', strokeWidth: '0.1px' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm2 16H5V5h11.17L19 7.83V19zm-7-7c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3zM6 6h9v4H6z' }));
function SaveOutlinedSvg() { return _SaveOutlined; }
var _ScatterPlot = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("circle", { cx: '7', cy: '14', r: '3' }),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("circle", { cx: '11', cy: '6', r: '3' }),
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("circle", { cx: '16.6', cy: '17.6', r: '3' }));
function ScatterPlotSvg() { return _ScatterPlot; }
var _SkipPrevious = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6 6h2v12H6zm3.5 6l8.5 6V6z' }));
function SkipPreviousSvg() { return _SkipPrevious; }
var _Stop = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6 6h12v12H6z' }));
function StopSvg() { return _Stop; }
var _SubscriptionsOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M4 6h16v2H4zm2-4h12v2H6zm14 8H4c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-8c0-1.1-.9-2-2-2zm0 10H4v-8h16v8zm-10-7.27v6.53L16 16z' }));
function SubscriptionsOutlinedSvg() { return _SubscriptionsOutlined; }
var _SwapHoriz = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M6.99 11L3 15l3.99 4v-3H14v-2H6.99v-3zM21 9l-3.99-4v3H10v2h7.01v3L21 9z' }));
function SwapHorizSvg() { return _SwapHoriz; }
var _Tune = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z' }));
function TuneSvg() { return _Tune; }
var _VisibilityOffOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 6c3.79 0 7.17 2.13 8.82 5.5-.59 1.22-1.42 2.27-2.41 3.12l1.41 1.41c1.39-1.23 2.49-2.77 3.18-4.53C21.27 7.11 17 4 12 4c-1.27 0-2.49.2-3.64.57l1.65 1.65C10.66 6.09 11.32 6 12 6zm-1.07 1.14L13 9.21c.57.25 1.03.71 1.28 1.28l2.07 2.07c.08-.34.14-.7.14-1.07C16.5 9.01 14.48 7 12 7c-.37 0-.72.05-1.07.14zM2.01 3.87l2.68 2.68C3.06 7.83 1.77 9.53 1 11.5 2.73 15.89 7 19 12 19c1.52 0 2.98-.29 4.32-.82l3.42 3.42 1.41-1.41L3.42 2.45 2.01 3.87zm7.5 7.5l2.61 2.61c-.04.01-.08.02-.12.02-1.38 0-2.5-1.12-2.5-2.5 0-.05.01-.08.01-.13zm-3.4-3.4l1.75 1.75c-.23.55-.36 1.15-.36 1.78 0 2.48 2.02 4.5 4.5 4.5.63 0 1.23-.13 1.77-.36l.98.98c-.88.24-1.8.38-2.75.38-3.79 0-7.17-2.13-8.82-5.5.7-1.43 1.72-2.61 2.93-3.53z' }));
function VisibilityOffOutlinedSvg() { return _VisibilityOffOutlined; }
var _VisibilityOutlined = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M12 6c3.79 0 7.17 2.13 8.82 5.5C19.17 14.87 15.79 17 12 17s-7.17-2.13-8.82-5.5C4.83 8.13 8.21 6 12 6m0-2C7 4 2.73 7.11 1 11.5 2.73 15.89 7 19 12 19s9.27-3.11 11-7.5C21.27 7.11 17 4 12 4zm0 5c1.38 0 2.5 1.12 2.5 2.5S13.38 14 12 14s-2.5-1.12-2.5-2.5S10.62 9 12 9m0-2c-2.48 0-4.5 2.02-4.5 4.5S9.52 16 12 16s4.5-2.02 4.5-4.5S14.48 7 12 7z' }));
function VisibilityOutlinedSvg() { return _VisibilityOutlined; }
var _Warning = react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    react__WEBPACK_IMPORTED_MODULE_0__["createElement"]("path", { d: 'M1 21h22L12 2 1 21zm12-3h-2v-2h2v2zm0-4h-2v-4h2v4z' }));
function WarningSvg() { return _Warning; }
// Aliases
var SelectionModeSvg = CursorDefaultOutlineSvg;
var SuperposeAtomsSvg = ScatterPlotSvg;
var SuperposeChainsSvg = LinearScaleSvg;
var SuperpositionSvg = FlipToFrontSvg;
//# sourceMappingURL=icons.js.map

/***/ }),
/* 15 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/*
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var Type;
(function (Type) {
    function Variable(name, type, isConstraint) { return { kind: 'variable', name: name, type: type, isConstraint: isConstraint }; }
    Type.Variable = Variable;
    function Value(namespace, name, parent) { return { kind: 'value', namespace: namespace, name: name, parent: parent }; }
    Type.Value = Value;
    function Container(namespace, name, child, alias) { return { kind: 'container', namespace: namespace, name: name, child: child, alias: alias }; }
    Type.Container = Container;
    function Union(types) { return { kind: 'union', types: types }; }
    Type.Union = Union;
    function OneOf(namespace, name, type, values) {
        var vals = Object.create(null);
        for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
            var v = values_1[_i];
            vals[v] = true;
        }
        return { kind: 'oneof', namespace: namespace, name: name, type: type, values: vals };
    }
    Type.OneOf = OneOf;
    Type.Any = { kind: 'any' };
    Type.AnyValue = { kind: 'any-value' };
    Type.Num = Value('', 'Number');
    Type.Str = Value('', 'String');
    Type.Bool = OneOf('', 'Bool', Type.Str, ['true', 'false']);
    function oneOfValues(_a) {
        var values = _a.values;
        return Object.keys(values).sort();
    }
    Type.oneOfValues = oneOfValues;
})(Type || (Type = {}));
/* harmony default export */ __webpack_exports__["a"] = (Type);
//# sourceMappingURL=type.js.map

/***/ }),
/* 16 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ task["a" /* Task */]; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ scheduler["a" /* Scheduler */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ chunkedSubtask; });

// UNUSED EXPORTS: RuntimeContext, Progress, MultistepTask

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/task.js
var task = __webpack_require__(256);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/execution/synchronous.js
var synchronous = __webpack_require__(266);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/execution/runtime-context.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var runtime_context_RuntimeContext;
(function (RuntimeContext) {
    RuntimeContext.Synchronous = synchronous["a" /* SyncRuntimeContext */];
})(runtime_context_RuntimeContext || (runtime_context_RuntimeContext = {}));

//# sourceMappingURL=runtime-context.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/execution/progress.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var Progress;
(function (Progress) {
    function _format(root, prefix) {
        if (prefix === void 0) { prefix = ''; }
        var p = root.progress;
        if (!root.children.length) {
            if (p.isIndeterminate)
                return "" + prefix + p.taskName + ": " + p.message;
            return "" + prefix + p.taskName + ": [" + p.current + "/" + p.max + "] " + p.message;
        }
        var newPrefix = prefix + '  |_ ';
        var subTree = root.children.map(function (c) { return _format(c, newPrefix); });
        if (p.isIndeterminate)
            return "" + prefix + p.taskName + ": " + p.message + "\n" + subTree.join('\n');
        return "" + prefix + p.taskName + ": [" + p.current + "/" + p.max + "] " + p.message + "\n" + subTree.join('\n');
    }
    function format(p) { return _format(p.root); }
    Progress.format = format;
})(Progress || (Progress = {}));

//# sourceMappingURL=progress.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/util/scheduler.js
var scheduler = __webpack_require__(339);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/util/multistep.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function MultistepTask(name, steps, f, onAbort) {
    var _this = this;
    return function (params) { return task["a" /* Task */].create(name, function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () { return Object(tslib_es6["__generator"])(this, function (_a) {
        return [2 /*return*/, f(params, function (n) { return ctx.update({ message: "" + steps[n], current: n + 1, max: steps.length }); }, ctx)];
    }); }); }, onAbort); };
}

//# sourceMappingURL=multistep.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/util/chunked.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function chunkedSubtask(ctx, initialChunk, state, f, update) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var chunkSize, globalProcessed, globalTime, start, lastSize, currentTime, delta;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    chunkSize = Math.max(initialChunk, 0);
                    globalProcessed = 0, globalTime = 0;
                    if (ctx.isSynchronous) {
                        f(Number.MAX_SAFE_INTEGER, state);
                        return [2 /*return*/, state];
                    }
                    start = Object(now["b" /* now */])();
                    lastSize = 0, currentTime = 0;
                    _a.label = 1;
                case 1:
                    if (!((lastSize = f(chunkSize, state)) > 0)) return [3 /*break*/, 4];
                    globalProcessed += lastSize;
                    delta = Object(now["b" /* now */])() - start;
                    currentTime += delta;
                    globalTime += delta;
                    if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                    return [4 /*yield*/, update(ctx, state, globalProcessed)];
                case 2:
                    _a.sent();
                    chunkSize = Math.round(currentTime * globalProcessed / globalTime) + 1;
                    start = Object(now["b" /* now */])();
                    currentTime = 0;
                    _a.label = 3;
                case 3: return [3 /*break*/, 1];
                case 4:
                    if (!ctx.shouldUpdate) return [3 /*break*/, 6];
                    return [4 /*yield*/, update(ctx, state, globalProcessed)];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6: return [2 /*return*/, state];
            }
        });
    });
}

//# sourceMappingURL=chunked.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/index.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







//# sourceMappingURL=index.js.map

/***/ }),
/* 17 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return splitValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return getValueVersions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AttributeSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return UniformSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return TextureSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return ElementsSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return DefineSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return ValueSpec; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return GlobalUniformSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return InternalSchema; });
/* unused harmony export ColorSchema */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return SizeSchema; });
/* unused harmony export MarkerSchema */
/* unused harmony export OverpaintSchema */
/* unused harmony export TransparencySchema */
/* unused harmony export ClippingSchema */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return BaseSchema; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function splitValues(schema, values) {
    var attributeValues = {};
    var defineValues = {};
    var textureValues = {};
    var uniformValues = {};
    var materialUniformValues = {};
    Object.keys(schema).forEach(function (k) {
        var spec = schema[k];
        if (spec.type === 'attribute')
            attributeValues[k] = values[k];
        if (spec.type === 'define')
            defineValues[k] = values[k];
        if (spec.type === 'texture')
            textureValues[k] = values[k];
        // check if k exists in values so that global uniforms are excluded here
        if (spec.type === 'uniform' && values[k] !== undefined) {
            if (spec.isMaterial)
                materialUniformValues[k] = values[k];
            else
                uniformValues[k] = values[k];
        }
    });
    return { attributeValues: attributeValues, defineValues: defineValues, textureValues: textureValues, uniformValues: uniformValues, materialUniformValues: materialUniformValues };
}
function getValueVersions(values) {
    var versions = {};
    Object.keys(values).forEach(function (k) {
        versions[k] = values[k].ref.version;
    });
    return versions;
}
function AttributeSpec(kind, itemSize, divisor) {
    return { type: 'attribute', kind: kind, itemSize: itemSize, divisor: divisor };
}
function UniformSpec(kind, isMaterial) {
    if (isMaterial === void 0) { isMaterial = false; }
    return { type: 'uniform', kind: kind, isMaterial: isMaterial };
}
function TextureSpec(kind, format, dataType, filter) {
    return { type: 'texture', kind: kind, format: format, dataType: dataType, filter: filter };
}
function ElementsSpec(kind) {
    return { type: 'elements', kind: kind };
}
function DefineSpec(kind, options) {
    return { type: 'define', kind: kind, options: options };
}
function ValueSpec(kind) {
    return { type: 'value', kind: kind };
}
//
var GlobalUniformSchema = {
    uModel: UniformSpec('m4'),
    uView: UniformSpec('m4'),
    uInvView: UniformSpec('m4'),
    uModelView: UniformSpec('m4'),
    uInvModelView: UniformSpec('m4'),
    uProjection: UniformSpec('m4'),
    uInvProjection: UniformSpec('m4'),
    uModelViewProjection: UniformSpec('m4'),
    uInvModelViewProjection: UniformSpec('m4'),
    uIsOrtho: UniformSpec('f'),
    uPixelRatio: UniformSpec('f'),
    uViewportHeight: UniformSpec('f'),
    uViewport: UniformSpec('v4'),
    uViewOffset: UniformSpec('v2'),
    uCameraPosition: UniformSpec('v3'),
    uNear: UniformSpec('f'),
    uFar: UniformSpec('f'),
    uFogNear: UniformSpec('f'),
    uFogFar: UniformSpec('f'),
    uFogColor: UniformSpec('v3'),
    uTransparentBackground: UniformSpec('i'),
    uClipObjectType: UniformSpec('i[]'),
    uClipObjectPosition: UniformSpec('v3[]'),
    uClipObjectRotation: UniformSpec('v4[]'),
    uClipObjectScale: UniformSpec('v3[]'),
    // all the following could in principle be per object
    // as a kind of 'material' parameter set
    // would need to test performance implications
    uLightIntensity: UniformSpec('f'),
    uAmbientIntensity: UniformSpec('f'),
    uMetalness: UniformSpec('f'),
    uRoughness: UniformSpec('f'),
    uReflectivity: UniformSpec('f'),
    uPickingAlphaThreshold: UniformSpec('f'),
    uInteriorDarkening: UniformSpec('f'),
    uInteriorColorFlag: UniformSpec('i'),
    uInteriorColor: UniformSpec('v3'),
    uHighlightColor: UniformSpec('v3'),
    uSelectColor: UniformSpec('v3'),
};
var InternalSchema = {
    uObjectId: UniformSpec('i'),
};
var ColorSchema = {
    // aColor: AttributeSpec('float32', 3, 0), // TODO
    uColor: UniformSpec('v3', true),
    uColorTexDim: UniformSpec('v2'),
    tColor: TextureSpec('image-uint8', 'rgb', 'ubyte', 'nearest'),
    dColorType: DefineSpec('string', ['uniform', 'attribute', 'instance', 'group', 'group_instance']),
};
var SizeSchema = {
    // aSize: AttributeSpec('float32', 1, 0), // TODO
    uSize: UniformSpec('f', true),
    uSizeTexDim: UniformSpec('v2'),
    tSize: TextureSpec('image-uint8', 'alpha', 'ubyte', 'nearest'),
    dSizeType: DefineSpec('string', ['uniform', 'attribute', 'instance', 'group', 'group_instance']),
    uSizeFactor: UniformSpec('f'),
};
var MarkerSchema = {
    uMarkerTexDim: UniformSpec('v2'),
    tMarker: TextureSpec('image-uint8', 'alpha', 'ubyte', 'nearest'),
};
var OverpaintSchema = {
    uOverpaintTexDim: UniformSpec('v2'),
    tOverpaint: TextureSpec('image-uint8', 'rgba', 'ubyte', 'nearest'),
    dOverpaint: DefineSpec('boolean'),
};
var TransparencySchema = {
    uTransparencyTexDim: UniformSpec('v2'),
    tTransparency: TextureSpec('image-uint8', 'alpha', 'ubyte', 'nearest'),
    dTransparency: DefineSpec('boolean'),
    dTransparencyVariant: DefineSpec('string', ['single', 'multi']),
};
var ClippingSchema = {
    dClipObjectCount: DefineSpec('number'),
    dClipVariant: DefineSpec('string', ['instance', 'pixel']),
    uClippingTexDim: UniformSpec('v2'),
    tClipping: TextureSpec('image-uint8', 'alpha', 'ubyte', 'nearest'),
    dClipping: DefineSpec('boolean'),
};
var BaseSchema = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, ColorSchema), MarkerSchema), OverpaintSchema), TransparencySchema), ClippingSchema), { aInstance: AttributeSpec('float32', 1, 1), aGroup: AttributeSpec('float32', 1, 0),
    /**
     * final per-instance transform calculated for instance `i` as
     * `aTransform[i] = matrix * transform[i] * extraTransform[i]`
     */
    aTransform: AttributeSpec('float32', 16, 1),
    /**
     * final alpha, calculated as `values.alpha * state.alpha`
     */
    uAlpha: UniformSpec('f', true), uInstanceCount: UniformSpec('i'), uGroupCount: UniformSpec('i'), uInvariantBoundingSphere: UniformSpec('v4'), drawCount: ValueSpec('number'), instanceCount: ValueSpec('number'),
    /** base alpha, see uAlpha  */
    alpha: ValueSpec('number'),
    /** global transform, see aTransform */
    matrix: ValueSpec('m4'),
    /** base per-instance transform, see aTransform */
    transform: ValueSpec('float32'),
    /** additional per-instance transform, see aTransform */
    extraTransform: ValueSpec('float32'),
    /** bounding sphere taking aTransform into account and encompases all instances */
    boundingSphere: ValueSpec('sphere'),
    /** bounding sphere NOT taking aTransform into account */
    invariantBoundingSphere: ValueSpec('sphere') });
//# sourceMappingURL=schema.js.map

/***/ }),
/* 18 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Argument; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Arguments; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return MSymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CustomPropSymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isSymbol; });
/* harmony import */ var _expression__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(132);
/*
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function Argument(type, params) {
    var _a = params || {}, _b = _a.description, description = _b === void 0 ? void 0 : _b, _c = _a.isOptional, isOptional = _c === void 0 ? false : _c, _d = _a.isRest, isRest = _d === void 0 ? false : _d, _e = _a.defaultValue, defaultValue = _e === void 0 ? void 0 : _e;
    return { type: type, isOptional: isOptional, isRest: isRest, defaultValue: defaultValue, description: description };
}
var Arguments;
(function (Arguments) {
    Arguments.None = Dictionary({});
    function Dictionary(map) {
        return { kind: 'dictionary', map: map, '@type': 0 };
    }
    Arguments.Dictionary = Dictionary;
    function List(type, params) {
        var _a = (params || {}).nonEmpty, nonEmpty = _a === void 0 ? false : _a;
        return { kind: 'list', type: type, nonEmpty: nonEmpty, '@type': 0 };
    }
    Arguments.List = List;
})(Arguments || (Arguments = {}));
function MSymbol(name, args, type, description) {
    var symbol = function (args) {
        return _expression__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Apply(_expression__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Symbol(symbol.id), args);
    };
    symbol.info = { namespace: '', name: name, description: description };
    symbol.id = '';
    symbol.args = args;
    symbol.type = type;
    return symbol;
}
function CustomPropSymbol(namespace, name, type, description) {
    var symbol = function (args) {
        return _expression__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Apply(_expression__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Symbol(symbol.id), args);
    };
    symbol.info = { namespace: namespace, name: name, description: description };
    symbol.id = namespace + "." + name;
    symbol.args = Arguments.None;
    symbol.type = type;
    return symbol;
}
function isSymbol(x) {
    var s = x;
    return typeof s === 'function' && !!s.info && !!s.args && typeof s.info.namespace === 'string' && !!s.type;
}
//# sourceMappingURL=symbol.js.map

/***/ }),
/* 19 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ControlGroup", function() { return ControlGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TextInput", function() { return TextInput; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandableControlRow", function() { return ExpandableControlRow; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SectionHeader", function() { return SectionHeader; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Button", function() { return Button; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "IconButton", function() { return IconButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleButton", function() { return ToggleButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ExpandGroup", function() { return ExpandGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ControlRow", function() { return ControlRow; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _icons__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var ControlGroup = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ControlGroup, _super);
    function ControlGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: !!_this.props.initialExpanded };
        _this.headerClicked = function () {
            if (_this.props.onHeaderClick) {
                _this.props.onHeaderClick();
            }
            else {
                _this.setState({ isExpanded: !_this.state.isExpanded });
            }
        };
        return _this;
    }
    ControlGroup.prototype.render = function () {
        var groupClassName = this.props.hideOffset ? 'msp-control-group-children' : 'msp-control-group-children msp-control-offset';
        if (this.props.childrenClassName)
            groupClassName += ' ' + this.props.childrenClassName;
        // TODO: customize header style (bg color, togle button etc)
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-wrapper', style: { position: 'relative', marginTop: this.props.noTopMargin ? 0 : void 0 } },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-header', style: { marginLeft: this.props.headerLeftMargin }, title: this.props.title },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Button, { onClick: this.headerClicked },
                    !this.props.hideExpander && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: this.state.isExpanded ? _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowRightSvg"] : _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowDropDownSvg"] }),
                    this.props.topRightIcon && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: this.props.topRightIcon, style: { position: 'absolute', right: '2px', top: 0 } }),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, this.props.header))),
            this.state.isExpanded && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: groupClassName, style: { display: this.state.isExpanded ? 'block' : 'none', maxHeight: this.props.maxHeight, overflow: 'hidden', overflowY: 'auto' } }, this.props.children));
    };
    return ControlGroup;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

function _id(x) { return x; }
var TextInput = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TextInput, _super);
    function TextInput() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.input = react__WEBPACK_IMPORTED_MODULE_1__["createRef"]();
        _this.delayHandle = void 0;
        _this.pendingValue = void 0;
        _this.state = { originalValue: '', value: '' };
        _this.onBlur = function () {
            _this.setState({ value: '' + _this.state.originalValue });
            if (_this.props.onBlur)
                _this.props.onBlur();
        };
        _this.raiseOnChange = function () {
            if (_this.pendingValue === void 0)
                return;
            _this.props.onChange(_this.pendingValue);
            _this.pendingValue = void 0;
        };
        _this.onChange = function (e) {
            var value = e.target.value;
            var isInvalid = (_this.props.isValid && !_this.props.isValid(value)) || (_this.props.numeric && Number.isNaN(+value));
            if (isInvalid) {
                _this.clearTimeout();
                _this.setState({ value: value });
                return;
            }
            if (_this.props.numeric) {
                _this.setState({ value: value }, function () { return _this.triggerChanged(value, +value); });
            }
            else {
                var converted_1 = (_this.props.toValue || _id)(value);
                var formatted_1 = (_this.props.fromValue || _id)(converted_1);
                _this.setState({ value: formatted_1 }, function () { return _this.triggerChanged(formatted_1, converted_1); });
            }
        };
        _this.onKeyUp = function (e) {
            if (e.charCode === 27 || e.keyCode === 27 /* esc */) {
                if (_this.props.blurOnEscape && _this.input.current) {
                    _this.input.current.blur();
                }
            }
        };
        _this.onKeyPress = function (e) {
            if (e.keyCode === 13 || e.charCode === 13 /* enter */) {
                if (_this.isPending) {
                    _this.clearTimeout();
                    _this.raiseOnChange();
                }
                if (_this.props.blurOnEnter && _this.input.current) {
                    _this.input.current.blur();
                }
                if (_this.props.onEnter)
                    _this.props.onEnter();
            }
            e.stopPropagation();
        };
        return _this;
    }
    Object.defineProperty(TextInput.prototype, "isPending", {
        get: function () { return typeof this.delayHandle !== 'undefined'; },
        enumerable: false,
        configurable: true
    });
    TextInput.prototype.clearTimeout = function () {
        if (this.isPending) {
            clearTimeout(this.delayHandle);
            this.delayHandle = void 0;
        }
    };
    TextInput.prototype.triggerChanged = function (formatted, converted) {
        this.clearTimeout();
        if (formatted === this.state.originalValue)
            return;
        if (this.props.delayMs) {
            this.pendingValue = converted;
            this.delayHandle = setTimeout(this.raiseOnChange, this.props.delayMs);
        }
        else {
            this.props.onChange(converted);
        }
    };
    TextInput.getDerivedStateFromProps = function (props, state) {
        var value = props.fromValue ? props.fromValue(props.value) : props.value;
        if (value === state.originalValue)
            return null;
        return { originalValue: value, value: value };
    };
    TextInput.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("input", { type: 'text', className: this.props.className, style: this.props.style, ref: this.input, onBlur: this.onBlur, value: this.state.value, placeholder: this.props.placeholder, onChange: this.onChange, onKeyPress: this.props.onEnter || this.props.blurOnEnter || this.props.blurOnEscape ? this.onKeyPress : void 0, onKeyDown: this.props.blurOnEscape ? this.onKeyUp : void 0, disabled: !!this.props.isDisabled });
    };
    return TextInput;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var ExpandableControlRow = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExpandableControlRow, _super);
    function ExpandableControlRow() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        return _this;
    }
    ExpandableControlRow.prototype.render = function () {
        var _a = this.props, label = _a.label, pivot = _a.pivot, controls = _a.controls;
        // TODO: fix the inline CSS
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ControlRow, { label: react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
                    label,
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("button", { className: 'msp-btn-link msp-btn-icon msp-control-group-expander', onClick: this.toggleExpanded, title: (this.state.isExpanded ? 'Less' : 'More') + " options", style: { background: 'transparent', textAlign: 'left', padding: '0' } },
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: this.state.isExpanded ? _icons__WEBPACK_IMPORTED_MODULE_3__["RemoveSvg"] : _icons__WEBPACK_IMPORTED_MODULE_3__["AddSvg"], style: { display: 'inline-block' } }))), control: pivot }, this.props.colorStripe && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-expandable-group-color-stripe', style: { backgroundColor: _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toStyle(this.props.colorStripe) } })),
            this.state.isExpanded && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-offset' }, controls));
    };
    return ExpandableControlRow;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

function SectionHeader(props) {
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: "msp-section-header" + (props.accent ? ' msp-transform-header-brand-' + props.accent : '') },
        props.icon && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: props.icon }),
        props.title,
        " ",
        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("small", null, props.desc));
}
function Button(props) {
    var className = 'msp-btn';
    if (!props.inline)
        className += ' msp-btn-block';
    if (props.noOverflow)
        className += ' msp-no-overflow';
    if (props.flex)
        className += ' msp-flex-item';
    if (props.commit === 'on' || props.commit)
        className += ' msp-btn-commit msp-btn-commit-on';
    if (props.commit === 'off')
        className += ' msp-btn-commit msp-btn-commit-off';
    if (!props.children)
        className += ' msp-btn-childless';
    if (props.className)
        className += ' ' + props.className;
    var style = void 0;
    if (props.flex) {
        if (typeof props.flex === 'number')
            style = { flex: "0 0 " + props.flex + "px", padding: 0, maxWidth: props.flex + "px" };
        else if (typeof props.flex === 'string')
            style = { flex: "0 0 " + props.flex, padding: 0, maxWidth: props.flex };
    }
    if (props.style) {
        if (style)
            Object.assign(style, props.style);
        else
            style = props.style;
    }
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("button", { onClick: props.onClick, title: props.title, disabled: props.disabled, style: style, className: className, "data-id": props['data-id'], "data-color": props['data-color'], onContextMenu: props.onContextMenu, onMouseEnter: props.onMouseEnter, onMouseLeave: props.onMouseLeave },
        props.icon && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: props.icon }),
        props.children);
}
function IconButton(props) {
    var className = "msp-btn msp-btn-icon" + (props.small ? '-small' : '') + (props.className ? ' ' + props.className : '');
    if (typeof props.toggleState !== 'undefined') {
        className += " msp-btn-link-toggle-" + (props.toggleState ? 'on' : 'off');
    }
    if (props.transparent) {
        className += ' msp-transparent-bg';
    }
    var style = void 0;
    if (props.flex) {
        if (typeof props.flex === 'boolean')
            style = { flex: '0 0 32px', padding: 0 };
        else if (typeof props.flex === 'number')
            style = { flex: "0 0 " + props.flex + "px", padding: 0, maxWidth: props.flex + "px" };
        else
            style = { flex: "0 0 " + props.flex, padding: 0, maxWidth: props.flex };
    }
    if (props.style) {
        if (style)
            Object.assign(style, props.style);
        else
            style = props.style;
    }
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("button", { className: className, onClick: props.onClick, title: props.title, disabled: props.disabled, "data-id": props['data-id'], style: style },
        props.svg && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: props.svg }),
        props.extraContent);
}
var ToggleButton = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ToggleButton, _super);
    function ToggleButton() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onClick = function (e) {
            e.currentTarget.blur();
            _this.props.toggle();
        };
        return _this;
    }
    ToggleButton.prototype.render = function () {
        var props = this.props;
        var label = props.label;
        var className = props.isSelected ? (props.className || '') + " msp-control-current" : props.className;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Button, { icon: this.props.icon, onClick: this.onClick, title: this.props.title, disabled: props.disabled, style: props.style, className: className }, label && this.props.isSelected ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, label) : label);
    };
    return ToggleButton;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var ExpandGroup = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExpandGroup, _super);
    function ExpandGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: !!_this.props.initiallyExpanded };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        return _this;
    }
    ExpandGroup.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-header', style: { marginTop: this.props.marginTop !== void 0 ? this.props.marginTop : '1px', marginLeft: this.props.headerLeftMargin } },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("button", { className: 'msp-btn msp-form-control msp-btn-block', onClick: this.toggleExpanded, style: this.props.headerStyle },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: this.state.isExpanded ? _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowDropDownSvg"] : _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowRightSvg"] }),
                    this.props.header)),
            this.state.isExpanded &&
                (this.props.noOffset
                    ? this.props.children
                    : react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this.props.accent ? 'msp-accent-offset' : 'msp-control-offset' }, this.props.children)));
    };
    return ExpandGroup;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

function ControlRow(props) {
    var className = 'msp-control-row';
    if (props.className)
        className += ' ' + props.className;
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: className },
        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { className: 'msp-control-row-label', title: props.title }, props.label),
        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-row-ctrl' }, props.control),
        props.children);
}
//# sourceMappingURL=common.js.map

/***/ }),
/* 20 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Tokenizer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return trimStr; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TokenBuilder; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * mostly from https://github.com/dsehnal/CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function Tokenizer(data) {
    return {
        data: data,
        position: 0,
        length: data.length,
        lineNumber: 1,
        tokenStart: 0,
        tokenEnd: 0
    };
}
(function (Tokenizer) {
    function getTokenString(state) {
        return state.data.substring(state.tokenStart, state.tokenEnd);
    }
    Tokenizer.getTokenString = getTokenString;
    /** Resets the state */
    function reset(state) {
        state.position = 0;
        state.lineNumber = 1;
        state.tokenStart = 0;
        state.tokenEnd = 0;
    }
    Tokenizer.reset = reset;
    /**
     * Eat everything until a newline occurs.
     */
    function eatLine(state) {
        var data = state.data;
        while (state.position < state.length) {
            switch (data.charCodeAt(state.position)) {
                case 10: // \n
                    state.tokenEnd = state.position;
                    ++state.position;
                    ++state.lineNumber;
                    return true;
                case 13: // \r
                    state.tokenEnd = state.position;
                    ++state.position;
                    ++state.lineNumber;
                    if (data.charCodeAt(state.position) === 10) {
                        ++state.position;
                    }
                    return true;
                default:
                    ++state.position;
                    break;
            }
        }
        state.tokenEnd = state.position;
        return state.tokenStart !== state.tokenEnd;
    }
    Tokenizer.eatLine = eatLine;
    /** Sets the current token start to the current position */
    function markStart(state) {
        state.tokenStart = state.position;
    }
    Tokenizer.markStart = markStart;
    /** Sets the current token start to current position and moves to the next line. */
    function markLine(state) {
        state.tokenStart = state.position;
        return eatLine(state);
    }
    Tokenizer.markLine = markLine;
    /** Advance the state by the given number of lines and return line as string. */
    function readLine(state) {
        markLine(state);
        return getTokenString(state);
    }
    Tokenizer.readLine = readLine;
    function readLinesChunk(state, count, tokens) {
        var read = 0;
        for (var i = 0; i < count; i++) {
            if (!markLine(state))
                return read;
            TokenBuilder.addUnchecked(tokens, state.tokenStart, state.tokenEnd);
            read++;
        }
        return read;
    }
    /** Advance the state by the given number of lines and return them*/
    function markLines(state, count) {
        var lineTokens = TokenBuilder.create(state.data, count * 2);
        readLinesChunk(state, count, lineTokens);
        return lineTokens;
    }
    Tokenizer.markLines = markLines;
    /** Advance the state by the given number of lines and return them */
    function readLines(state, count) {
        var ret = [];
        for (var i = 0; i < count; i++) {
            ret.push(Tokenizer.readLine(state));
        }
        return ret;
    }
    Tokenizer.readLines = readLines;
    /** Advance the state by the given number of lines and return line starts/ends as tokens. */
    function readLinesAsync(state, count, ctx, initialLineCount) {
        if (initialLineCount === void 0) { initialLineCount = 100000; }
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var length, lineTokens, linesAlreadyRead;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        length = state.length;
                        lineTokens = TokenBuilder.create(state.data, count * 2);
                        linesAlreadyRead = 0;
                        return [4 /*yield*/, Object(_mol_task__WEBPACK_IMPORTED_MODULE_1__[/* chunkedSubtask */ "c"])(ctx, initialLineCount, state, function (chunkSize, state) {
                                var linesToRead = Math.min(count - linesAlreadyRead, chunkSize);
                                readLinesChunk(state, linesToRead, lineTokens);
                                linesAlreadyRead += linesToRead;
                                return linesToRead;
                            }, function (ctx, state) { return ctx.update({ message: 'Parsing...', current: state.position, max: length }); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, lineTokens];
                }
            });
        });
    }
    Tokenizer.readLinesAsync = readLinesAsync;
    function readAllLines(data) {
        var state = Tokenizer(data);
        var tokens = TokenBuilder.create(state.data, Math.max(data.length / 80, 2));
        while (markLine(state)) {
            TokenBuilder.add(tokens, state.tokenStart, state.tokenEnd);
        }
        return tokens;
    }
    Tokenizer.readAllLines = readAllLines;
    function readLinesChunkChecked(state, count, tokens) {
        var read = 0;
        for (var i = 0; i < count; i++) {
            if (!markLine(state))
                return read;
            TokenBuilder.add(tokens, state.tokenStart, state.tokenEnd);
            read++;
        }
        return read;
    }
    function readAllLinesAsync(data, ctx, chunkSize) {
        if (chunkSize === void 0) { chunkSize = 100000; }
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var state, tokens;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        state = Tokenizer(data);
                        tokens = TokenBuilder.create(state.data, Math.max(data.length / 80, 2));
                        return [4 /*yield*/, Object(_mol_task__WEBPACK_IMPORTED_MODULE_1__[/* chunkedSubtask */ "c"])(ctx, chunkSize, state, function (chunkSize, state) {
                                readLinesChunkChecked(state, chunkSize, tokens);
                                return state.position < state.length ? chunkSize : 0;
                            }, function (ctx, state) { return ctx.update({ message: 'Parsing...', current: state.position, max: length }); })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, tokens];
                }
            });
        });
    }
    Tokenizer.readAllLinesAsync = readAllLinesAsync;
    /**
     * Eat everything until a whitespace/newline occurs.
     */
    function eatValue(state) {
        while (state.position < state.length) {
            switch (state.data.charCodeAt(state.position)) {
                case 9: // \t
                case 10: // \n
                case 13: // \r
                case 32: // ' '
                    state.tokenEnd = state.position;
                    return;
                default:
                    ++state.position;
                    break;
            }
        }
        state.tokenEnd = state.position;
    }
    Tokenizer.eatValue = eatValue;
    /**
     * Skips all the whitespace - space, tab, newline, CR
     * Handles incrementing line count.
     */
    function skipWhitespace(state) {
        var prev = -1;
        while (state.position < state.length) {
            var c = state.data.charCodeAt(state.position);
            switch (c) {
                case 9: // '\t'
                case 32: // ' '
                    prev = c;
                    ++state.position;
                    break;
                case 10: // \n
                    // handle \r\n
                    if (prev !== 13) {
                        ++state.lineNumber;
                    }
                    prev = c;
                    ++state.position;
                    break;
                case 13: // \r
                    prev = c;
                    ++state.position;
                    ++state.lineNumber;
                    break;
                default:
                    return prev;
            }
        }
        return prev;
    }
    Tokenizer.skipWhitespace = skipWhitespace;
    /** Trims spaces and tabs */
    function trim(state, start, end) {
        var data = state.data;
        var s = start, e = end - 1;
        var c = data.charCodeAt(s);
        while ((c === 9 || c === 32) && s <= e)
            c = data.charCodeAt(++s);
        c = data.charCodeAt(e);
        while ((c === 9 || c === 32) && e >= s)
            c = data.charCodeAt(--e);
        state.tokenStart = s;
        state.tokenEnd = e + 1;
        state.position = end;
        return state;
    }
    Tokenizer.trim = trim;
})(Tokenizer || (Tokenizer = {}));
function trimStr(data, start, end) {
    var s = start, e = end - 1;
    var c = data.charCodeAt(s);
    while ((c === 9 || c === 32) && s <= e)
        c = data.charCodeAt(++s);
    c = data.charCodeAt(e);
    while ((c === 9 || c === 32) && e >= s)
        c = data.charCodeAt(--e);
    return data.substring(s, e + 1);
}
var TokenBuilder;
(function (TokenBuilder) {
    function resize(builder) {
        // scale the size using golden ratio, because why not.
        var newBuffer = new Uint32Array((1.61 * builder.indices.length) | 0);
        newBuffer.set(builder.indices);
        builder.indices = newBuffer;
        builder.indicesLenMinus2 = (newBuffer.length - 2) | 0;
    }
    function add(tokens, start, end) {
        var builder = tokens;
        if (builder.offset > builder.indicesLenMinus2) {
            resize(builder);
        }
        builder.indices[builder.offset++] = start;
        builder.indices[builder.offset++] = end;
        tokens.count++;
    }
    TokenBuilder.add = add;
    function addToken(tokens, tokenizer) {
        add(tokens, tokenizer.tokenStart, tokenizer.tokenEnd);
    }
    TokenBuilder.addToken = addToken;
    function addUnchecked(tokens, start, end) {
        tokens.indices[tokens.offset++] = start;
        tokens.indices[tokens.offset++] = end;
        tokens.count++;
    }
    TokenBuilder.addUnchecked = addUnchecked;
    function create(data, size) {
        size = Math.max(10, size);
        return {
            data: data,
            indicesLenMinus2: (size - 2) | 0,
            count: 0,
            offset: 0,
            indices: new Uint32Array(size)
        };
    }
    TokenBuilder.create = create;
})(TokenBuilder || (TokenBuilder = {}));
//# sourceMappingURL=tokenizer.js.map

/***/ }),
/* 21 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __extends; });
/* unused harmony export __assign */
/* unused harmony export __rest */
/* unused harmony export __decorate */
/* unused harmony export __param */
/* unused harmony export __metadata */
/* unused harmony export __awaiter */
/* unused harmony export __generator */
/* unused harmony export __createBinding */
/* unused harmony export __exportStar */
/* unused harmony export __values */
/* unused harmony export __read */
/* unused harmony export __spread */
/* unused harmony export __spreadArrays */
/* unused harmony export __await */
/* unused harmony export __asyncGenerator */
/* unused harmony export __asyncDelegator */
/* unused harmony export __asyncValues */
/* unused harmony export __makeTemplateObject */
/* unused harmony export __importStar */
/* unused harmony export __importDefault */
/* unused harmony export __classPrivateFieldGet */
/* unused harmony export __classPrivateFieldSet */
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */

var extendStatics = function(d, b) {
    extendStatics = Object.setPrototypeOf ||
        ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
        function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
    return extendStatics(d, b);
};

function __extends(d, b) {
    extendStatics(d, b);
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}

var __assign = function() {
    __assign = Object.assign || function __assign(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
        }
        return t;
    }
    return __assign.apply(this, arguments);
}

function __rest(s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
}

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function __param(paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
}

function __metadata(metadataKey, metadataValue) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
}

function __awaiter(thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
}

function __generator(thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
}

function __createBinding(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}

function __exportStar(m, exports) {
    for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p];
}

function __values(o) {
    var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
    if (m) return m.call(o);
    if (o && typeof o.length === "number") return {
        next: function () {
            if (o && i >= o.length) o = void 0;
            return { value: o && o[i++], done: !o };
        }
    };
    throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}

function __read(o, n) {
    var m = typeof Symbol === "function" && o[Symbol.iterator];
    if (!m) return o;
    var i = m.call(o), r, ar = [], e;
    try {
        while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
    }
    catch (error) { e = { error: error }; }
    finally {
        try {
            if (r && !r.done && (m = i["return"])) m.call(i);
        }
        finally { if (e) throw e.error; }
    }
    return ar;
}

function __spread() {
    for (var ar = [], i = 0; i < arguments.length; i++)
        ar = ar.concat(__read(arguments[i]));
    return ar;
}

function __spreadArrays() {
    for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
    for (var r = Array(s), k = 0, i = 0; i < il; i++)
        for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
            r[k] = a[j];
    return r;
};

function __await(v) {
    return this instanceof __await ? (this.v = v, this) : new __await(v);
}

function __asyncGenerator(thisArg, _arguments, generator) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var g = generator.apply(thisArg, _arguments || []), i, q = [];
    return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
    function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
    function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
    function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
    function fulfill(value) { resume("next", value); }
    function reject(value) { resume("throw", value); }
    function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}

function __asyncDelegator(o) {
    var i, p;
    return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
    function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}

function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator], i;
    return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
    function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
    function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}

function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

function __importStar(mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result.default = mod;
    return result;
}

function __importDefault(mod) {
    return (mod && mod.__esModule) ? mod : { default: mod };
}

function __classPrivateFieldGet(receiver, privateMap) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to get private field on non-instance");
    }
    return privateMap.get(receiver);
}

function __classPrivateFieldSet(receiver, privateMap, value) {
    if (!privateMap.has(receiver)) {
        throw new TypeError("attempted to set private field on non-instance");
    }
    privateMap.set(receiver, value);
    return value;
}


/***/ }),
/* 22 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "ElementSymbol", function() { return /* binding */ ElementSymbol; });
__webpack_require__.d(__webpack_exports__, "getElementFromAtomicNumber", function() { return /* binding */ getElementFromAtomicNumber; });
__webpack_require__.d(__webpack_exports__, "PolymerTypeAtomRoleId", function() { return /* binding */ PolymerTypeAtomRoleId; });
__webpack_require__.d(__webpack_exports__, "ProteinBackboneAtoms", function() { return /* binding */ ProteinBackboneAtoms; });
__webpack_require__.d(__webpack_exports__, "NucleicBackboneAtoms", function() { return /* binding */ NucleicBackboneAtoms; });
__webpack_require__.d(__webpack_exports__, "DProteinComponentTypeNames", function() { return /* binding */ DProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "LProteinComponentTypeNames", function() { return /* binding */ LProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "GammaProteinComponentTypeNames", function() { return /* binding */ GammaProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "BetaProteinComponentTypeNames", function() { return /* binding */ BetaProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "ProteinTerminusComponentTypeNames", function() { return /* binding */ ProteinTerminusComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "OtherProteinComponentTypeNames", function() { return /* binding */ OtherProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "ProteinComponentTypeNames", function() { return /* binding */ ProteinComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "DNAComponentTypeNames", function() { return /* binding */ DNAComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "RNAComponentTypeNames", function() { return /* binding */ RNAComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "SaccharideComponentTypeNames", function() { return /* binding */ SaccharideComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "OtherComponentTypeNames", function() { return /* binding */ OtherComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "IonComponentTypeNames", function() { return /* binding */ IonComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "LipidComponentTypeNames", function() { return /* binding */ LipidComponentTypeNames; });
__webpack_require__.d(__webpack_exports__, "WaterNames", function() { return /* binding */ WaterNames; });
__webpack_require__.d(__webpack_exports__, "AminoAcidNamesL", function() { return /* binding */ AminoAcidNamesL; });
__webpack_require__.d(__webpack_exports__, "AminoAcidNamesD", function() { return /* binding */ AminoAcidNamesD; });
__webpack_require__.d(__webpack_exports__, "AminoAcidNames", function() { return /* binding */ AminoAcidNames; });
__webpack_require__.d(__webpack_exports__, "RnaBaseNames", function() { return /* binding */ RnaBaseNames; });
__webpack_require__.d(__webpack_exports__, "DnaBaseNames", function() { return /* binding */ DnaBaseNames; });
__webpack_require__.d(__webpack_exports__, "PeptideBaseNames", function() { return /* binding */ PeptideBaseNames; });
__webpack_require__.d(__webpack_exports__, "PurineBaseNames", function() { return /* binding */ PurineBaseNames; });
__webpack_require__.d(__webpack_exports__, "PyrimidineBaseNames", function() { return /* binding */ PyrimidineBaseNames; });
__webpack_require__.d(__webpack_exports__, "BaseNames", function() { return /* binding */ BaseNames; });
__webpack_require__.d(__webpack_exports__, "isPurineBase", function() { return /* binding */ isPurineBase; });
__webpack_require__.d(__webpack_exports__, "isPyrimidineBase", function() { return /* binding */ isPyrimidineBase; });
__webpack_require__.d(__webpack_exports__, "PolymerNames", function() { return /* binding */ PolymerNames; });
__webpack_require__.d(__webpack_exports__, "getMoleculeType", function() { return /* binding */ getMoleculeType; });
__webpack_require__.d(__webpack_exports__, "getPolymerType", function() { return /* binding */ getPolymerType; });
__webpack_require__.d(__webpack_exports__, "getComponentType", function() { return /* binding */ getComponentType; });
__webpack_require__.d(__webpack_exports__, "getDefaultChemicalComponent", function() { return /* binding */ getDefaultChemicalComponent; });
__webpack_require__.d(__webpack_exports__, "getEntityType", function() { return /* binding */ getEntityType; });
__webpack_require__.d(__webpack_exports__, "getEntitySubtype", function() { return /* binding */ getEntitySubtype; });
__webpack_require__.d(__webpack_exports__, "isPolymer", function() { return /* binding */ isPolymer; });
__webpack_require__.d(__webpack_exports__, "isNucleic", function() { return /* binding */ isNucleic; });
__webpack_require__.d(__webpack_exports__, "isProtein", function() { return /* binding */ isProtein; });
__webpack_require__.d(__webpack_exports__, "IonNames", function() { return /* binding */ IonNames; });
__webpack_require__.d(__webpack_exports__, "SecondaryStructureType", function() { return /* binding */ types_SecondaryStructureType; });
__webpack_require__.d(__webpack_exports__, "MaxAsa", function() { return /* binding */ MaxAsa; });
__webpack_require__.d(__webpack_exports__, "DefaultMaxAsa", function() { return /* binding */ DefaultMaxAsa; });
__webpack_require__.d(__webpack_exports__, "BondType", function() { return /* binding */ types_BondType; });
__webpack_require__.d(__webpack_exports__, "ResidueHydrophobicity", function() { return /* binding */ ResidueHydrophobicity; });
__webpack_require__.d(__webpack_exports__, "DefaultResidueHydrophobicity", function() { return /* binding */ DefaultResidueHydrophobicity; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/bit-flags.js
var bit_flags = __webpack_require__(207);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/constants.js
var constants = __webpack_require__(178);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var set = __webpack_require__(90);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types/lipids.js
/**
* Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
*
* Code-generated lipid params file. Names extracted from Martini FF lipids itp.
*
* @author molstar/lipid-params cli
*/
var LipidNames = new Set(['DAPC', 'DBPC', 'DFPC', 'DGPC', 'DIPC', 'DLPC', 'DNPC', 'DOPC', 'DPPC', 'DRPC', 'DTPC', 'DVPC', 'DXPC', 'DYPC', 'LPPC', 'PAPC', 'PEPC', 'PGPC', 'PIPC', 'POPC', 'PRPC', 'PUPC', 'DAPE', 'DBPE', 'DFPE', 'DGPE', 'DIPE', 'DLPE', 'DNPE', 'DOPE', 'DPPE', 'DRPE', 'DTPE', 'DUPE', 'DVPE', 'DXPE', 'DYPE', 'LPPE', 'PAPE', 'PGPE', 'PIPE', 'POPE', 'PQPE', 'PRPE', 'PUPE', 'DAPS', 'DBPS', 'DFPS', 'DGPS', 'DIPS', 'DLPS', 'DNPS', 'DOPS', 'DPPS', 'DRPS', 'DTPS', 'DUPS', 'DVPS', 'DXPS', 'DYPS', 'LPPS', 'PAPS', 'PGPS', 'PIPS', 'POPS', 'PQPS', 'PRPS', 'PUPS', 'DAPG', 'DBPG', 'DFPG', 'DGPG', 'DIPG', 'DLPG', 'DNPG', 'DOPG', 'DPPG', 'DRPG', 'DTPG', 'DVPG', 'DXPG', 'DYPG', 'LPPG', 'PAPG', 'PGPG', 'PIPG', 'POPG', 'PRPG', 'DAPA', 'DBPA', 'DFPA', 'DGPA', 'DIPA', 'DLPA', 'DNPA', 'DOPA', 'DPPA', 'DRPA', 'DTPA', 'DVPA', 'DXPA', 'DYPA', 'LPPA', 'PAPA', 'PGPA', 'PIPA', 'POPA', 'PRPA', 'PUPA', 'DPP', 'DPPI', 'PAPI', 'PIPI', 'POP', 'POPI', 'PUPI', 'PVP', 'PVPI', 'PADG', 'PIDG', 'PODG', 'PUDG', 'PVDG', 'APC', 'CPC', 'IPC', 'LPC', 'OPC', 'PPC', 'TPC', 'UPC', 'VPC', 'BNSM', 'DBSM', 'DPSM', 'DXSM', 'PGSM', 'PNSM', 'POSM', 'PVSM', 'XNSM', 'DPCE', 'DXCE', 'PNCE', 'XNCE']);
//# sourceMappingURL=lipids.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var _a;




var _esCache = (function () {
    var cache = Object.create(null);
    var letters = [];
    for (var i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++)
        letters[letters.length] = String.fromCharCode(i);
    for (var i = 'a'.charCodeAt(0); i <= 'z'.charCodeAt(0); i++)
        letters[letters.length] = String.fromCharCode(i);
    for (var i = '0'.charCodeAt(0); i <= '9'.charCodeAt(0); i++)
        letters[letters.length] = String.fromCharCode(i);
    for (var _i = 0, letters_1 = letters; _i < letters_1.length; _i++) {
        var k = letters_1[_i];
        cache[k] = k.toUpperCase();
        for (var _a = 0, letters_2 = letters; _a < letters_2.length; _a++) {
            var l = letters_2[_a];
            cache[k + l] = (k + l).toUpperCase();
            for (var _b = 0, letters_3 = letters; _b < letters_3.length; _b++) {
                var m = letters_3[_b];
                cache[k + l + m] = (k + l + m).toUpperCase();
            }
        }
    }
    return cache;
}());
function ElementSymbol(s) {
    return _esCache[s] || s.toUpperCase();
}
var _elementByAtomicNumber = new Map([[1, 'H'], [2, 'He'], [3, 'Li'], [4, 'Be'], [5, 'B'], [6, 'C'], [7, 'N'], [8, 'O'], [9, 'F'], [10, 'Ne'], [11, 'Na'], [12, 'Mg'], [13, 'Al'], [14, 'Si'], [15, 'P'], [16, 'S'], [17, 'Cl'], [18, 'Ar'], [19, 'K'], [20, 'Ca'], [21, 'Sc'], [22, 'Ti'], [23, 'V'], [24, 'Cr'], [25, 'Mn'], [26, 'Fe'], [27, 'Co'], [28, 'Ni'], [29, 'Cu'], [30, 'Zn'], [31, 'Ga'], [32, 'Ge'], [33, 'As'], [34, 'Se'], [35, 'Br'], [36, 'Kr'], [37, 'Rb'], [38, 'Sr'], [39, 'Y'], [40, 'Zr'], [41, 'Nb'], [42, 'Mo'], [43, 'Tc'], [44, 'Ru'], [45, 'Rh'], [46, 'Pd'], [47, 'Ag'], [48, 'Cd'], [49, 'In'], [50, 'Sn'], [51, 'Sb'], [52, 'Te'], [53, 'I'], [54, 'Xe'], [55, 'Cs'], [56, 'Ba'], [57, 'La'], [58, 'Ce'], [59, 'Pr'], [60, 'Nd'], [61, 'Pm'], [62, 'Sm'], [63, 'Eu'], [64, 'Gd'], [65, 'Tb'], [66, 'Dy'], [67, 'Ho'], [68, 'Er'], [69, 'Tm'], [70, 'Yb'], [71, 'Lu'], [72, 'Hf'], [73, 'Ta'], [74, 'W'], [75, 'Re'], [76, 'Os'], [77, 'Ir'], [78, 'Pt'], [79, 'Au'], [80, 'Hg'], [81, 'Tl'], [82, 'Pb'], [83, 'Bi'], [84, 'Po'], [85, 'At'], [86, 'Rn'], [87, 'Fr'], [88, 'Ra'], [89, 'Ac'], [90, 'Th'], [91, 'Pa'], [92, 'U'], [93, 'Np'], [94, 'Pu'], [95, 'Am'], [96, 'Cm'], [97, 'Bk'], [98, 'Cf'], [99, 'Es'], [100, 'Fm'], [101, 'Md'], [102, 'No'], [103, 'Lr'], [104, 'Rf'], [105, 'Db'], [106, 'Sg'], [107, 'Bh'], [108, 'Hs'], [109, 'Mt'], [110, 'Ds'], [111, 'Rg'], [112, 'Cn'], [113, 'Uut'], [114, 'Fl'], [115, 'Uup'], [116, 'Lv'], [117, 'Uus'], [118, 'Uuo']]
    .map(function (e) { return [e[0], ElementSymbol(e[1])]; }));
function getElementFromAtomicNumber(n) {
    if (_elementByAtomicNumber.has(n))
        return _elementByAtomicNumber.get(n);
    return ElementSymbol('H');
}
var PolymerTypeAtomRoleId = (_a = {},
    _a[0 /* NA */] = {
        trace: new Set(),
        directionFrom: new Set(),
        directionTo: new Set(),
        backboneStart: new Set(),
        backboneEnd: new Set(),
        coarseBackbone: new Set()
    },
    _a[1 /* Protein */] = {
        trace: new Set(['CA']),
        directionFrom: new Set(['C']),
        directionTo: new Set(['O', 'OC1', 'O1', 'OX1', 'OXT']),
        backboneStart: new Set(['N']),
        backboneEnd: new Set(['C']),
        // CA1 is used e.g. in GFP chromophores
        // BB is often used for coarse grained models
        coarseBackbone: new Set(['CA', 'BB', 'CA1'])
    },
    _a[2 /* GammaProtein */] = {
        trace: new Set(['CA']),
        directionFrom: new Set(['C']),
        directionTo: new Set(['O']),
        backboneStart: new Set(['N']),
        backboneEnd: new Set(['CD']),
        coarseBackbone: new Set(['CA'])
    },
    _a[3 /* BetaProtein */] = {
        trace: new Set(['CA']),
        directionFrom: new Set(['C']),
        directionTo: new Set(['O']),
        backboneStart: new Set(['N']),
        backboneEnd: new Set(['CG']),
        coarseBackbone: new Set(['CA'])
    },
    _a[4 /* RNA */] = {
        trace: new Set(['O3\'', 'O3*']),
        directionFrom: new Set(['C4\'', 'C4*']),
        directionTo: new Set(['C3\'', 'C3*']),
        backboneStart: new Set(['P']),
        backboneEnd: new Set(['O3\'', 'O3*']),
        coarseBackbone: new Set(['P'])
    },
    _a[5 /* DNA */] = {
        trace: new Set(['O3\'', 'O3*']),
        directionFrom: new Set(['C3\'', 'C3*']),
        directionTo: new Set(['C1\'', 'C1*']),
        backboneStart: new Set(['P']),
        backboneEnd: new Set(['O3\'', 'O3*']),
        coarseBackbone: new Set(['P'])
    },
    _a[6 /* PNA */] = {
        trace: new Set(['N4\'', 'N4*']),
        directionFrom: new Set(['N4\'', 'N4*']),
        directionTo: new Set(['C7\'', 'C7*']),
        backboneStart: new Set(['N1\'', 'N1*']),
        backboneEnd: new Set(['C\'', 'C*']),
        coarseBackbone: new Set(['P'])
    },
    _a);
var ProteinBackboneAtoms = new Set([
    'CA', 'C', 'N', 'O',
    'O1', 'O2', 'OC1', 'OC2', 'OT1', 'OT2', 'OX1', 'OXT',
    'H', 'H1', 'H2', 'H3', 'HA', 'HN', 'HXT',
    'BB'
]);
var NucleicBackboneAtoms = new Set([
    'P', 'OP1', 'OP2', 'HOP2', 'HOP3',
    'O2\'', 'O3\'', 'O4\'', 'O5\'', 'C1\'', 'C2\'', 'C3\'', 'C4\'', 'C5\'',
    'H1\'', 'H2\'', 'H2\'\'', 'HO2\'', 'H3\'', 'H4\'', 'H5\'', 'H5\'\'', 'HO3\'', 'HO5\'',
    'O2*', 'O3*', 'O4*', 'O5*', 'C1*', 'C2*', 'C3*', 'C4*', 'C5*'
]);
/** Chemical component type names for D-linked protein */
var DProteinComponentTypeNames = new Set([
    'D-PEPTIDE LINKING', 'D-PEPTIDE NH3 AMINO TERMINUS',
    'D-PEPTIDE COOH CARBOXY TERMINUS', 'D-GAMMA-PEPTIDE, C-DELTA LINKING',
    'D-BETA-PEPTIDE, C-GAMMA LINKING'
]);
/** Chemical component type names for L-linked protein */
var LProteinComponentTypeNames = new Set([
    'L-PEPTIDE LINKING', 'L-PEPTIDE NH3 AMINO TERMINUS',
    'L-PEPTIDE COOH CARBOXY TERMINUS', 'L-GAMMA-PEPTIDE, C-DELTA LINKING',
    'L-BETA-PEPTIDE, C-GAMMA LINKING'
]);
/** Chemical component type names for gamma protein, overlaps with D/L-linked */
var GammaProteinComponentTypeNames = new Set([
    'D-GAMMA-PEPTIDE, C-DELTA LINKING', 'L-GAMMA-PEPTIDE, C-DELTA LINKING'
]);
/** Chemical component type names for beta protein, overlaps with D/L-linked */
var BetaProteinComponentTypeNames = new Set([
    'D-BETA-PEPTIDE, C-GAMMA LINKING', 'L-BETA-PEPTIDE, C-GAMMA LINKING'
]);
/** Chemical component type names for protein termini, overlaps with D/L-linked */
var ProteinTerminusComponentTypeNames = new Set([
    'D-PEPTIDE NH3 AMINO TERMINUS', 'D-PEPTIDE COOH CARBOXY TERMINUS',
    'L-PEPTIDE NH3 AMINO TERMINUS', 'L-PEPTIDE COOH CARBOXY TERMINUS'
]);
/** Chemical component type names for pepdite-like protein */
var OtherProteinComponentTypeNames = new Set([
    'PEPTIDE LINKING', 'PEPTIDE-LIKE',
]);
/** Chemical component type names for protein */
var ProteinComponentTypeNames = set["a" /* SetUtils */].unionMany(DProteinComponentTypeNames, LProteinComponentTypeNames, OtherProteinComponentTypeNames);
/** Chemical component type names for DNA */
var DNAComponentTypeNames = new Set([
    'DNA LINKING', 'L-DNA LINKING', 'DNA OH 5 PRIME TERMINUS', 'DNA OH 3 PRIME TERMINUS',
]);
/** Chemical component type names for RNA */
var RNAComponentTypeNames = new Set([
    'RNA LINKING', 'L-RNA LINKING', 'RNA OH 5 PRIME TERMINUS', 'RNA OH 3 PRIME TERMINUS',
]);
/** Chemical component type names for saccharide */
var SaccharideComponentTypeNames = new Set([
    'D-SACCHARIDE, BETA LINKING', 'L-SACCHARIDE, BETA LINKING',
    'D-SACCHARIDE, ALPHA LINKING', 'L-SACCHARIDE, ALPHA LINKING',
    'L-SACCHARIDE', 'D-SACCHARIDE', 'SACCHARIDE',
    // the following four are marked to be deprecated in the mmCIF dictionary
    'D-SACCHARIDE 1,4 AND 1,4 LINKING', 'L-SACCHARIDE 1,4 AND 1,4 LINKING',
    'D-SACCHARIDE 1,4 AND 1,6 LINKING', 'L-SACCHARIDE 1,4 AND 1,6 LINKING',
]);
/** Chemical component type names for other */
var OtherComponentTypeNames = new Set([
    'NON-POLYMER', 'OTHER'
]);
/** Chemical component type names for ion (extension to mmcif) */
var IonComponentTypeNames = new Set([
    'ION'
]);
/** Chemical component type names for lipid (extension to mmcif) */
var LipidComponentTypeNames = new Set([
    'LIPID'
]);
/** Common names for water molecules */
var WaterNames = new Set([
    'SOL', 'WAT', 'HOH', 'H2O', 'W', 'DOD', 'D3O', 'TIP', 'TIP3', 'TIP4', 'SPC'
]);
var AminoAcidNamesL = new Set([
    'HIS', 'ARG', 'LYS', 'ILE', 'PHE', 'LEU', 'TRP', 'ALA', 'MET', 'PRO', 'CYS',
    'ASN', 'VAL', 'GLY', 'SER', 'GLN', 'TYR', 'ASP', 'GLU', 'THR', 'SEC', 'PYL',
    'UNK' // unknown amino acid from CCD
]);
var AminoAcidNamesD = new Set([
    'DAL',
    'DAR',
    'DSG',
    'DAS',
    'DCY',
    'DGL',
    'DGN',
    'DHI',
    'DIL',
    'DLE',
    'DLY',
    'MED',
    'DPN',
    'DPR',
    'DSN',
    'DTH',
    'DTR',
    'DTY',
    'DVA',
    'DNE' // D-NORLEUCINE
    // ???  // D-SELENOCYSTEINE
]);
var AminoAcidNames = set["a" /* SetUtils */].unionMany(AminoAcidNamesL, AminoAcidNamesD);
var RnaBaseNames = new Set([
    'A', 'C', 'T', 'G', 'I', 'U',
    'N' // unknown RNA base from CCD
]);
var DnaBaseNames = new Set([
    'DA', 'DC', 'DT', 'DG', 'DI', 'DU',
    'DN' // unknown DNA base from CCD
]);
var PeptideBaseNames = new Set(['APN', 'CPN', 'TPN', 'GPN']);
var PurineBaseNames = new Set(['A', 'G', 'I', 'DA', 'DG', 'DI', 'APN', 'GPN']);
var PyrimidineBaseNames = new Set(['C', 'T', 'U', 'DC', 'DT', 'DU', 'CPN', 'TPN']);
var BaseNames = set["a" /* SetUtils */].unionMany(RnaBaseNames, DnaBaseNames, PeptideBaseNames);
var isPurineBase = function (compId) { return PurineBaseNames.has(compId.toUpperCase()); };
var isPyrimidineBase = function (compId) { return PyrimidineBaseNames.has(compId.toUpperCase()); };
var PolymerNames = set["a" /* SetUtils */].unionMany(AminoAcidNames, BaseNames);
/** get the molecule type from component type and id */
function getMoleculeType(compType, compId) {
    compType = compType.toUpperCase();
    compId = compId.toUpperCase();
    if (PeptideBaseNames.has(compId)) {
        return 8 /* PNA */;
    }
    else if (ProteinComponentTypeNames.has(compType)) {
        return 5 /* Protein */;
    }
    else if (RNAComponentTypeNames.has(compType)) {
        return 6 /* RNA */;
    }
    else if (DNAComponentTypeNames.has(compType)) {
        return 7 /* DNA */;
    }
    else if (SaccharideComponentTypeNames.has(compType)) {
        return 9 /* Saccharide */;
    }
    else if (WaterNames.has(compId)) {
        return 2 /* Water */;
    }
    else if (IonNames.has(compId)) {
        return 3 /* Ion */;
    }
    else if (LipidNames.has(compId)) {
        return 4 /* Lipid */;
    }
    else if (OtherComponentTypeNames.has(compType)) {
        if (constants["c" /* SaccharideCompIdMap */].has(compId)) {
            // trust our saccharide table more than given 'non-polymer' or 'other' component type
            return 9 /* Saccharide */;
        }
        else {
            return 1 /* Other */;
        }
    }
    else {
        return 0 /* Unknown */;
    }
}
function getPolymerType(compType, molType) {
    compType = compType.toUpperCase();
    if (molType === 5 /* Protein */) {
        if (GammaProteinComponentTypeNames.has(compType)) {
            return 2 /* GammaProtein */;
        }
        else if (BetaProteinComponentTypeNames.has(compType)) {
            return 3 /* BetaProtein */;
        }
        else if (ProteinTerminusComponentTypeNames.has(compType)) {
            return 0 /* NA */;
        }
        else {
            return 1 /* Protein */;
        }
    }
    else if (molType === 6 /* RNA */) {
        return 4 /* RNA */;
    }
    else if (molType === 7 /* DNA */) {
        return 5 /* DNA */;
    }
    else if (molType === 8 /* PNA */) {
        return 6 /* PNA */;
    }
    else {
        return 0 /* NA */;
    }
}
function getComponentType(compId) {
    compId = compId.toUpperCase();
    if (AminoAcidNames.has(compId)) {
        return 'peptide linking';
    }
    else if (RnaBaseNames.has(compId)) {
        return 'RNA linking';
    }
    else if (DnaBaseNames.has(compId)) {
        return 'DNA linking';
    }
    else if (constants["c" /* SaccharideCompIdMap */].has(compId)) {
        return 'saccharide';
    }
    else {
        return 'other';
    }
}
function getDefaultChemicalComponent(compId) {
    // TODO: this is to make the chem_comp_type property work if chem_comp category is not present.
    // should we try to set the formula etc better?
    return {
        formula: '',
        formula_weight: 0,
        id: compId,
        name: compId,
        mon_nstd_flag: PolymerNames.has(compId) ? 'y' : 'n',
        pdbx_synonyms: [],
        type: getComponentType(compId)
    };
}
function getEntityType(compId) {
    compId = compId.toUpperCase();
    if (WaterNames.has(compId)) {
        return 'water';
    }
    else if (PolymerNames.has(compId)) {
        return 'polymer';
    }
    else if (constants["c" /* SaccharideCompIdMap */].has(compId)) {
        return 'branched';
    }
    else {
        return 'non-polymer';
    }
}
function getEntitySubtype(compId, compType) {
    compId = compId.toUpperCase();
    compType = compType.toUpperCase();
    if (LProteinComponentTypeNames.has(compType)) {
        return 'polypeptide(L)';
    }
    else if (DProteinComponentTypeNames.has(compType)) {
        return 'polypeptide(D)';
    }
    else if (RNAComponentTypeNames.has(compType)) {
        return 'polyribonucleotide';
    }
    else if (DNAComponentTypeNames.has(compType)) {
        return 'polydeoxyribonucleotide';
    }
    else if (SaccharideComponentTypeNames.has(compType)) {
        return 'oligosaccharide';
    }
    else if (constants["c" /* SaccharideCompIdMap */].has(compId)) {
        return 'oligosaccharide';
    }
    else if (PeptideBaseNames.has(compId)) {
        return 'peptide nucleic acid';
    }
    else if (AminoAcidNamesL.has(compId)) {
        return 'polypeptide(L)';
    }
    else if (AminoAcidNamesD.has(compId)) {
        return 'polypeptide(D)';
    }
    else if (RnaBaseNames.has(compId)) {
        return 'polyribonucleotide';
    }
    else if (DnaBaseNames.has(compId)) {
        return 'polydeoxyribonucleotide';
    }
    else if (IonComponentTypeNames.has(compType) || IonNames.has(compId)) {
        return 'ion';
    }
    else if (LipidComponentTypeNames.has(compType) || LipidNames.has(compId)) {
        return 'lipid';
    }
    else {
        return 'other';
    }
}
function isPolymer(moleculeType) {
    return isNucleic(moleculeType) || isProtein(moleculeType);
}
function isNucleic(moleculeType) {
    return moleculeType === 7 /* DNA */ || moleculeType === 6 /* RNA */ || moleculeType === 8 /* PNA */;
}
function isProtein(moleculeType) {
    return moleculeType === 5 /* Protein */;
}
/**
 * TODO write script that read CCD and outputs list of ion names
 *
 * all chemical components with the word "ion" in their name, Sep 2016
 *
 * SET SESSION group_concat_max_len = 1000000;
 * SELECT GROUP_CONCAT(id_ ORDER BY id_ ASC SEPARATOR '", "') from
 * (
 *     SELECT count(obj_id) as c, id_
 *     FROM pdb.chem_comp WHERE name LIKE "% ION%"
 *     GROUP BY id_
 * ) AS t1;
 */
var IonNames = new Set([
    '118', '119', '1AL', '1CU', '2FK', '2HP', '2OF', '3CO',
    '3MT', '3NI', '3OF', '3P8', '4MO', '4PU', '543', '6MO', 'ACT', 'AG', 'AL',
    'ALF', 'AM', 'ATH', 'AU', 'AU3', 'AUC', 'AZI', 'BA', 'BCT', 'BEF', 'BF4', 'BO4',
    'BR', 'BS3', 'BSY', 'CA', 'CAC', 'CD', 'CD1', 'CD3', 'CD5', 'CE', 'CHT', 'CL',
    'CO', 'CO3', 'CO5', 'CON', 'CR', 'CS', 'CSB', 'CU', 'CU1', 'CU3', 'CUA', 'CUZ',
    'CYN', 'DME', 'DMI', 'DSC', 'DTI', 'DY', 'E4N', 'EDR', 'EMC', 'ER3', 'EU',
    'EU3', 'F', 'FE', 'FE2', 'FPO', 'GA', 'GD3', 'GEP', 'HAI', 'HG', 'HGC', 'IN',
    'IOD', 'IR', 'IR3', 'IRI', 'IUM', 'K', 'KO4', 'LA', 'LCO', 'LCP', 'LI', 'LU',
    'MAC', 'MG', 'MH2', 'MH3', 'MLI', 'MLT', 'MMC', 'MN', 'MN3', 'MN5', 'MN6',
    'MO1', 'MO2', 'MO3', 'MO4', 'MO5', 'MO6', 'MOO', 'MOS', 'MOW', 'MW1', 'MW2',
    'MW3', 'NA', 'NA2', 'NA5', 'NA6', 'NAO', 'NAW', 'NCO', 'NET', 'NH4', 'NI',
    'NI1', 'NI2', 'NI3', 'NO2', 'NO3', 'NRU', 'O4M', 'OAA', 'OC1', 'OC2', 'OC3',
    'OC4', 'OC5', 'OC6', 'OC7', 'OC8', 'OCL', 'OCM', 'OCN', 'OCO', 'OF1', 'OF2',
    'OF3', 'OH', 'OS', 'OS4', 'OXL', 'PB', 'PBM', 'PD', 'PDV', 'PER', 'PI', 'PO3',
    'PO4', 'PR', 'PT', 'PT4', 'PTN', 'RB', 'RH3', 'RHD', 'RU', 'SB', 'SCN', 'SE4',
    'SEK', 'SM', 'SMO', 'SO3', 'SO4', 'SR', 'T1A', 'TB', 'TBA', 'TCN', 'TEA', 'TH',
    'THE', 'TL', 'TMA', 'TRA', 'UNX', 'V', 'VN3', 'VO4', 'W', 'WO5', 'Y1', 'YB',
    'YB2', 'YH', 'YT3', 'ZCM', 'ZN', 'ZN2', 'ZN3', 'ZNO', 'ZO3',
    // additional ion names
    'OHX'
]);
var types_SecondaryStructureType;
(function (SecondaryStructureType) {
    SecondaryStructureType.is = bit_flags["a" /* default */].has;
    SecondaryStructureType.create = bit_flags["a" /* default */].create;
    SecondaryStructureType.SecondaryStructureMmcif = {
        HELX_LH_27_P: 2 /* Helix */ | 32 /* LeftHanded */ | 1024 /* Helix27 */,
        HELX_LH_3T_P: 2 /* Helix */ | 32 /* LeftHanded */ | 2048 /* Helix3Ten */,
        HELX_LH_AL_P: 2 /* Helix */ | 32 /* LeftHanded */ | 4096 /* HelixAlpha */,
        HELX_LH_A_N: 1 /* DoubleHelix */ | 32 /* LeftHanded */ | 524288 /* DoubleHelixA */,
        HELX_LH_B_N: 1 /* DoubleHelix */ | 32 /* LeftHanded */ | 1048576 /* DoubleHelixB */,
        HELX_LH_GA_P: 2 /* Helix */ | 32 /* LeftHanded */ | 8192 /* HelixGamma */,
        HELX_LH_N: 1 /* DoubleHelix */ | 32 /* LeftHanded */,
        HELX_LH_OM_P: 2 /* Helix */ | 32 /* LeftHanded */ | 16384 /* HelixOmega */,
        HELX_LH_OT_N: 1 /* DoubleHelix */ | 32 /* LeftHanded */ | 131072 /* DoubleHelixOther */,
        HELX_LH_OT_P: 2 /* Helix */ | 32 /* LeftHanded */ | 512 /* HelixOther */,
        HELX_LH_P: 2 /* Helix */ | 32 /* LeftHanded */,
        HELX_LH_PI_P: 2 /* Helix */ | 32 /* LeftHanded */ | 32768 /* HelixPi */,
        HELX_LH_PP_P: 2 /* Helix */ | 32 /* LeftHanded */ | 65536 /* HelixPolyproline */,
        HELX_LH_Z_N: 1 /* DoubleHelix */ | 32 /* LeftHanded */ | 262144 /* DoubleHelixZ */,
        HELX_N: 1 /* DoubleHelix */,
        HELX_OT_N: 1 /* DoubleHelix */,
        HELX_OT_P: 2 /* Helix */,
        HELX_P: 2 /* Helix */,
        HELX_RH_27_P: 2 /* Helix */ | 64 /* RightHanded */ | 1024 /* Helix27 */,
        HELX_RH_3T_P: 2 /* Helix */ | 64 /* RightHanded */ | 2048 /* Helix3Ten */,
        HELX_RH_AL_P: 2 /* Helix */ | 64 /* RightHanded */ | 4096 /* HelixAlpha */,
        HELX_RH_A_N: 1 /* DoubleHelix */ | 64 /* RightHanded */ | 524288 /* DoubleHelixA */,
        HELX_RH_B_N: 1 /* DoubleHelix */ | 64 /* RightHanded */ | 1048576 /* DoubleHelixB */,
        HELX_RH_GA_P: 2 /* Helix */ | 64 /* RightHanded */ | 8192 /* HelixGamma */,
        HELX_RH_N: 1 /* DoubleHelix */ | 64 /* RightHanded */,
        HELX_RH_OM_P: 2 /* Helix */ | 64 /* RightHanded */ | 16384 /* HelixOmega */,
        HELX_RH_OT_N: 1 /* DoubleHelix */ | 64 /* RightHanded */ | 131072 /* DoubleHelixOther */,
        HELX_RH_OT_P: 2 /* Helix */ | 64 /* RightHanded */ | 512 /* HelixOther */,
        HELX_RH_P: 2 /* Helix */ | 64 /* RightHanded */,
        HELX_RH_PI_P: 2 /* Helix */ | 64 /* RightHanded */ | 32768 /* HelixPi */,
        HELX_RH_PP_P: 2 /* Helix */ | 64 /* RightHanded */ | 65536 /* HelixPolyproline */,
        HELX_RH_Z_N: 1 /* DoubleHelix */ | 64 /* RightHanded */ | 262144 /* DoubleHelixZ */,
        STRN: 4 /* Beta */ | 4194304 /* BetaStrand */,
        TURN_OT_P: 16 /* Turn */ | 33554432 /* TurnOther */,
        TURN_P: 16 /* Turn */,
        TURN_TY1P_P: 16 /* Turn */ | 256 /* InverseTurn */ | 67108864 /* Turn1 */,
        TURN_TY1_P: 16 /* Turn */ | 128 /* ClassicTurn */ | 67108864 /* Turn1 */,
        TURN_TY2P_P: 16 /* Turn */ | 256 /* InverseTurn */ | 134217728 /* Turn2 */,
        TURN_TY2_P: 16 /* Turn */ | 128 /* ClassicTurn */ | 134217728 /* Turn2 */,
        TURN_TY3P_P: 16 /* Turn */ | 256 /* InverseTurn */ | 268435456 /* Turn3 */,
        TURN_TY3_P: 16 /* Turn */ | 128 /* ClassicTurn */ | 268435456 /* Turn3 */,
    };
    SecondaryStructureType.SecondaryStructurePdb = {
        1: 2 /* Helix */ | 64 /* RightHanded */ | 4096 /* HelixAlpha */,
        2: 2 /* Helix */ | 64 /* RightHanded */ | 16384 /* HelixOmega */,
        3: 2 /* Helix */ | 64 /* RightHanded */ | 32768 /* HelixPi */,
        4: 2 /* Helix */ | 64 /* RightHanded */ | 8192 /* HelixGamma */,
        5: 2 /* Helix */ | 64 /* RightHanded */ | 2048 /* Helix3Ten */,
        6: 2 /* Helix */ | 32 /* LeftHanded */ | 4096 /* HelixAlpha */,
        7: 2 /* Helix */ | 32 /* LeftHanded */ | 16384 /* HelixOmega */,
        8: 2 /* Helix */ | 32 /* LeftHanded */ | 8192 /* HelixGamma */,
        9: 2 /* Helix */ | 1024 /* Helix27 */,
        10: 2 /* Helix */ | 65536 /* HelixPolyproline */,
    };
    SecondaryStructureType.SecondaryStructureStride = {
        H: 2 /* Helix */ | 4096 /* HelixAlpha */,
        G: 2 /* Helix */ | 2048 /* Helix3Ten */,
        I: 2 /* Helix */ | 32768 /* HelixPi */,
        E: 4 /* Beta */ | 8388608 /* BetaSheet */,
        B: 4 /* Beta */ | 4194304 /* BetaStrand */,
        T: 16 /* Turn */,
        C: 536870912 /* NA */,
    };
    SecondaryStructureType.SecondaryStructureDssp = {
        H: 2 /* Helix */ | 4096 /* HelixAlpha */,
        B: 4 /* Beta */ | 4194304 /* BetaStrand */,
        E: 4 /* Beta */ | 8388608 /* BetaSheet */,
        G: 2 /* Helix */ | 2048 /* Helix3Ten */,
        I: 2 /* Helix */ | 32768 /* HelixPi */,
        T: 16 /* Turn */,
        S: 8 /* Bend */,
    };
})(types_SecondaryStructureType || (types_SecondaryStructureType = {}));
/** Maximum accessible surface area observed for amino acids. Taken from: http://dx.doi.org/10.1371/journal.pone.0080635 */
var MaxAsa = {
    'ALA': 121.0,
    'ARG': 265.0,
    'ASN': 187.0,
    'ASP': 187.0,
    'CYS': 148.0,
    'GLU': 214.0,
    'GLN': 214.0,
    'GLY': 97.0,
    'HIS': 216.0,
    'ILE': 195.0,
    'LEU': 191.0,
    'LYS': 230.0,
    'MET': 203.0,
    'PHE': 228.0,
    'PRO': 154.0,
    'SER': 143.0,
    'THR': 163.0,
    'TRP': 264.0,
    'TYR': 255.0,
    'VAL': 165.0
};
var DefaultMaxAsa = 121.0;
var types_BondType;
(function (BondType) {
    BondType.is = bit_flags["a" /* default */].has;
    function create(flags) {
        return bit_flags["a" /* default */].create(flags);
    }
    BondType.create = create;
    function isCovalent(flags) {
        return (flags & 1 /* Covalent */) !== 0;
    }
    BondType.isCovalent = isCovalent;
    BondType.Names = {
        'covalent': 1 /* Covalent */,
        'metal-coordination': 2 /* MetallicCoordination */,
        'hydrogen-bond': 4 /* HydrogenBond */,
        'disulfide': 4 /* HydrogenBond */,
        'aromatic': 4 /* HydrogenBond */,
        'computed': 4 /* HydrogenBond */,
    };
    function isName(name) {
        return name in BondType.Names;
    }
    BondType.isName = isName;
    function fromName(name) {
        switch (name) {
            case 'covalent': return 1 /* Covalent */;
            case 'metal-coordination': return 2 /* MetallicCoordination */;
            case 'hydrogen-bond': return 4 /* HydrogenBond */;
            case 'disulfide': return 8 /* Disulfide */;
            case 'aromatic': return 16 /* Aromatic */;
            case 'computed': return 32 /* Computed */;
        }
    }
    BondType.fromName = fromName;
    function fromNames(names) {
        var f = 0 /* None */;
        for (var i = 0, il = names.length; i < il; ++i) {
            f |= fromName(names[i]);
        }
        return f;
    }
    BondType.fromNames = fromNames;
})(types_BondType || (types_BondType = {}));
/**
 * "Experimentally determined hydrophobicity scale for proteins at membrane interfaces"
 * by Wimely and White (doi:10.1038/nsb1096-842)
 * http://blanco.biomol.uci.edu/Whole_residue_HFscales.txt
 * https://www.nature.com/articles/nsb1096-842
 */
var ResidueHydrophobicity = {
    // AA  DGwif   DGwoct  Oct-IF
    'ALA': [0.17, 0.50, 0.33],
    'ARG': [0.81, 1.81, 1.00],
    'ASN': [0.42, 0.85, 0.43],
    'ASP': [1.23, 3.64, 2.41],
    'ASH': [-0.07, 0.43, 0.50],
    'CYS': [-0.24, -0.02, 0.22],
    'GLN': [0.58, 0.77, 0.19],
    'GLU': [2.02, 3.63, 1.61],
    'GLH': [-0.01, 0.11, 0.12],
    'GLY': [0.01, 1.15, 1.14],
    // "His+": [  0.96,  2.33,  1.37 ],
    'HIS': [0.17, 0.11, -0.06],
    'ILE': [-0.31, -1.12, -0.81],
    'LEU': [-0.56, -1.25, -0.69],
    'LYS': [0.99, 2.80, 1.81],
    'MET': [-0.23, -0.67, -0.44],
    'PHE': [-1.13, -1.71, -0.58],
    'PRO': [0.45, 0.14, -0.31],
    'SER': [0.13, 0.46, 0.33],
    'THR': [0.14, 0.25, 0.11],
    'TRP': [-1.85, -2.09, -0.24],
    'TYR': [-0.94, -0.71, 0.23],
    'VAL': [0.07, -0.46, -0.53]
};
var DefaultResidueHydrophobicity = [0.00, 0.00, 0.00];
//# sourceMappingURL=types.js.map

/***/ }),
/* 23 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EveryLoci", function() { return EveryLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEveryLoci", function() { return isEveryLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "EmptyLoci", function() { return EmptyLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isEmptyLoci", function() { return isEmptyLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDataLoci", function() { return isDataLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "areDataLociEqual", function() { return areDataLociEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isDataLociEmpty", function() { return isDataLociEmpty; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DataLoci", function() { return DataLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Loci", function() { return Loci; });
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(159);
/* harmony import */ var _shape__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(49);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1);
/* harmony import */ var _structure_structure__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(27);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(5);
/* harmony import */ var _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(126);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(41);
/* harmony import */ var _volume_volume__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(138);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











/** A Loci that includes every loci */
var EveryLoci = { kind: 'every-loci' };
function isEveryLoci(x) {
    return !!x && x.kind === 'every-loci';
}
/** A Loci that is empty */
var EmptyLoci = { kind: 'empty-loci' };
function isEmptyLoci(x) {
    return !!x && x.kind === 'empty-loci';
}
function isDataLoci(x) {
    return !!x && x.kind === 'data-loci';
}
function areDataLociEqual(a, b) {
    // use shallowEqual to allow simple data objects that are contructed on-the-fly
    if (!Object(_mol_util__WEBPACK_IMPORTED_MODULE_7__[/* shallowEqual */ "l"])(a.data, b.data) || a.tag !== b.tag)
        return false;
    if (a.elements.length !== b.elements.length)
        return false;
    for (var i = 0, il = a.elements.length; i < il; ++i) {
        if (!Object(_mol_util__WEBPACK_IMPORTED_MODULE_7__[/* shallowEqual */ "l"])(a.elements[i], b.elements[i]))
            return false;
    }
    return true;
}
function isDataLociEmpty(loci) {
    return loci.elements.length === 0 ? true : false;
}
function DataLoci(tag, data, elements, getBoundingSphere, getLabel) {
    return { kind: 'data-loci', tag: tag, data: data, elements: elements, getBoundingSphere: getBoundingSphere, getLabel: getLabel };
}

var Loci;
(function (Loci) {
    var boundaryHelper = new _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_8__[/* BoundaryHelper */ "a"]('98');
    function getBundleBoundingSphere(bundle) {
        var spheres = bundle.loci.map(function (l) { return getBoundingSphere(l); }).filter(function (s) { return !!s; });
        boundaryHelper.reset();
        for (var _i = 0, spheres_1 = spheres; _i < spheres_1.length; _i++) {
            var s = spheres_1[_i];
            boundaryHelper.includePositionRadius(s.center, s.radius);
        }
        boundaryHelper.finishedIncludeStep();
        for (var _a = 0, spheres_2 = spheres; _a < spheres_2.length; _a++) {
            var s = spheres_2[_a];
            boundaryHelper.radiusPositionRadius(s.center, s.radius);
        }
        return boundaryHelper.getSphere();
    }
    Loci.getBundleBoundingSphere = getBundleBoundingSphere;
    function areEqual(lociA, lociB) {
        if (isEveryLoci(lociA) && isEveryLoci(lociB))
            return true;
        if (isEmptyLoci(lociA) && isEmptyLoci(lociB))
            return true;
        if (isDataLoci(lociA) && isDataLoci(lociB)) {
            return areDataLociEqual(lociA, lociB);
        }
        if (_structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLoci(lociA) && _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLoci(lociB)) {
            return _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].areLociEqual(lociA, lociB);
        }
        if (_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(lociA) && _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(lociB)) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.areEqual(lociA, lociB);
        }
        if (_structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLoci(lociA) && _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLoci(lociB)) {
            return _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].areLociEqual(lociA, lociB);
        }
        if (_shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].isLoci(lociA) && _shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].isLoci(lociB)) {
            return _shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].areLociEqual(lociA, lociB);
        }
        if (_shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].isLoci(lociA) && _shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].isLoci(lociB)) {
            return _shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].areLociEqual(lociA, lociB);
        }
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].isLoci(lociA) && _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].isLoci(lociB)) {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].areLociEqual(lociA, lociB);
        }
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.isLoci(lociA) && _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.isLoci(lociB)) {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.areLociEqual(lociA, lociB);
        }
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.isLoci(lociA) && _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.isLoci(lociB)) {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.areLociEqual(lociA, lociB);
        }
        return false;
    }
    Loci.areEqual = areEqual;
    function isEvery(loci) {
        return !!loci && loci.kind === 'every-loci';
    }
    Loci.isEvery = isEvery;
    function isEmpty(loci) {
        if (isEveryLoci(loci))
            return false;
        if (isEmptyLoci(loci))
            return true;
        if (isDataLoci(loci))
            return isDataLociEmpty(loci);
        if (_structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLoci(loci))
            return _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLociEmpty(loci);
        if (_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci))
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.isEmpty(loci);
        if (_structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLoci(loci))
            return _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLociEmpty(loci);
        if (_shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].isLoci(loci))
            return _shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].isLociEmpty(loci);
        if (_shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].isLoci(loci))
            return _shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].isLociEmpty(loci);
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].isLoci(loci))
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].isLociEmpty(loci);
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.isLoci(loci))
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.isLociEmpty(loci);
        if (_volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.isLoci(loci))
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.isLociEmpty(loci);
        return false;
    }
    Loci.isEmpty = isEmpty;
    function remap(loci, data) {
        if (data instanceof _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"]) {
            if (_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)) {
                loci = _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.remap(loci, data);
            }
            else if (_structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLoci(loci)) {
                loci = _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].remapLoci(loci, data);
            }
            else if (_structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLoci(loci)) {
                loci = _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].remapLoci(loci, data);
            }
        }
        return loci;
    }
    Loci.remap = remap;
    function getBoundingSphere(loci, boundingSphere) {
        if (loci.kind === 'every-loci' || loci.kind === 'empty-loci')
            return void 0;
        if (!boundingSphere)
            boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"])();
        if (loci.kind === 'structure-loci') {
            return _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, loci.structure.boundary.sphere);
        }
        else if (loci.kind === 'element-loci') {
            return _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.getBoundary(loci).sphere);
        }
        else if (loci.kind === 'bond-loci') {
            return _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].getBoundingSphere(loci, boundingSphere);
        }
        else if (loci.kind === 'shape-loci') {
            return _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, loci.shape.geometry.boundingSphere);
        }
        else if (loci.kind === 'group-loci') {
            return _shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].getBoundingSphere(loci, boundingSphere);
        }
        else if (loci.kind === 'data-loci') {
            return loci.getBoundingSphere(boundingSphere);
        }
        else if (loci.kind === 'volume-loci') {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].getBoundingSphere(loci.volume, boundingSphere);
        }
        else if (loci.kind === 'isosurface-loci') {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Isosurface.getBoundingSphere(loci.volume, loci.isoValue, boundingSphere);
        }
        else if (loci.kind === 'cell-loci') {
            return _volume_volume__WEBPACK_IMPORTED_MODULE_10__[/* Volume */ "a"].Cell.getBoundingSphere(loci.volume, loci.indices, boundingSphere);
        }
    }
    Loci.getBoundingSphere = getBoundingSphere;
    var tmpSphere3D = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].zero();
    function getCenter(loci, center) {
        var boundingSphere = getBoundingSphere(loci, tmpSphere3D);
        return boundingSphere ? _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].copy(center || Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), boundingSphere.center) : undefined;
    }
    Loci.getCenter = getCenter;
    function getPrincipalAxes(loci) {
        if (loci.kind === 'every-loci' || loci.kind === 'empty-loci')
            return void 0;
        if (loci.kind === 'structure-loci') {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.getPrincipalAxes(_structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].toStructureElementLoci(loci.structure));
        }
        else if (loci.kind === 'element-loci') {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.getPrincipalAxes(loci);
        }
        else if (loci.kind === 'bond-loci') {
            // TODO
            return void 0;
        }
        else if (loci.kind === 'shape-loci') {
            // TODO
            return void 0;
        }
        else if (loci.kind === 'group-loci') {
            // TODO
            return void 0;
        }
        else if (loci.kind === 'data-loci') {
            // TODO maybe add loci.getPrincipalAxes()???
            return void 0;
        }
        else if (loci.kind === 'volume-loci') {
            // TODO
            return void 0;
        }
        else if (loci.kind === 'isosurface-loci') {
            // TODO
            return void 0;
        }
        else if (loci.kind === 'cell-loci') {
            // TODO
            return void 0;
        }
    }
    Loci.getPrincipalAxes = getPrincipalAxes;
    //
    var Granularity = {
        'element': function (loci) { return loci; },
        'residue': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeResidues(loci, true)
                : loci;
        },
        'chain': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeChains(loci)
                : loci;
        },
        'entity': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeEntities(loci)
                : loci;
        },
        'model': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeModels(loci)
                : loci;
        },
        'structure': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].toStructureElementLoci(loci.structure)
                : _shape__WEBPACK_IMPORTED_MODULE_2__[/* ShapeGroup */ "b"].isLoci(loci)
                    ? _shape__WEBPACK_IMPORTED_MODULE_2__[/* Shape */ "a"].Loci(loci.shape)
                    : loci;
        },
        'elementInstances': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToAllInstances(loci)
                : loci;
        },
        'residueInstances': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToAllInstances(_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeResidues(loci, true))
                : loci;
        },
        'chainInstances': function (loci) {
            return _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)
                ? _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToAllInstances(_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.extendToWholeChains(loci))
                : loci;
        },
    };
    Loci.GranularityOptions = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].objectToOptions(Granularity, function (k) {
        switch (k) {
            case 'element': return 'Atom/Coarse Element';
            case 'elementInstances': return ['Atom/Coarse Element Instances', 'With Symmetry'];
            case 'structure': return 'Structure/Shape';
            default: return k.indexOf('Instances')
                ? [Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_9__[/* stringToWords */ "d"])(k), 'With Symmetry'] : Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_9__[/* stringToWords */ "d"])(k);
        }
    });
    function applyGranularity(loci, granularity) {
        return Granularity[granularity](loci);
    }
    Loci.applyGranularity = applyGranularity;
    /**
     * Converts structure related loci to StructureElement.Loci and applies
     * granularity if given
     */
    function normalize(loci, granularity) {
        if (granularity !== 'element' && _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].isLoci(loci)) {
            // convert Bond.Loci to a StructureElement.Loci so granularity can be applied
            loci = _structure_structure_unit_bonds__WEBPACK_IMPORTED_MODULE_1__[/* Bond */ "a"].toStructureElementLoci(loci);
        }
        if (_structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].isLoci(loci)) {
            // convert to StructureElement.Loci
            loci = _structure_structure__WEBPACK_IMPORTED_MODULE_5__[/* Structure */ "c"].toStructureElementLoci(loci.structure);
        }
        if (_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.is(loci)) {
            // ensure the root structure is used
            loci = _structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Loci.remap(loci, loci.structure.root);
        }
        if (granularity) {
            // needs to be applied AFTER remapping to root
            loci = applyGranularity(loci, granularity);
        }
        return loci;
    }
    Loci.normalize = normalize;
})(Loci || (Loci = {}));
//# sourceMappingURL=loci.js.map

/***/ }),
/* 24 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(43);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return _color__WEBPACK_IMPORTED_MODULE_0__["Color"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorMap", function() { return _color__WEBPACK_IMPORTED_MODULE_0__["ColorMap"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorTable", function() { return _color__WEBPACK_IMPORTED_MODULE_0__["ColorTable"]; });

/* harmony import */ var _scale__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(337);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ColorScale", function() { return _scale__WEBPACK_IMPORTED_MODULE_1__["a"]; });

/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


//# sourceMappingURL=index.js.map

/***/ }),
/* 25 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ mat4["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ mat3; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ vec2; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* reexport */ vec3["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* reexport */ vec4; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ quat; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ common["a" /* EPSILON */]; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/mat4.js
var mat4 = __webpack_require__(105);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/mat3.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */

function mat3_Mat3() {
    return mat3_Mat3.zero();
}
(function (Mat3) {
    function zero() {
        // force double backing array by 0.1.
        var ret = [0.1, 0, 0, 0, 0, 0, 0, 0, 0];
        ret[0] = 0.0;
        return ret;
    }
    Mat3.zero = zero;
    function identity() {
        var out = zero();
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 1;
        out[5] = 0;
        out[6] = 0;
        out[7] = 0;
        out[8] = 1;
        return out;
    }
    Mat3.identity = identity;
    function setIdentity(mat) {
        mat[0] = 1;
        mat[1] = 0;
        mat[2] = 0;
        mat[3] = 0;
        mat[4] = 1;
        mat[5] = 0;
        mat[6] = 0;
        mat[7] = 0;
        mat[8] = 1;
        return mat;
    }
    Mat3.setIdentity = setIdentity;
    function toArray(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        out[offset + 2] = a[2];
        out[offset + 3] = a[3];
        out[offset + 4] = a[4];
        out[offset + 5] = a[5];
        out[offset + 6] = a[6];
        out[offset + 7] = a[7];
        out[offset + 8] = a[8];
        return out;
    }
    Mat3.toArray = toArray;
    function fromArray(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        a[2] = array[offset + 2];
        a[3] = array[offset + 3];
        a[4] = array[offset + 4];
        a[5] = array[offset + 5];
        a[6] = array[offset + 6];
        a[7] = array[offset + 7];
        a[8] = array[offset + 8];
        return a;
    }
    Mat3.fromArray = fromArray;
    /**
     * Copies the upper-left 3x3 values into the given mat3.
     */
    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;
    }
    Mat3.fromMat4 = fromMat4;
    function create(a00, a01, a02, a10, a11, a12, a20, a21, a22) {
        var out = zero();
        out[0] = a00;
        out[1] = a01;
        out[2] = a02;
        out[3] = a10;
        out[4] = a11;
        out[5] = a12;
        out[6] = a20;
        out[7] = a21;
        out[8] = a22;
        return out;
    }
    Mat3.create = create;
    var _id = identity();
    function isIdentity(m, eps) {
        return areEqual(m, _id, typeof eps === 'undefined' ? common["a" /* EPSILON */] : eps);
    }
    Mat3.isIdentity = isIdentity;
    function hasNaN(m) {
        for (var i = 0; i < 9; i++)
            if (isNaN(m[i]))
                return true;
        return false;
    }
    Mat3.hasNaN = hasNaN;
    /**
     * Creates a new Mat3 initialized with values from an existing matrix
     */
    function clone(a) {
        return Mat3.copy(Mat3.zero(), a);
    }
    Mat3.clone = clone;
    function areEqual(a, b, eps) {
        for (var i = 0; i < 9; i++) {
            if (Math.abs(a[i] - b[i]) > eps)
                return false;
        }
        return true;
    }
    Mat3.areEqual = areEqual;
    function setValue(a, i, j, value) {
        a[3 * j + i] = value;
    }
    Mat3.setValue = setValue;
    function getValue(a, i, j) {
        return a[3 * j + i];
    }
    Mat3.getValue = getValue;
    /**
     * Copy the values from one Mat3 to another
     */
    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;
    }
    Mat3.copy = copy;
    /**
     * Transpose the values of a Mat3
     */
    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;
    }
    Mat3.transpose = transpose;
    /**
     * Inverts a Mat3
     */
    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) {
            console.warn('non-invertible matrix.', a);
            return out;
        }
        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;
    }
    Mat3.invert = invert;
    function symmtricFromUpper(out, a) {
        if (out === a) {
            out[3] = a[1];
            out[6] = a[2];
            out[7] = a[5];
        }
        else {
            out[0] = a[0];
            out[1] = a[1];
            out[2] = a[2];
            out[3] = a[1];
            out[4] = a[4];
            out[5] = a[5];
            out[6] = a[2];
            out[7] = a[5];
            out[8] = a[8];
        }
        return out;
    }
    Mat3.symmtricFromUpper = symmtricFromUpper;
    function symmtricFromLower(out, a) {
        if (out === a) {
            out[1] = a[3];
            out[2] = a[6];
            out[5] = a[7];
        }
        else {
            out[0] = a[0];
            out[1] = a[3];
            out[2] = a[6];
            out[3] = a[3];
            out[4] = a[4];
            out[5] = a[7];
            out[6] = a[6];
            out[7] = a[7];
            out[8] = a[8];
        }
        return out;
    }
    Mat3.symmtricFromLower = symmtricFromLower;
    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];
        var b01 = a22 * a11 - a12 * a21;
        var b11 = -a22 * a10 + a12 * a20;
        var b21 = a21 * a10 - a11 * a20;
        // Calculate the determinant
        return a00 * b01 + a01 * b11 + a02 * b21;
    }
    Mat3.determinant = determinant;
    function trace(a) {
        return a[0] + a[4] + a[8];
    }
    Mat3.trace = trace;
    function sub(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;
    }
    Mat3.sub = sub;
    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;
    }
    Mat3.add = add;
    function mul(out, a, b) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8];
        var b00 = b[0], b01 = b[1], b02 = b[2], b10 = b[3], b11 = b[4], b12 = b[5], b20 = b[6], b21 = b[7], b22 = b[8];
        out[0] = b00 * a00 + b01 * a10 + b02 * a20;
        out[1] = b00 * a01 + b01 * a11 + b02 * a21;
        out[2] = b00 * a02 + b01 * a12 + b02 * a22;
        out[3] = b10 * a00 + b11 * a10 + b12 * a20;
        out[4] = b10 * a01 + b11 * a11 + b12 * a21;
        out[5] = b10 * a02 + b11 * a12 + b12 * a22;
        out[6] = b20 * a00 + b21 * a10 + b22 * a20;
        out[7] = b20 * a01 + b21 * a11 + b22 * a21;
        out[8] = b20 * a02 + b21 * a12 + b22 * a22;
        return out;
    }
    Mat3.mul = mul;
    function subScalar(out, a, s) {
        out[0] = a[0] - s;
        out[1] = a[1] - s;
        out[2] = a[2] - s;
        out[3] = a[3] - s;
        out[4] = a[4] - s;
        out[5] = a[5] - s;
        out[6] = a[6] - s;
        out[7] = a[7] - s;
        out[8] = a[8] - s;
        return out;
    }
    Mat3.subScalar = subScalar;
    function addScalar(out, a, s) {
        out[0] = a[0] + s;
        out[1] = a[1] + s;
        out[2] = a[2] + s;
        out[3] = a[3] + s;
        out[4] = a[4] + s;
        out[5] = a[5] + s;
        out[6] = a[6] + s;
        out[7] = a[7] + s;
        out[8] = a[8] + s;
        return out;
    }
    Mat3.addScalar = addScalar;
    function mulScalar(out, a, s) {
        out[0] = a[0] * s;
        out[1] = a[1] * s;
        out[2] = a[2] * s;
        out[3] = a[3] * s;
        out[4] = a[4] * s;
        out[5] = a[5] * s;
        out[6] = a[6] * s;
        out[7] = a[7] * s;
        out[8] = a[8] * s;
        return out;
    }
    Mat3.mulScalar = mulScalar;
    var piThird = Math.PI / 3;
    var tmpB = Mat3();
    /**
     * Given a real symmetric 3x3 matrix A, compute the eigenvalues
     *
     * From https://en.wikipedia.org/wiki/Eigenvalue_algorithm#3.C3.973_matrices
     */
    function symmetricEigenvalues(out, a) {
        var p1 = a[1] * a[1] + a[2] * a[2] + a[5] * a[5];
        if (p1 === 0) {
            out[0] = a[0];
            out[1] = a[4];
            out[2] = a[8];
        }
        else {
            var q = trace(a) / 3;
            var a1 = a[0] - q;
            var a2 = a[4] - q;
            var a3 = a[8] - q;
            var p2 = a1 * a1 + a2 * a2 + a3 * a3 + 2 * p1;
            var p = Math.sqrt(p2 / 6);
            mulScalar(tmpB, Mat3.Identity, q);
            sub(tmpB, a, tmpB);
            mulScalar(tmpB, tmpB, (1 / p));
            var r = determinant(tmpB) / 2;
            // In exact arithmetic for a symmetric matrix  -1 <= r <= 1
            // but computation error can leave it slightly outside this range.
            var phi = r <= -1 ? piThird : r >= 1 ?
                0 : Math.acos(r) / 3;
            // the eigenvalues satisfy eig3 <= eig2 <= eig1
            out[0] = q + 2 * p * Math.cos(phi);
            out[2] = q + 2 * p * Math.cos(phi + (2 * piThird));
            out[1] = 3 * q - out[0] - out[2]; // since trace(A) = eig1 + eig2 + eig3
        }
        return out;
    }
    Mat3.symmetricEigenvalues = symmetricEigenvalues;
    var tmpR0 = [0.1, 0.0, 0.0];
    var tmpR1 = [0.1, 0.0, 0.0];
    var tmpR2 = [0.1, 0.0, 0.0];
    var tmpR0xR1 = [0.1, 0.0, 0.0];
    var tmpR0xR2 = [0.1, 0.0, 0.0];
    var tmpR1xR2 = [0.1, 0.0, 0.0];
    /**
     * Calculates the eigenvector for the given eigenvalue `e` of matrix `a`
     */
    function eigenvector(out, a, e) {
        vec3["a" /* default */].set(tmpR0, a[0] - e, a[1], a[2]);
        vec3["a" /* default */].set(tmpR1, a[1], a[4] - e, a[5]);
        vec3["a" /* default */].set(tmpR2, a[2], a[5], a[8] - e);
        vec3["a" /* default */].cross(tmpR0xR1, tmpR0, tmpR1);
        vec3["a" /* default */].cross(tmpR0xR2, tmpR0, tmpR2);
        vec3["a" /* default */].cross(tmpR1xR2, tmpR1, tmpR2);
        var d0 = vec3["a" /* default */].dot(tmpR0xR1, tmpR0xR1);
        var d1 = vec3["a" /* default */].dot(tmpR0xR2, tmpR0xR2);
        var d2 = vec3["a" /* default */].dot(tmpR1xR2, tmpR1xR2);
        var dmax = d0;
        var imax = 0;
        if (d1 > dmax) {
            dmax = d1;
            imax = 1;
        }
        if (d2 > dmax)
            imax = 2;
        if (imax === 0) {
            vec3["a" /* default */].scale(out, tmpR0xR1, 1 / Math.sqrt(d0));
        }
        else if (imax === 1) {
            vec3["a" /* default */].scale(out, tmpR0xR2, 1 / Math.sqrt(d1));
        }
        else {
            vec3["a" /* default */].scale(out, tmpR1xR2, 1 / Math.sqrt(d2));
        }
        return out;
    }
    Mat3.eigenvector = eigenvector;
    /**
     * Get matrix to transform directions, e.g. normals
     */
    function directionTransform(out, t) {
        Mat3.fromMat4(out, t);
        Mat3.invert(out, out);
        Mat3.transpose(out, out);
        return out;
    }
    Mat3.directionTransform = directionTransform;
    Mat3.Identity = identity();
})(mat3_Mat3 || (mat3_Mat3 = {}));
/* harmony default export */ var mat3 = (mat3_Mat3);
//# sourceMappingURL=mat3.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/vec2.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function Vec2() {
    return Vec2.zero();
}
(function (Vec2) {
    function zero() {
        // force double backing array by 0.1.
        var ret = [0.1, 0];
        ret[0] = 0.0;
        return ret;
    }
    Vec2.zero = zero;
    function clone(a) {
        var out = zero();
        out[0] = a[0];
        out[1] = a[1];
        return out;
    }
    Vec2.clone = clone;
    function create(x, y) {
        var out = zero();
        out[0] = x;
        out[1] = y;
        return out;
    }
    Vec2.create = create;
    function hasNaN(a) {
        return isNaN(a[0]) || isNaN(a[1]);
    }
    Vec2.hasNaN = hasNaN;
    function toArray(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        return out;
    }
    Vec2.toArray = toArray;
    function fromArray(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        return a;
    }
    Vec2.fromArray = fromArray;
    function copy(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        return out;
    }
    Vec2.copy = copy;
    function set(out, x, y) {
        out[0] = x;
        out[1] = y;
        return out;
    }
    Vec2.set = set;
    function add(out, a, b) {
        out[0] = a[0] + b[0];
        out[1] = a[1] + b[1];
        return out;
    }
    Vec2.add = add;
    function sub(out, a, b) {
        out[0] = a[0] - b[0];
        out[1] = a[1] - b[1];
        return out;
    }
    Vec2.sub = sub;
    function mul(out, a, b) {
        out[0] = a[0] * b[0];
        out[1] = a[1] * b[1];
        return out;
    }
    Vec2.mul = mul;
    function div(out, a, b) {
        out[0] = a[0] / b[0];
        out[1] = a[1] / b[1];
        return out;
    }
    Vec2.div = div;
    function scale(out, a, b) {
        out[0] = a[0] * b;
        out[1] = a[1] * b;
        return out;
    }
    Vec2.scale = scale;
    /**
     * Math.round the components of a Vec2
     */
    function round(out, a) {
        out[0] = Math.round(a[0]);
        out[1] = Math.round(a[1]);
        return out;
    }
    Vec2.round = round;
    /**
     * Math.ceil the components of a Vec2
     */
    function ceil(out, a) {
        out[0] = Math.ceil(a[0]);
        out[1] = Math.ceil(a[1]);
        return out;
    }
    Vec2.ceil = ceil;
    /**
     * Math.floor the components of a Vec2
     */
    function floor(out, a) {
        out[0] = Math.floor(a[0]);
        out[1] = Math.floor(a[1]);
        return out;
    }
    Vec2.floor = floor;
    function distance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1];
        return Math.sqrt(x * x + y * y);
    }
    Vec2.distance = distance;
    function squaredDistance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1];
        return x * x + y * y;
    }
    Vec2.squaredDistance = squaredDistance;
    function magnitude(a) {
        var x = a[0], y = a[1];
        return Math.sqrt(x * x + y * y);
    }
    Vec2.magnitude = magnitude;
    function squaredMagnitude(a) {
        var x = a[0], y = a[1];
        return x * x + y * y;
    }
    Vec2.squaredMagnitude = squaredMagnitude;
    /**
     * Returns the inverse of the components of a Vec2
     */
    function inverse(out, a) {
        out[0] = 1.0 / a[0];
        out[1] = 1.0 / a[1];
        return out;
    }
    Vec2.inverse = inverse;
    function areEqual(a, b) {
        return a[0] === b[0] && a[1] === b[1];
    }
    Vec2.areEqual = areEqual;
    function toString(a, precision) {
        return "[" + a[0].toPrecision(precision) + " " + a[1].toPrecision(precision) + "}]";
    }
    Vec2.toString = toString;
})(Vec2 || (Vec2 = {}));
/* harmony default export */ var vec2 = (Vec2);
//# sourceMappingURL=vec2.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/vec3.js
var vec3 = __webpack_require__(137);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/vec4.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function vec4_Vec4() {
    return vec4_Vec4.zero();
}
(function (Vec4) {
    function zero() {
        // force double backing array by 0.1.
        var ret = [0.1, 0, 0, 0];
        ret[0] = 0.0;
        return ret;
    }
    Vec4.zero = zero;
    function clone(a) {
        var out = zero();
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    Vec4.clone = clone;
    function create(x, y, z, w) {
        var out = zero();
        out[0] = x;
        out[1] = y;
        out[2] = z;
        out[3] = w;
        return out;
    }
    Vec4.create = create;
    function fromSphere(out, sphere) {
        out[0] = sphere.center[0];
        out[1] = sphere.center[1];
        out[2] = sphere.center[2];
        out[3] = sphere.radius;
        return out;
    }
    Vec4.fromSphere = fromSphere;
    function ofSphere(sphere) {
        return fromSphere(zero(), sphere);
    }
    Vec4.ofSphere = ofSphere;
    function hasNaN(a) {
        return isNaN(a[0]) || isNaN(a[1]) || isNaN(a[2]) || isNaN(a[3]);
    }
    Vec4.hasNaN = hasNaN;
    function toArray(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        out[offset + 2] = a[2];
        out[offset + 3] = a[3];
        return out;
    }
    Vec4.toArray = toArray;
    function fromArray(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        a[2] = array[offset + 2];
        a[3] = array[offset + 3];
        return a;
    }
    Vec4.fromArray = fromArray;
    function toVec3Array(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        out[offset + 2] = a[2];
    }
    Vec4.toVec3Array = toVec3Array;
    function fromVec3Array(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        a[2] = array[offset + 2];
        a[3] = 0;
        return a;
    }
    Vec4.fromVec3Array = fromVec3Array;
    function copy(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    Vec4.copy = copy;
    function set(out, x, y, z, w) {
        out[0] = x;
        out[1] = y;
        out[2] = z;
        out[3] = w;
        return out;
    }
    Vec4.set = set;
    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;
    }
    Vec4.add = add;
    function distance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3];
        return Math.sqrt(x * x + y * y + z * z + w * w);
    }
    Vec4.distance = distance;
    function scale(out, a, b) {
        out[0] = a[0] * b;
        out[1] = a[1] * b;
        out[2] = a[2] * b;
        out[4] = a[4] * b;
        return out;
    }
    Vec4.scale = scale;
    /**
     * Math.round the components of a Vec4
     */
    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;
    }
    Vec4.round = round;
    /**
     * Math.ceil the components of a Vec4
     */
    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;
    }
    Vec4.ceil = ceil;
    /**
     * Math.floor the components of a Vec3
     */
    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;
    }
    Vec4.floor = floor;
    function squaredDistance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2], w = b[3] - a[3];
        return x * x + y * y + z * z + w * w;
    }
    Vec4.squaredDistance = squaredDistance;
    function norm(a) {
        var x = a[0], y = a[1], z = a[2], w = a[3];
        return Math.sqrt(x * x + y * y + z * z + w * w);
    }
    Vec4.norm = norm;
    function squaredNorm(a) {
        var x = a[0], y = a[1], z = a[2], w = a[3];
        return x * x + y * y + z * z + w * w;
    }
    Vec4.squaredNorm = squaredNorm;
    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;
    }
    Vec4.transformMat4 = transformMat4;
    function dot(a, b) {
        return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
    }
    Vec4.dot = dot;
    /**
     * Returns the inverse of the components of a Vec4
     */
    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;
    }
    Vec4.inverse = inverse;
    /**
     * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
     */
    function exactEquals(a, b) {
        return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3];
    }
    Vec4.exactEquals = exactEquals;
    /**
     * Returns whether or not the vectors have approximately the same elements in the same position.
     */
    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) <= common["a" /* EPSILON */] * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
            Math.abs(a1 - b1) <= common["a" /* EPSILON */] * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
            Math.abs(a2 - b2) <= common["a" /* EPSILON */] * Math.max(1.0, Math.abs(a2), Math.abs(b2)) &&
            Math.abs(a3 - b3) <= common["a" /* EPSILON */] * Math.max(1.0, Math.abs(a3), Math.abs(b3)));
    }
    Vec4.equals = equals;
    function toString(a, precision) {
        return "[" + a[0].toPrecision(precision) + " " + a[1].toPrecision(precision) + " " + a[2].toPrecision(precision) + "  " + a[3].toPrecision(precision) + "]";
    }
    Vec4.toString = toString;
})(vec4_Vec4 || (vec4_Vec4 = {}));
/* harmony default export */ var vec4 = (vec4_Vec4);
//# sourceMappingURL=vec4.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/common.js
var common = __webpack_require__(82);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/quat.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */
/*
 * Quat.fromUnitVec3 has been modified from https://github.com/Jam3/quat-from-unit-vec3,
 * copyright (c) 2015 Jam3. MIT License
 */



function quat_Quat() {
    return quat_Quat.zero();
}
(function (Quat) {
    function zero() {
        // force double backing array by 0.1.
        var ret = [0.1, 0, 0, 0];
        ret[0] = 0.0;
        return ret;
    }
    Quat.zero = zero;
    function identity() {
        var out = zero();
        out[3] = 1;
        return out;
    }
    Quat.identity = identity;
    function setIdentity(out) {
        out[0] = 0;
        out[1] = 0;
        out[2] = 0;
        out[3] = 1;
    }
    Quat.setIdentity = setIdentity;
    function hasNaN(q) {
        return isNaN(q[0]) || isNaN(q[1]) || isNaN(q[2]) || isNaN(q[3]);
    }
    Quat.hasNaN = hasNaN;
    function create(x, y, z, w) {
        var out = identity();
        out[0] = x;
        out[1] = y;
        out[2] = z;
        out[3] = w;
        return out;
    }
    Quat.create = create;
    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;
    }
    Quat.setAxisAngle = setAxisAngle;
    /**
     * 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.
     */
    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;
    }
    Quat.getAxisAngle = getAxisAngle;
    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;
    }
    Quat.multiply = multiply;
    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;
    }
    Quat.rotateX = rotateX;
    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;
    }
    Quat.rotateY = rotateY;
    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;
    }
    Quat.rotateZ = rotateZ;
    /**
     * 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.
     */
    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;
    }
    Quat.calculateW = calculateW;
    /**
     * Performs a spherical linear interpolation between two quat
     */
    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, cosom, sinom, scale0, scale1;
        // 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;
    }
    Quat.slerp = slerp;
    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;
    }
    Quat.invert = invert;
    /**
     * Calculates the conjugate of a quat
     * If the quaternion is normalized, this function is faster than quat.inverse and produces the same result.
     */
    function conjugate(out, a) {
        out[0] = -a[0];
        out[1] = -a[1];
        out[2] = -a[2];
        out[3] = a[3];
        return out;
    }
    Quat.conjugate = conjugate;
    /**
     * 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.
     */
    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;
        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;
    }
    Quat.fromMat3 = fromMat3;
    var fromUnitVec3Temp = Object(vec3["a" /* default */])();
    /** Quaternion from two normalized unit vectors. */
    function fromUnitVec3(out, a, b) {
        // assumes a and b are normalized
        var r = vec3["a" /* default */].dot(a, b) + 1;
        if (r < common["a" /* EPSILON */]) {
            // If u and v are exactly opposite, rotate 180 degrees
            // around an arbitrary orthogonal axis. Axis normalisation
            // can happen later, when we normalise the quaternion.
            r = 0;
            if (Math.abs(a[0]) > Math.abs(a[2])) {
                vec3["a" /* default */].set(fromUnitVec3Temp, -a[1], a[0], 0);
            }
            else {
                vec3["a" /* default */].set(fromUnitVec3Temp, 0, -a[2], a[1]);
            }
        }
        else {
            // Otherwise, build quaternion the standard way.
            vec3["a" /* default */].cross(fromUnitVec3Temp, a, b);
        }
        out[0] = fromUnitVec3Temp[0];
        out[1] = fromUnitVec3Temp[1];
        out[2] = fromUnitVec3Temp[2];
        out[3] = r;
        normalize(out, out);
        return out;
    }
    Quat.fromUnitVec3 = fromUnitVec3;
    function clone(a) {
        var out = zero();
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    Quat.clone = clone;
    function toArray(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        out[offset + 2] = a[2];
        out[offset + 3] = a[3];
        return out;
    }
    Quat.toArray = toArray;
    function fromArray(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        a[2] = array[offset + 2];
        a[3] = array[offset + 3];
        return a;
    }
    Quat.fromArray = fromArray;
    function copy(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[3] = a[3];
        return out;
    }
    Quat.copy = copy;
    function set(out, x, y, z, w) {
        out[0] = x;
        out[1] = y;
        out[2] = z;
        out[3] = w;
        return out;
    }
    Quat.set = set;
    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;
    }
    Quat.add = add;
    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;
    }
    Quat.normalize = normalize;
    /**
     * Sets a quaternion to represent the shortest rotation from one
     * vector to another.
     *
     * Both vectors are assumed to be unit length.
     */
    var rotTmpVec3 = Object(vec3["a" /* default */])();
    var rotTmpVec3UnitX = vec3["a" /* default */].create(1, 0, 0);
    var rotTmpVec3UnitY = vec3["a" /* default */].create(0, 1, 0);
    function rotationTo(out, a, b) {
        var dot = vec3["a" /* default */].dot(a, b);
        if (dot < -0.999999) {
            vec3["a" /* default */].cross(rotTmpVec3, rotTmpVec3UnitX, a);
            if (vec3["a" /* default */].magnitude(rotTmpVec3) < 0.000001)
                vec3["a" /* default */].cross(rotTmpVec3, rotTmpVec3UnitY, a);
            vec3["a" /* default */].normalize(rotTmpVec3, rotTmpVec3);
            setAxisAngle(out, rotTmpVec3, 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["a" /* default */].cross(rotTmpVec3, a, b);
            out[0] = rotTmpVec3[0];
            out[1] = rotTmpVec3[1];
            out[2] = rotTmpVec3[2];
            out[3] = 1 + dot;
            return normalize(out, out);
        }
    }
    Quat.rotationTo = rotationTo;
    /**
     * Performs a spherical linear interpolation with two control points
     */
    var sqlerpTemp1 = Quat();
    var sqlerpTemp2 = Quat();
    function sqlerp(out, a, b, c, d, t) {
        slerp(sqlerpTemp1, a, d, t);
        slerp(sqlerpTemp2, b, c, t);
        slerp(out, sqlerpTemp1, sqlerpTemp2, 2 * t * (1 - t));
        return out;
    }
    Quat.sqlerp = sqlerp;
    /**
     * 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.
     */
    var axesTmpMat = mat3();
    function setAxes(out, view, right, up) {
        axesTmpMat[0] = right[0];
        axesTmpMat[3] = right[1];
        axesTmpMat[6] = right[2];
        axesTmpMat[1] = up[0];
        axesTmpMat[4] = up[1];
        axesTmpMat[7] = up[2];
        axesTmpMat[2] = -view[0];
        axesTmpMat[5] = -view[1];
        axesTmpMat[8] = -view[2];
        return normalize(out, Quat.fromMat3(out, axesTmpMat));
    }
    Quat.setAxes = setAxes;
    function toString(a, precision) {
        return "[" + a[0].toPrecision(precision) + " " + a[1].toPrecision(precision) + " " + a[2].toPrecision(precision) + "  " + a[3].toPrecision(precision) + "]";
    }
    Quat.toString = toString;
    Quat.Identity = identity();
})(quat_Quat || (quat_Quat = {}));
/* harmony default export */ var quat = (quat_Quat);
//# sourceMappingURL=quat.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */








//# sourceMappingURL=3d.js.map

/***/ }),
/* 26 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginCommands", function() { return PluginCommands; });
/* harmony import */ var _command__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(95);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var PluginCommands = {
    State: {
        SetCurrentObject: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        ApplyAction: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        Update: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        RemoveObject: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        ToggleExpanded: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        ToggleVisibility: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        Snapshots: {
            Add: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Replace: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Move: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Remove: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Apply: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Clear: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Upload: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Fetch: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            DownloadToFile: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            OpenFile: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            OpenUrl: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        }
    },
    Interactivity: {
        Object: {
            Highlight: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        },
        Structure: {
            Highlight: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
            Select: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])()
        },
        ClearHighlights: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
    },
    Layout: {
        Update: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])()
    },
    Toast: {
        Show: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        Hide: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])()
    },
    Camera: {
        Reset: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        SetSnapshot: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        Focus: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])()
    },
    Canvas3D: {
        SetSettings: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])(),
        ResetSettings: Object(_command__WEBPACK_IMPORTED_MODULE_0__[/* PluginCommand */ "a"])()
    }
};
//# sourceMappingURL=commands.js.map

/***/ }),
/* 27 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ structure_element["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ bonds["a" /* Bond */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ structure_structure["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* reexport */ structure_unit["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "f", function() { return /* reexport */ symmetry["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* reexport */ properties["a" /* default */]; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* reexport */ rings["a" /* UnitRing */]; });
__webpack_require__.d(__webpack_exports__, "i", function() { return /* reexport */ rings["b" /* UnitRings */]; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ CifExportContext; });
__webpack_require__.d(__webpack_exports__, "k", function() { return /* reexport */ mmCIF_Export_Filters; });
__webpack_require__.d(__webpack_exports__, "j", function() { return /* reexport */ encode_mmCIF_categories; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element.js + 3 modules
var structure_element = __webpack_require__(129);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/structure.js + 6 modules
var structure_structure = __webpack_require__(112);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit.js + 2 modules
var structure_unit = __webpack_require__(37);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/symmetry.js
var symmetry = __webpack_require__(239);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds.js + 3 modules
var bonds = __webpack_require__(159);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/properties.js
var properties = __webpack_require__(168);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/rings.js + 1 modules
var rings = __webpack_require__(201);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/writer/cif.js + 6 modules
var cif = __webpack_require__(62);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/atom_site.js
var atom_site = __webpack_require__(251);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/secondary-structure.js
var secondary_structure = __webpack_require__(280);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/secondary-structure.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var CifField = cif["a" /* CifWriter */].Field;


var _struct_conf = {
    name: 'struct_conf',
    instance: function (ctx) {
        var elements = findElements(ctx, 'helix');
        return {
            fields: struct_conf_fields,
            source: [{ data: elements, rowCount: elements.length }]
        };
    }
};
var _struct_sheet_range = {
    name: 'struct_sheet_range',
    instance: function (ctx) {
        var elements = findElements(ctx, 'sheet').sort(compare_ssr);
        return {
            fields: struct_sheet_range_fields,
            source: [{ data: elements, rowCount: elements.length }]
        };
    }
};
function compare_ssr(x, y) {
    var a = x.element, b = y.element;
    return a.sheet_id < b.sheet_id ? -1 : a.sheet_id === b.sheet_id ? x.start.element - y.start.element : 1;
}
;
var struct_conf_fields = Object(tslib_es6["__spreadArrays"])([
    CifField.str('conf_type_id', function (i, data) { return data[i].element.type_id; }),
    CifField.str('id', function (i, data, idx) { return "" + data[i].element.type_id + (idx + 1); })
], Object(atom_site["b" /* residueIdFields */])(function (i, e) { return e[i].start; }, { prefix: 'beg' }), Object(atom_site["b" /* residueIdFields */])(function (i, e) { return e[i].end; }, { prefix: 'end' }), [
    CifField.str('pdbx_PDB_helix_class', function (i, data) { return data[i].element.helix_class; }),
    CifField.str('details', function (i, data) { return data[i].element.details || ''; }, {
        valueKind: function (i, d) { return !!d[i].element.details ? 0 /* Present */ : 2 /* Unknown */; }
    }),
    CifField.int('pdbx_PDB_helix_length', function (i, data) { return data[i].length; })
]);
var struct_sheet_range_fields = Object(tslib_es6["__spreadArrays"])([
    CifField.str('sheet_id', function (i, data) { return data[i].element.sheet_id; }),
    CifField.index('id')
], Object(atom_site["b" /* residueIdFields */])(function (i, e) { return e[i].start; }, { prefix: 'beg' }), Object(atom_site["b" /* residueIdFields */])(function (i, e) { return e[i].end; }, { prefix: 'end' }), [
    CifField.str('symmetry', function (i, data) { return ''; }, { valueKind: function (i, d) { return 2 /* Unknown */; } })
]);
function findElements(ctx, kind) {
    // TODO: encode secondary structure for different models?
    var secondaryStructure = secondary_structure["a" /* ModelSecondaryStructure */].Provider.get(ctx.firstModel);
    if (!secondaryStructure)
        return [];
    var key = secondaryStructure.key, elements = secondaryStructure.elements;
    var ssElements = [];
    var structure = ctx.structures[0];
    for (var _i = 0, _a = structure.units; _i < _a.length; _i++) {
        var unit = _a[_i];
        // currently can only support this for "identity" operators.
        if (!structure_unit["a" /* default */].isAtomic(unit) || !unit.conformation.operator.isIdentity)
            continue;
        var segs = unit.model.atomicHierarchy.residueAtomSegments;
        var residues = mol_data_int["Segmentation"].transientSegments(segs, unit.elements);
        var current = void 0, move = true;
        while (residues.hasNext) {
            if (move)
                current = residues.move();
            var start = current.index;
            var startIdx = key[start];
            var element = elements[startIdx];
            if (element.kind !== kind) {
                move = true;
                continue;
            }
            var prev = start;
            while (residues.hasNext) {
                prev = current.index;
                current = residues.move();
                if (startIdx !== key[current.index]) {
                    move = false;
                    ssElements[ssElements.length] = {
                        start: structure_element["a" /* default */].Location.create(structure, unit, segs.offsets[start]),
                        end: structure_element["a" /* default */].Location.create(structure, unit, segs.offsets[prev]),
                        length: prev - start + 1,
                        element: element
                    };
                    break;
                }
            }
        }
    }
    return ssElements;
}
//# sourceMappingURL=secondary-structure.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var set = __webpack_require__(90);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js + 8 modules
var reader_cif = __webpack_require__(31);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/utils.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






function getModelMmCifCategory(model, name) {
    if (!mmcif["MmcifFormat"].is(model.sourceData))
        return;
    return model.sourceData.data.db[name];
}
function getUniqueResidueNamesFromStructures(structures) {
    return set["a" /* SetUtils */].unionMany.apply(set["a" /* SetUtils */], structures.map(function (s) { return s.uniqueResidueNames; }));
}
function getUniqueEntityIdsFromStructures(structures) {
    if (structures.length === 0)
        return new Set();
    var names = structures[0].model.entities.data.id;
    return new Set(getUniqueEntityIndicesFromStructures(structures).map(function (i) { return names.value(i); }));
}
function getUniqueEntityIndicesFromStructures(structures) {
    if (structures.length === 0)
        return [];
    if (structures.length === 1)
        return structures[0].entityIndices;
    var ret = generic["c" /* UniqueArray */].create();
    for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
        var s = structures_1[_i];
        for (var _a = 0, _b = s.entityIndices; _a < _b.length; _a++) {
            var e = _b[_a];
            generic["c" /* UniqueArray */].add(ret, e, e);
        }
    }
    Object(util["q" /* sortArray */])(ret.array);
    return ret.array;
}
function copy_mmCif_category(name, condition) {
    return {
        name: name,
        instance: function (_a) {
            var structures = _a.structures;
            if (condition && !condition(structures[0]))
                return cif["a" /* CifWriter */].Category.Empty;
            var model = structures[0].model;
            if (!mmcif["MmcifFormat"].is(model.sourceData))
                return cif["a" /* CifWriter */].Category.Empty;
            var table = model.sourceData.data.db[name];
            if (!table || !table._rowCount)
                return cif["a" /* CifWriter */].Category.Empty;
            return cif["a" /* CifWriter */].Category.ofTable(table);
        }
    };
}
function copy_source_mmCifCategory(encoder, ctx, category) {
    if (!mmcif["MmcifFormat"].is(ctx.firstModel.sourceData))
        return;
    var fs = cif["a" /* CifWriter */].fields();
    if (encoder.isBinary) {
        for (var _i = 0, _a = category.fieldNames; _i < _a.length; _i++) {
            var f = _a[_i];
            // TODO: this could be optimized
            var field = classifyField(f, category.getField(f));
            fs.add(field);
        }
    }
    else {
        var _loop_1 = function (f) {
            var field = category.getField(f);
            fs.str(f, function (row) { return field.str(row); });
        };
        for (var _b = 0, _c = category.fieldNames; _b < _c.length; _b++) {
            var f = _c[_b];
            _loop_1(f);
        }
    }
    var fields = fs.getFields();
    return {
        name: category.name,
        instance: function () {
            return { fields: fields, source: [{ data: void 0, rowCount: category.rowCount }] };
        }
    };
}
function classifyField(name, field) {
    var type = Object(reader_cif["d" /* getCifFieldType */])(field);
    if (type['@type'] === 'str') {
        return { name: name, type: 0 /* Str */, value: field.str, valueKind: field.valueKind };
    }
    else if (type['@type'] === 'float') {
        return cif["a" /* CifWriter */].Field.float(name, field.float, { valueKind: field.valueKind, typedArray: Float64Array });
    }
    else {
        return cif["a" /* CifWriter */].Field.int(name, field.int, { valueKind: field.valueKind, typedArray: Int32Array });
    }
}
//# sourceMappingURL=utils.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/misc.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var CifCategory = cif["a" /* CifWriter */].Category;
var _chem_comp = {
    name: 'chem_comp',
    instance: function (_a) {
        var firstModel = _a.firstModel, structures = _a.structures, cache = _a.cache;
        var chem_comp = getModelMmCifCategory(structures[0].model, 'chem_comp');
        if (!chem_comp)
            return CifCategory.Empty;
        var id = chem_comp.id;
        var names = cache.uniqueResidueNames || (cache.uniqueResidueNames = getUniqueResidueNamesFromStructures(structures));
        var indices = db["Column"].indicesOf(id, function (id) { return names.has(id); });
        return CifCategory.ofTable(chem_comp, indices);
    }
};
var _pdbx_chem_comp_identifier = {
    name: 'pdbx_chem_comp_identifier',
    instance: function (_a) {
        var firstModel = _a.firstModel, structures = _a.structures, cache = _a.cache;
        var pdbx_chem_comp_identifier = getModelMmCifCategory(firstModel, 'pdbx_chem_comp_identifier');
        if (!pdbx_chem_comp_identifier)
            return CifCategory.Empty;
        var comp_id = pdbx_chem_comp_identifier.comp_id;
        var names = cache.uniqueResidueNames || (cache.uniqueResidueNames = getUniqueResidueNamesFromStructures(structures));
        var indices = db["Column"].indicesOf(comp_id, function (id) { return names.has(id); });
        return CifCategory.ofTable(pdbx_chem_comp_identifier, indices);
    }
};
var _pdbx_nonpoly_scheme = {
    name: 'pdbx_nonpoly_scheme',
    instance: function (_a) {
        var firstModel = _a.firstModel, structures = _a.structures, cache = _a.cache;
        var pdbx_nonpoly_scheme = getModelMmCifCategory(firstModel, 'pdbx_nonpoly_scheme');
        if (!pdbx_nonpoly_scheme)
            return CifCategory.Empty;
        // TODO: filter?
        return CifCategory.ofTable(pdbx_nonpoly_scheme);
    }
};
//# sourceMappingURL=misc.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/sequence.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var sequence_CifCategory = cif["a" /* CifWriter */].Category;
var _struct_asym = createCategory('struct_asym');
var _entity_poly = createCategory('entity_poly');
var _entity_poly_seq = createCategory('entity_poly_seq');
function createCategory(categoryName) {
    return {
        name: categoryName,
        instance: function (_a) {
            var structures = _a.structures, cache = _a.cache;
            return getCategoryInstance(structures, categoryName, cache);
        }
    };
}
function getCategoryInstance(structures, categoryName, cache) {
    var category = getModelMmCifCategory(structures[0].model, categoryName);
    if (!category)
        return sequence_CifCategory.Empty;
    var entity_id = category.entity_id;
    var names = cache.uniqueEntityIds || (cache.uniqueEntityIds = getUniqueEntityIdsFromStructures(structures));
    var indices = db["Column"].indicesOf(entity_id, function (id) { return names.has(id); });
    return sequence_CifCategory.ofTable(category, indices);
}
//# sourceMappingURL=sequence.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/atom_site_operator_mapping.js
var atom_site_operator_mapping = __webpack_require__(326);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/export/mmcif.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var mmcif_CifCategory = cif["a" /* CifWriter */].Category;







var CifExportContext;
(function (CifExportContext) {
    function create(structures) {
        var structureArray = Array.isArray(structures) ? structures : [structures];
        return {
            structures: structureArray,
            firstModel: structureArray[0].model,
            cache: Object.create(null)
        };
    }
    CifExportContext.create = create;
})(CifExportContext || (CifExportContext = {}));
var _entity = {
    name: 'entity',
    instance: function (_a) {
        var structures = _a.structures;
        var indices = getUniqueEntityIndicesFromStructures(structures);
        return mmcif_CifCategory.ofTable(structures[0].model.entities.data, indices);
    }
};
function isWithoutSymmetry(structure) {
    return structure.units.every(function (u) { return u.conformation.operator.isIdentity; });
}
var Categories = [
    // Basics
    copy_mmCif_category('entry'),
    copy_mmCif_category('exptl'),
    _entity,
    // Symmetry
    copy_mmCif_category('cell', isWithoutSymmetry),
    copy_mmCif_category('symmetry', isWithoutSymmetry),
    // Assemblies
    copy_mmCif_category('pdbx_struct_assembly', isWithoutSymmetry),
    copy_mmCif_category('pdbx_struct_assembly_gen', isWithoutSymmetry),
    copy_mmCif_category('pdbx_struct_oper_list', isWithoutSymmetry),
    // Secondary structure
    _struct_conf,
    _struct_sheet_range,
    // Sequence
    _struct_asym,
    _entity_poly,
    _entity_poly_seq,
    // Branch
    copy_mmCif_category('pdbx_entity_branch'),
    copy_mmCif_category('pdbx_entity_branch_link'),
    copy_mmCif_category('pdbx_branch_scheme'),
    // Misc
    // TODO: filter for actual present residues?
    _chem_comp,
    _pdbx_chem_comp_identifier,
    copy_mmCif_category('atom_sites'),
    _pdbx_nonpoly_scheme,
    // Atoms
    atom_site["a" /* _atom_site */]
];
var _Filters;
(function (_Filters) {
    _Filters.AtomSitePositionsFieldNames = new Set(['id', 'Cartn_x', 'Cartn_y', 'Cartn_z']);
})(_Filters || (_Filters = {}));
var mmCIF_Export_Filters = {
    onlyPositions: {
        includeCategory: function (name) { return name === 'atom_site'; },
        includeField: function (cat, field) { return _Filters.AtomSitePositionsFieldNames.has(field); }
    }
};
function getCustomPropCategories(customProp, ctx, params) {
    var _a;
    if (!customProp.cifExport || customProp.cifExport.categories.length === 0)
        return [];
    var prefix = customProp.cifExport.prefix;
    var cats = customProp.cifExport.categories;
    var propCtx = ctx;
    if (customProp.cifExport.context) {
        var propId = custom_property["CustomPropertyDescriptor"].getUUID(customProp);
        if (ctx.cache[propId + '__ctx'])
            propCtx = ctx.cache[propId + '__ctx'];
        else {
            propCtx = customProp.cifExport.context(ctx) || ctx;
            ctx.cache[propId + '__ctx'] = propCtx;
        }
    }
    var ret = [];
    for (var _i = 0, cats_1 = cats; _i < cats_1.length; _i++) {
        var cat = cats_1[_i];
        if ((_a = params === null || params === void 0 ? void 0 : params.skipCategoryNames) === null || _a === void 0 ? void 0 : _a.has(cat.name))
            continue;
        if (cat.name.indexOf(prefix) !== 0)
            throw new Error("Custom category '" + cat.name + "' name must start with prefix '" + prefix + ".'");
        ret.push([cat, propCtx]);
    }
    return ret;
}
/** Doesn't start a data block */
function encode_mmCIF_categories(encoder, structures, params) {
    var first = Array.isArray(structures) ? structures[0] : structures;
    var models = first.models;
    if (models.length !== 1)
        throw 'Can\'t export stucture composed from multiple models.';
    var ctx = (params === null || params === void 0 ? void 0 : params.exportCtx) || CifExportContext.create(structures);
    if ((params === null || params === void 0 ? void 0 : params.copyAllCategories) && mmcif["MmcifFormat"].is(models[0].sourceData)) {
        encode_mmCIF_categories_copyAll(encoder, ctx);
    }
    else {
        encode_mmCIF_categories_default(encoder, ctx, params);
    }
}
function encode_mmCIF_categories_default(encoder, ctx, params) {
    var _a;
    for (var _i = 0, Categories_1 = Categories; _i < Categories_1.length; _i++) {
        var cat = Categories_1[_i];
        if ((params === null || params === void 0 ? void 0 : params.skipCategoryNames) && (params === null || params === void 0 ? void 0 : params.skipCategoryNames.has(cat.name)))
            continue;
        encoder.writeCategory(cat, ctx);
    }
    if (!((_a = params === null || params === void 0 ? void 0 : params.skipCategoryNames) === null || _a === void 0 ? void 0 : _a.has('atom_site')) && encoder.isCategoryIncluded('atom_site')) {
        var info = Object(atom_site_operator_mapping["b" /* atom_site_operator_mapping */])(ctx);
        if (info)
            encoder.writeCategory(info[0], info[1], info[2]);
    }
    var _params = params || {};
    for (var _b = 0, _c = ctx.firstModel.customProperties.all; _b < _c.length; _b++) {
        var customProp = _c[_b];
        for (var _d = 0, _e = getCustomPropCategories(customProp, ctx, _params); _d < _e.length; _d++) {
            var _f = _e[_d], cat = _f[0], propCtx = _f[1];
            encoder.writeCategory(cat, propCtx);
        }
    }
    for (var _g = 0, _h = ctx.structures; _g < _h.length; _g++) {
        var s = _h[_g];
        if (!s.hasCustomProperties)
            continue;
        for (var _j = 0, _k = s.customPropertyDescriptors.all; _j < _k.length; _j++) {
            var customProp = _k[_j];
            for (var _l = 0, _m = getCustomPropCategories(customProp, ctx, _params); _l < _m.length; _l++) {
                var _o = _m[_l], cat = _o[0], propCtx = _o[1];
                encoder.writeCategory(cat, propCtx);
            }
        }
    }
}
function encode_mmCIF_categories_copyAll(encoder, ctx) {
    var providedCategories = new Map();
    for (var _i = 0, Categories_2 = Categories; _i < Categories_2.length; _i++) {
        var cat = Categories_2[_i];
        providedCategories.set(cat.name, [cat, ctx]);
    }
    var mapping = Object(atom_site_operator_mapping["b" /* atom_site_operator_mapping */])(ctx);
    if (mapping)
        providedCategories.set(mapping[0].name, mapping);
    for (var _a = 0, _b = ctx.firstModel.customProperties.all; _a < _b.length; _a++) {
        var customProp = _b[_a];
        for (var _c = 0, _d = getCustomPropCategories(customProp, ctx); _c < _d.length; _c++) {
            var info = _d[_c];
            providedCategories.set(info[0].name, info);
        }
    }
    for (var _e = 0, _f = ctx.structures; _e < _f.length; _e++) {
        var s = _f[_e];
        if (!s.hasCustomProperties)
            continue;
        for (var _g = 0, _h = s.customPropertyDescriptors.all; _g < _h.length; _g++) {
            var customProp = _h[_g];
            for (var _j = 0, _k = getCustomPropCategories(customProp, ctx); _j < _k.length; _j++) {
                var info = _k[_j];
                providedCategories.set(info[0].name, info);
            }
        }
    }
    var handled = new Set();
    var data = ctx.firstModel.sourceData.data;
    for (var _l = 0, _m = data.frame.categoryNames; _l < _m.length; _l++) {
        var catName = _m[_l];
        handled.add(catName);
        if (providedCategories.has(catName)) {
            var info = providedCategories.get(catName);
            encoder.writeCategory(info[0], info[1], info[2]);
        }
        else {
            if (data.db[catName]) {
                var cat = copy_mmCif_category(catName);
                encoder.writeCategory(cat, ctx);
            }
            else {
                var cat = copy_source_mmCifCategory(encoder, ctx, data.frame.categories[catName]);
                if (cat)
                    encoder.writeCategory(cat);
            }
        }
    }
    providedCategories.forEach(function (info, name) {
        if (!handled.has(name))
            encoder.writeCategory(info[0], info[1], info[2]);
    });
}
function to_mmCIF(name, structure, asBinary) {
    if (asBinary === void 0) { asBinary = false; }
    var enc = cif["a" /* CifWriter */].createEncoder({ binary: asBinary });
    enc.startDataBlock(name);
    encode_mmCIF_categories(enc, structure);
    return enc.getData();
}
/* harmony default export */ var export_mmcif = (to_mmCIF);
//# sourceMappingURL=mmcif.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */









//# sourceMappingURL=structure.js.map

/***/ }),
/* 28 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StateTransforms", function() { return /* binding */ StateTransforms; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin-state/transforms/misc.js
var misc_namespaceObject = {};
__webpack_require__.r(misc_namespaceObject);
__webpack_require__.d(misc_namespaceObject, "CreateGroup", function() { return CreateGroup; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin-state/transforms/volume.js
var volume_namespaceObject = {};
__webpack_require__.r(volume_namespaceObject);
__webpack_require__.d(volume_namespaceObject, "VolumeFromCcp4", function() { return VolumeFromCcp4; });
__webpack_require__.d(volume_namespaceObject, "VolumeFromDsn6", function() { return VolumeFromDsn6; });
__webpack_require__.d(volume_namespaceObject, "VolumeFromCube", function() { return VolumeFromCube; });
__webpack_require__.d(volume_namespaceObject, "VolumeFromDx", function() { return VolumeFromDx; });
__webpack_require__.d(volume_namespaceObject, "AssignColorVolume", function() { return AssignColorVolume; });
__webpack_require__.d(volume_namespaceObject, "VolumeFromDensityServerCif", function() { return VolumeFromDensityServerCif; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/data.js + 6 modules
var transforms_data = __webpack_require__(288);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/misc.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var CreateGroup = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'create-group',
    display: { name: 'Group' },
    from: [],
    to: objects["a" /* PluginStateObject */].Group,
    params: {
        label: param_definition["ParamDefinition"].Text('Group'),
        description: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(''))
    }
})({
    apply: function (_a) {
        var params = _a.params;
        return new objects["a" /* PluginStateObject */].Group({}, params);
    },
    update: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (Object(mol_util["m" /* shallowEqualObjects */])(oldParams, newParams))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.label = newParams.label;
        b.description = newParams.description;
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
//# sourceMappingURL=misc.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/model.js + 35 modules
var model = __webpack_require__(316);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js + 8 modules
var cif = __webpack_require__(31);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/misc.js
var misc = __webpack_require__(46);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/ccp4/parser.js
var parser = __webpack_require__(365);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/typed-array.js
var typed_array = __webpack_require__(193);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/ccp4.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









/** When available (e.g. in MRC files) use ORIGIN records instead of N[CRS]START */
function getCcp4Origin(header) {
    if (header.originX === 0.0 && header.originY === 0.0 && header.originZ === 0.0) {
        return linear_algebra["Vec3"].create(header.NCSTART, header.NRSTART, header.NSSTART);
    }
    else {
        return linear_algebra["Vec3"].create(header.originX / (header.xLength / header.NX), header.originY / (header.yLength / header.NY), header.originZ / (header.zLength / header.NZ));
    }
}
function getTypedArrayCtor(header) {
    var valueType = Object(parser["a" /* getCcp4ValueType */])(header);
    switch (valueType) {
        case typed_array["a" /* TypedArrayValueType */].Float32: return Float32Array;
        case typed_array["a" /* TypedArrayValueType */].Int8: return Int8Array;
        case typed_array["a" /* TypedArrayValueType */].Int16: return Int16Array;
        case typed_array["a" /* TypedArrayValueType */].Uint16: return Uint16Array;
    }
    throw Error(valueType + " is not a supported value format.");
}
function volumeFromCcp4(source, params) {
    var _this = this;
    return mol_task["b" /* Task */].create('Create Volume', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var header, values, size, angles, spacegroup, cell, axis_order_fast_to_slow, normalizeOrder, grid, extent, origin, gridOrigin, origin_frac, dimensions_frac, space, data, calcStats;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            header = source.header, values = source.values;
            size = linear_algebra["Vec3"].create(header.xLength, header.yLength, header.zLength);
            if (params && params.voxelSize)
                linear_algebra["Vec3"].mul(size, size, params.voxelSize);
            angles = linear_algebra["Vec3"].create(Object(misc["c" /* degToRad */])(header.alpha), Object(misc["c" /* degToRad */])(header.beta), Object(misc["c" /* degToRad */])(header.gamma));
            spacegroup = header.ISPG > 65536 ? 0 : header.ISPG;
            cell = geometry["f" /* SpacegroupCell */].create(spacegroup || 'P 1', size, angles);
            axis_order_fast_to_slow = linear_algebra["Vec3"].create(header.MAPC - 1, header.MAPR - 1, header.MAPS - 1);
            normalizeOrder = linear_algebra["Tensor"].convertToCanonicalAxisIndicesFastToSlow(axis_order_fast_to_slow);
            grid = [header.NX, header.NY, header.NZ];
            extent = normalizeOrder([header.NC, header.NR, header.NS]);
            origin = getCcp4Origin(header);
            if (params === null || params === void 0 ? void 0 : params.offset)
                linear_algebra["Vec3"].add(origin, origin, params.offset);
            gridOrigin = normalizeOrder(origin);
            origin_frac = linear_algebra["Vec3"].create(gridOrigin[0] / grid[0], gridOrigin[1] / grid[1], gridOrigin[2] / grid[2]);
            dimensions_frac = linear_algebra["Vec3"].create(extent[0] / grid[0], extent[1] / grid[1], extent[2] / grid[2]);
            space = linear_algebra["Tensor"].Space(extent, linear_algebra["Tensor"].invertAxisOrder(axis_order_fast_to_slow), getTypedArrayCtor(header));
            data = linear_algebra["Tensor"].create(space, linear_algebra["Tensor"].Data1(values));
            calcStats = header.AMIN === 0 && header.AMAX === 0 && header.AMEAN === 0 && header.ARMS === 0;
            return [2 /*return*/, {
                    label: params === null || params === void 0 ? void 0 : params.label,
                    grid: {
                        transform: { kind: 'spacegroup', cell: cell, fractionalBox: geometry["b" /* Box3D */].create(origin_frac, linear_algebra["Vec3"].add(linear_algebra["Vec3"].zero(), origin_frac, dimensions_frac)) },
                        cells: data,
                        stats: {
                            min: (isNaN(header.AMIN) || calcStats) ? Object(array["arrayMin"])(values) : header.AMIN,
                            max: (isNaN(header.AMAX) || calcStats) ? Object(array["arrayMax"])(values) : header.AMAX,
                            mean: (isNaN(header.AMEAN) || calcStats) ? Object(array["arrayMean"])(values) : header.AMEAN,
                            sigma: (isNaN(header.ARMS) || header.ARMS === 0) ? Object(array["arrayRms"])(values) : header.ARMS
                        },
                    },
                    sourceData: Ccp4Format.create(source),
                    customProperties: new custom_property["CustomProperties"](),
                    _propertyData: Object.create(null),
                }];
        });
    }); });
}
//

var Ccp4Format;
(function (Ccp4Format) {
    function is(x) {
        return x.kind === 'ccp4';
    }
    Ccp4Format.is = is;
    function create(ccp4) {
        return { kind: 'ccp4', name: ccp4.name, data: ccp4 };
    }
    Ccp4Format.create = create;
})(Ccp4Format || (Ccp4Format = {}));
//# sourceMappingURL=ccp4.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/density-server.js
var density_server = __webpack_require__(363);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/dsn6.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







function volumeFromDsn6(source, params) {
    var _this = this;
    return mol_task["b" /* Task */].create('Create Volume', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var header, values, size, angles, cell, grid, extent, gridOrigin, origin_frac, dimensions_frac, space, data;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            header = source.header, values = source.values;
            size = linear_algebra["Vec3"].create(header.xlen, header.ylen, header.zlen);
            if (params && params.voxelSize)
                linear_algebra["Vec3"].mul(size, size, params.voxelSize);
            angles = linear_algebra["Vec3"].create(Object(misc["c" /* degToRad */])(header.alpha), Object(misc["c" /* degToRad */])(header.beta), Object(misc["c" /* degToRad */])(header.gamma));
            cell = geometry["f" /* SpacegroupCell */].create('P 1', size, angles);
            grid = [header.xRate, header.yRate, header.zRate];
            extent = [header.xExtent, header.yExtent, header.zExtent];
            gridOrigin = [header.xStart, header.yStart, header.zStart];
            origin_frac = linear_algebra["Vec3"].create(gridOrigin[0] / grid[0], gridOrigin[1] / grid[1], gridOrigin[2] / grid[2]);
            dimensions_frac = linear_algebra["Vec3"].create(extent[0] / grid[0], extent[1] / grid[1], extent[2] / grid[2]);
            space = linear_algebra["Tensor"].Space(extent, [0, 1, 2], Float32Array);
            data = linear_algebra["Tensor"].create(space, linear_algebra["Tensor"].Data1(values));
            return [2 /*return*/, {
                    label: params === null || params === void 0 ? void 0 : params.label,
                    grid: {
                        transform: { kind: 'spacegroup', cell: cell, fractionalBox: geometry["b" /* Box3D */].create(origin_frac, linear_algebra["Vec3"].add(linear_algebra["Vec3"].zero(), origin_frac, dimensions_frac)) },
                        cells: data,
                        stats: {
                            min: Object(array["arrayMin"])(values),
                            max: Object(array["arrayMax"])(values),
                            mean: Object(array["arrayMean"])(values),
                            sigma: header.sigma !== undefined ? header.sigma : Object(array["arrayRms"])(values)
                        },
                    },
                    sourceData: Dsn6Format.create(source),
                    customProperties: new custom_property["CustomProperties"](),
                    _propertyData: Object.create(null),
                }];
        });
    }); });
}
//

var Dsn6Format;
(function (Dsn6Format) {
    function is(x) {
        return x.kind === 'dsn6';
    }
    Dsn6Format.is = is;
    function create(dsn6) {
        return { kind: 'dsn6', name: dsn6.name, data: dsn6 };
    }
    Dsn6Format.create = create;
})(Dsn6Format || (Dsn6Format = {}));
//# sourceMappingURL=dsn6.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/cube.js
var cube = __webpack_require__(354);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/dx.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function volumeFromDx(source, params) {
    var _this = this;
    return mol_task["b" /* Task */].create('Create Volume', function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var header, values, space, data, matrix, basis;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            header = source.header, values = source.values;
            space = linear_algebra["Tensor"].Space(header.dim, [0, 1, 2], Float64Array);
            data = linear_algebra["Tensor"].create(space, linear_algebra["Tensor"].Data1(values));
            matrix = linear_algebra["Mat4"].fromTranslation(Object(linear_algebra["Mat4"])(), header.min);
            basis = linear_algebra["Mat4"].fromScaling(Object(linear_algebra["Mat4"])(), header.h);
            linear_algebra["Mat4"].mul(matrix, matrix, basis);
            return [2 /*return*/, {
                    label: params === null || params === void 0 ? void 0 : params.label,
                    grid: {
                        transform: { kind: 'matrix', matrix: matrix },
                        cells: data,
                        stats: {
                            min: Object(array["arrayMin"])(values),
                            max: Object(array["arrayMax"])(values),
                            mean: Object(array["arrayMean"])(values),
                            sigma: Object(array["arrayRms"])(values)
                        },
                    },
                    sourceData: DxFormat.create(source),
                    customProperties: new custom_property["CustomProperties"](),
                    _propertyData: Object.create(null),
                }];
        });
    }); });
}
//

var DxFormat;
(function (DxFormat) {
    function is(x) {
        return x.kind === 'dx';
    }
    DxFormat.is = is;
    function create(dx) {
        return { kind: 'dx', name: dx.name, data: dx };
    }
    DxFormat.create = create;
})(DxFormat || (DxFormat = {}));
//# sourceMappingURL=dx.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/volume.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















var VolumeFromCcp4 = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-from-ccp4',
    display: { name: 'Volume from CCP4/MRC/MAP', description: 'Create Volume from CCP4/MRC/MAP data' },
    from: objects["a" /* PluginStateObject */].Format.Ccp4,
    to: objects["a" /* PluginStateObject */].Volume.Data,
    params: function (a) {
        return {
            voxelSize: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(1, 1, 1)),
            offset: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(0, 0, 0))
        };
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Create volume from CCP4/MRC/MAP', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var volume, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, volumeFromCcp4(a.data, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { label: a.data.name || a.label })).runInContext(ctx)];
                    case 1:
                        volume = _a.sent();
                        props = { label: volume.label || 'Volume', description: "Volume " + a.data.header.NX + "\u00D7" + a.data.header.NX + "\u00D7" + a.data.header.NX };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
                }
            });
        }); });
    }
});
var VolumeFromDsn6 = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-from-dsn6',
    display: { name: 'Volume from DSN6/BRIX', description: 'Create Volume from DSN6/BRIX data' },
    from: objects["a" /* PluginStateObject */].Format.Dsn6,
    to: objects["a" /* PluginStateObject */].Volume.Data,
    params: function (a) {
        return {
            voxelSize: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(1, 1, 1))
        };
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Create volume from DSN6/BRIX', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var volume, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, volumeFromDsn6(a.data, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { label: a.data.name || a.label })).runInContext(ctx)];
                    case 1:
                        volume = _a.sent();
                        props = { label: volume.label || 'Volume', description: "Volume " + a.data.header.xExtent + "\u00D7" + a.data.header.yExtent + "\u00D7" + a.data.header.zExtent };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
                }
            });
        }); });
    }
});
var VolumeFromCube = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-from-cube',
    display: { name: 'Volume from Cube', description: 'Create Volume from Cube data' },
    from: objects["a" /* PluginStateObject */].Format.Cube,
    to: objects["a" /* PluginStateObject */].Volume.Data,
    params: function (a) {
        if (!a)
            return { dataIndex: param_definition["ParamDefinition"].Numeric(0) };
        return {
            dataIndex: param_definition["ParamDefinition"].Select(0, a.data.header.dataSetIds.map(function (id, i) { return [i, "" + id]; }))
        };
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Create volume from Cube', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var volume, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, Object(cube["b" /* volumeFromCube */])(a.data, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { label: a.data.name || a.label })).runInContext(ctx)];
                    case 1:
                        volume = _a.sent();
                        props = { label: volume.label || 'Volume', description: "Volume " + a.data.header.dim[0] + "\u00D7" + a.data.header.dim[1] + "\u00D7" + a.data.header.dim[2] };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
                }
            });
        }); });
    }
});
var VolumeFromDx = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-from-dx',
    display: { name: 'Parse DX', description: 'Create volume from DX data.' },
    from: objects["a" /* PluginStateObject */].Format.Dx,
    to: objects["a" /* PluginStateObject */].Volume.Data
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse DX', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var volume, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        console.log(a);
                        return [4 /*yield*/, volumeFromDx(a.data, { label: a.data.name || a.label }).runInContext(ctx)];
                    case 1:
                        volume = _a.sent();
                        props = { label: volume.label || 'Volume', description: "Volume " + a.data.header.dim[0] + "\u00D7" + a.data.header.dim[1] + "\u00D7" + a.data.header.dim[2] };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
                }
            });
        }); });
    }
});
var VolumeFromDensityServerCif = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-from-density-server-cif',
    display: { name: 'Volume from density-server CIF', description: 'Identify and create all separate models in the specified CIF data block' },
    from: objects["a" /* PluginStateObject */].Format.Cif,
    to: objects["a" /* PluginStateObject */].Volume.Data,
    params: function (a) {
        if (!a) {
            return {
                blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.' }))
            };
        }
        var blocks = a.data.blocks.slice(1); // zero block contains query meta-data
        return {
            blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Select(blocks[0] && blocks[0].header, blocks.map(function (b) { return [b.header, b.header]; }), { description: 'Header of the block to parse' }))
        };
    }
})({
    isApplicable: function (a) { return a.data.blocks.length > 0; },
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Parse density-server CIF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var header, block, densityServerCif, volume, _a, x, y, z, props;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        header = params.blockHeader || a.data.blocks[1].header;
                        block = a.data.blocks.find(function (b) { return b.header === header; });
                        if (!block)
                            throw new Error("Data block '" + [header] + "' not found.");
                        densityServerCif = cif["a" /* CIF */].schema.densityServer(block);
                        return [4 /*yield*/, Object(density_server["a" /* volumeFromDensityServerData */])(densityServerCif).runInContext(ctx)];
                    case 1:
                        volume = _b.sent();
                        _a = volume.grid.cells.space.dimensions, x = _a[0], y = _a[1], z = _a[2];
                        props = { label: densityServerCif.volume_data_3d_info.name.value(0), description: "Volume " + x + "\u00D7" + y + "\u00D7" + z };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
                }
            });
        }); });
    }
});
var AssignColorVolume = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'assign-color-volume',
    display: { name: 'Assign Color Volume', description: 'Assigns another volume to be available for coloring.' },
    from: objects["a" /* PluginStateObject */].Volume.Data,
    to: objects["a" /* PluginStateObject */].Volume.Data,
    isDecorator: true,
    params: function (a, plugin) {
        if (!a)
            return { ref: param_definition["ParamDefinition"].Text() };
        var cells = plugin.state.data.select(mol_state["StateSelection"].Generators.root.subtree().ofType(objects["a" /* PluginStateObject */].Volume.Data).filter(function (cell) { var _a; return !!cell.obj && !((_a = cell.obj) === null || _a === void 0 ? void 0 : _a.data.colorVolume) && cell.obj !== a; }));
        if (cells.length === 0)
            return { ref: param_definition["ParamDefinition"].Text('', { isHidden: true }) };
        return { ref: param_definition["ParamDefinition"].Select(cells[0].transform.ref, cells.map(function (c) { return [c.transform.ref, c.obj.label]; })) };
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params, dependencies = _a.dependencies;
        return mol_task["b" /* Task */].create('Assign Color Volume', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var colorVolume, volume, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                if (!dependencies || !dependencies[params.ref]) {
                    throw new Error('Dependency not available.');
                }
                colorVolume = dependencies[params.ref].data;
                volume = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, a.data), { colorVolume: colorVolume });
                props = { label: a.label, description: 'Volume + Colors' };
                return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Data(volume, props)];
            });
        }); });
    }
});
//# sourceMappingURL=volume.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/representation.js + 13 modules
var representation = __webpack_require__(198);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var StateTransforms = {
    Data: transforms_data,
    Misc: misc_namespaceObject,
    Model: model,
    Volume: volume_namespaceObject,
    Representation: representation
};
//# sourceMappingURL=transforms.js.map

/***/ }),
/* 29 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayMax", function() { return arrayMax; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayMin", function() { return arrayMin; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayMinMax", function() { return arrayMinMax; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arraySum", function() { return arraySum; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayMean", function() { return arrayMean; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayRms", function() { return arrayRms; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fillSerial", function() { return fillSerial; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayRemoveInPlace", function() { return arrayRemoveInPlace; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayRemoveAtInPlace", function() { return arrayRemoveAtInPlace; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arraySetAdd", function() { return arraySetAdd; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arraySetRemove", function() { return arraySetRemove; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayEqual", function() { return arrayEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "arrayIsIdentity", function() { return arrayIsIdentity; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// TODO move to mol-math as Vector???
/** Get the maximum value in an array */
function arrayMax(array) {
    var max = -Infinity;
    for (var i = 0, il = array.length; i < il; ++i) {
        if (array[i] > max)
            max = array[i];
    }
    return max;
}
/** Get the minimum value in an array */
function arrayMin(array) {
    var min = Infinity;
    for (var i = 0, il = array.length; i < il; ++i) {
        if (array[i] < min)
            min = array[i];
    }
    return min;
}
/** Get the minimum & maximum value in an array */
function arrayMinMax(array) {
    var min = Infinity;
    var max = -Infinity;
    for (var i = 0, il = array.length; i < il; ++i) {
        if (array[i] < min)
            min = array[i];
        if (array[i] > max)
            max = array[i];
    }
    return [min, max];
}
/** Get the sum of values in an array */
function arraySum(array, stride, offset) {
    if (stride === void 0) { stride = 1; }
    if (offset === void 0) { offset = 0; }
    var n = array.length;
    var sum = 0;
    for (var i = offset; i < n; i += stride) {
        sum += array[i];
    }
    return sum;
}
/** Get the mean of values in an array */
function arrayMean(array, stride, offset) {
    if (stride === void 0) { stride = 1; }
    if (offset === void 0) { offset = 0; }
    return arraySum(array, stride, offset) / (array.length / stride);
}
/** Get the root mean square of values in an array */
function arrayRms(array) {
    var n = array.length;
    var sumSq = 0;
    for (var i = 0; i < n; ++i) {
        var di = array[i];
        sumSq += di * di;
    }
    return Math.sqrt(sumSq / n);
}
/** Fill an array with serial numbers starting from 0 until n - 1 (defaults to array.length) */
function fillSerial(array, n) {
    for (var i = 0, il = n ? Math.min(n, array.length) : array.length; i < il; ++i)
        array[i] = i;
    return array;
}
function arrayRemoveInPlace(xs, x) {
    var i = 0, l = xs.length, found = false;
    for (; i < l; i++) {
        if (xs[i] === x) {
            found = true;
            break;
        }
    }
    if (!found)
        return false;
    arrayRemoveAtInPlace(xs, i);
    return true;
}
function arrayRemoveAtInPlace(xs, idx) {
    for (var i = idx, _i = xs.length - 1; i < _i; i++) {
        xs[i] = xs[i + 1];
    }
    xs.pop();
}
function arraySetAdd(xs, x) {
    if (xs.indexOf(x) >= 0)
        return false;
    xs.push(x);
    return true;
}
function arraySetRemove(xs, x) {
    var idx = xs.indexOf(x);
    if (idx < 0)
        return false;
    for (var i = idx, _i = xs.length - 1; i < _i; i++) {
        xs[i] = xs[i + 1];
    }
    xs.pop();
    return true;
}
function arrayEqual(xs, ys) {
    if (!xs || xs.length === 0)
        return !ys || ys.length === 0;
    if (!ys)
        return false;
    var lenX = xs.length;
    if (lenX !== ys.length)
        return false;
    for (var i = 0; i < lenX; i++) {
        if (xs[i] !== ys[i])
            return false;
    }
    return true;
}
function arrayIsIdentity(xs) {
    for (var i = 0, _i = xs.length; i < _i; i++) {
        if (xs[i] !== i)
            return false;
    }
    return true;
}
//# sourceMappingURL=array.js.map

/***/ }),
/* 30 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return typeSymbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return formalCharge; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return atomId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return altLoc; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return compId; });
/* unused harmony export interBondCount */
/* unused harmony export intraBondCount */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return bondCount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return bondToElementCount; });
/* unused harmony export intraConnectedTo */
/* unused harmony export interConnectedTo */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return connectedTo; });
/* unused harmony export eachInterBondedAtom */
/* unused harmony export eachIntraBondedAtom */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return eachBondedAtom; });
/* unused harmony export eachResidueAtom */
/* harmony import */ var _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function typeSymbol(unit, index) {
    return unit.model.atomicHierarchy.atoms.type_symbol.value(unit.elements[index]);
}
function formalCharge(unit, index) {
    return unit.model.atomicHierarchy.atoms.pdbx_formal_charge.value(unit.elements[index]);
}
function atomId(unit, index) {
    return unit.model.atomicHierarchy.atoms.label_atom_id.value(unit.elements[index]);
}
function altLoc(unit, index) {
    return unit.model.atomicHierarchy.atoms.label_alt_id.value(unit.elements[index]);
}
function compId(unit, index) {
    return unit.model.atomicHierarchy.atoms.label_comp_id.value(unit.elements[index]);
}
//
function interBondCount(structure, unit, index) {
    var count = 0;
    var indices = structure.interUnitBonds.getEdgeIndices(index, unit);
    for (var i = 0, il = indices.length; i < il; ++i) {
        var b = structure.interUnitBonds.edges[indices[i]];
        if (_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(b.props.flag))
            count += 1;
    }
    return count;
}
function intraBondCount(unit, index) {
    var count = 0;
    var _a = unit.bonds, offset = _a.offset, flags = _a.edgeProps.flags;
    for (var i = offset[index], il = offset[index + 1]; i < il; ++i) {
        if (_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(flags[i]))
            count += 1;
    }
    return count;
}
function bondCount(structure, unit, index) {
    return interBondCount(structure, unit, index) + intraBondCount(unit, index);
}
function bondToElementCount(structure, unit, index, element) {
    var count = 0;
    eachBondedAtom(structure, unit, index, function (unit, index) {
        if (typeSymbol(unit, index) === element)
            count += 1;
    });
    return count;
}
//
function intraConnectedTo(unit, indexA, indexB) {
    var _a = unit.bonds, offset = _a.offset, b = _a.b, flags = _a.edgeProps.flags;
    _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].is;
    for (var i = offset[indexA], il = offset[indexA + 1]; i < il; ++i) {
        if (b[i] === indexB && _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(flags[i]))
            return true;
    }
    return false;
}
function interConnectedTo(structure, unitA, indexA, unitB, indexB) {
    var b = structure.interUnitBonds.getEdge(indexA, unitA, indexB, unitB);
    return b && _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(b.props.flag);
}
function connectedTo(structure, unitA, indexA, unitB, indexB) {
    return unitA === unitB ? intraConnectedTo(unitA, indexA, indexB) : interConnectedTo(structure, unitA, indexA, unitB, indexB);
}
//
function eachInterBondedAtom(structure, unit, index, cb) {
    var indices = structure.interUnitBonds.getEdgeIndices(index, unit);
    for (var i = 0, il = indices.length; i < il; ++i) {
        var b = structure.interUnitBonds.edges[indices[i]];
        if (_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(b.props.flag))
            cb(b.unitB, b.indexB);
    }
}
function eachIntraBondedAtom(unit, index, cb) {
    var _a = unit.bonds, offset = _a.offset, b = _a.b, flags = _a.edgeProps.flags;
    for (var i = offset[index], il = offset[index + 1]; i < il; ++i) {
        if (_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["BondType"].isCovalent(flags[i]))
            cb(unit, b[i]);
    }
}
function eachBondedAtom(structure, unit, index, cb) {
    eachInterBondedAtom(structure, unit, index, cb);
    eachIntraBondedAtom(unit, index, cb);
}
//
function eachResidueAtom(unit, index, cb) {
    var offsets = unit.model.atomicHierarchy.residueAtomSegments.offsets;
    var rI = unit.getResidueIndex(index);
    for (var i = offsets[rI], il = offsets[rI + 1]; i < il; ++i) {
        // TODO optimize, avoid search with .indexOf
        var idx = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].indexOf(unit.elements, i);
        if (idx !== -1)
            cb(idx);
    }
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 31 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ CIF; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ data_model["b" /* CifCategory */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ data_model["c" /* CifField */]; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ data_model["f" /* getCifFieldType */]; });

// UNUSED EXPORTS: CifFile, CifBlock, CifSaveFrame, tensorFieldNameGetter, getTensor

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/data-model.js
var data_model = __webpack_require__(128);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/tokenizer.js
var text_tokenizer = __webpack_require__(20);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/result.js
var result = __webpack_require__(67);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/text/parser.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/**
 * mmCIF parser.
 *
 * Trying to be as close to the specification http://www.iucr.org/resources/cif/spec/version1.1/cifsyntax
 *
 * Differences I'm aware of:
 * - Except keywords (data_, loop_, save_) everything is case sensitive.
 * - The tokens . and ? are treated the same as the values '.' and '?'.
 * - Ignores \ in the multiline values:
 *     ;abc\
 *     efg
 *     ;
 *   should have the value 'abcefg' but will have the value 'abc\\nefg' instead.
 *   Post processing of this is left to the consumer of the data.
 * - Similarly, things like punctuation (\', ..) are left to be processed by the user if needed.
 *
 */




/**
 * Eat everything until a whitespace/newline occurs.
 */
function eatValue(state) {
    while (state.position < state.length) {
        switch (state.data.charCodeAt(state.position)) {
            case 9: // \t
            case 10: // \n
            case 13: // \r
            case 32: // ' '
                state.tokenEnd = state.position;
                return;
            default:
                ++state.position;
                break;
        }
    }
    state.tokenEnd = state.position;
}
/**
 * Eats an escaped value. Handles the "degenerate" cases as well.
 *
 * "Degenerate" cases:
 * - 'xx'x' => xx'x
 * - 'xxxNEWLINE => 'xxx
 *
 */
function eatEscaped(state, esc) {
    var next, c;
    ++state.position;
    while (state.position < state.length) {
        c = state.data.charCodeAt(state.position);
        if (c === esc) {
            next = state.data.charCodeAt(state.position + 1);
            switch (next) {
                case 9: // \t
                case 10: // \n
                case 13: // \r
                case 32: // ' '
                    // get rid of the quotes.
                    state.tokenStart++;
                    state.tokenEnd = state.position;
                    state.isEscaped = true;
                    ++state.position;
                    return;
                default:
                    if (next === void 0) { // = "end of stream"
                        // get rid of the quotes.
                        state.tokenStart++;
                        state.tokenEnd = state.position;
                        state.isEscaped = true;
                        ++state.position;
                        return;
                    }
                    ++state.position;
                    break;
            }
        }
        else {
            // handle 'xxxNEWLINE => 'xxx
            if (c === 10 || c === 13) {
                state.tokenEnd = state.position;
                return;
            }
            ++state.position;
        }
    }
    state.tokenEnd = state.position;
}
/**
 * Eats an escaped value "triple quote" (''') value.
 */
function eatTripleQuote(state) {
    // skip the '''
    state.position += 3;
    while (state.position < state.length) {
        if (state.data.charCodeAt(state.position) === 39 /* ' */ && isTripleQuoteAtPosition(state)) {
            // get rid of the quotes.
            state.tokenStart += 3;
            state.tokenEnd = state.position;
            state.isEscaped = true;
            state.position += 3;
            return;
        }
        ++state.position;
    }
    state.tokenEnd = state.position;
}
/**
 * Eats a multiline token of the form NL;....NL;
 */
function eatMultiline(state) {
    var prev = 59, pos = state.position + 1, c;
    while (pos < state.length) {
        c = state.data.charCodeAt(pos);
        if (c === 59 && (prev === 10 || prev === 13)) { // ;, \n \r
            state.position = pos + 1;
            // get rid of the ;
            state.tokenStart++;
            // remove trailing newlines
            pos--;
            c = state.data.charCodeAt(pos);
            while (c === 10 || c === 13) {
                pos--;
                c = state.data.charCodeAt(pos);
            }
            state.tokenEnd = pos + 1;
            state.isEscaped = true;
            return;
        }
        else {
            // handle line numbers
            if (c === 13) { // \r
                state.lineNumber++;
            }
            else if (c === 10 && prev !== 13) { // \r\n
                state.lineNumber++;
            }
            prev = c;
            ++pos;
        }
    }
    state.position = pos;
    return prev;
}
function eatImportGet(state) {
    // _import.get [{'save':orient_matrix  'file':templ_attr.cif}]
    // skipWhitespace(state)
    while (state.position < state.length) {
        switch (state.data.charCodeAt(state.position)) {
            case 93: // ]
                ++state.position;
                state.tokenEnd = state.position;
                state.isImportGet = false;
                return;
            default:
                ++state.position;
                break;
        }
    }
}
/**
 * Skips until \n or \r occurs -- therefore the newlines get handled by the "skipWhitespace" function.
 */
function skipCommentLine(state) {
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        if (c === 10 || c === 13) {
            return;
        }
        ++state.position;
    }
}
/**
 * Skips all the whitespace - space, tab, newline, CR
 * Handles incrementing line count.
 */
function skipWhitespace(state) {
    var prev = 10;
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        switch (c) {
            case 9: // '\t'
            case 32: // ' '
                prev = c;
                ++state.position;
                break;
            case 10: // \n
                // handle \r\n
                if (prev !== 13) {
                    ++state.lineNumber;
                }
                prev = c;
                ++state.position;
                break;
            case 13: // \r
                prev = c;
                ++state.position;
                ++state.lineNumber;
                break;
            default:
                return prev;
        }
    }
    return prev;
}
/**
 * Returns true if there are two consecutive ' in +1 and +2 positions.
 */
function isTripleQuoteAtPosition(state) {
    if (state.length - state.position < 2)
        return false;
    if (state.data.charCodeAt(state.position + 1) !== 39)
        return false; // '
    if (state.data.charCodeAt(state.position + 2) !== 39)
        return false; // '
    return true;
}
function isData(state) {
    // here we already assume the 5th char is _ and that the length >= 5
    // d/D
    var c = state.data.charCodeAt(state.tokenStart);
    if (c !== 68 && c !== 100)
        return false;
    // a/A
    c = state.data.charCodeAt(state.tokenStart + 1);
    if (c !== 65 && c !== 97)
        return false;
    // t/t
    c = state.data.charCodeAt(state.tokenStart + 2);
    if (c !== 84 && c !== 116)
        return false;
    // a/A
    c = state.data.charCodeAt(state.tokenStart + 3);
    if (c !== 65 && c !== 97)
        return false;
    return true;
}
function isSave(state) {
    // here we already assume the 5th char is _ and that the length >= 5
    // s/S
    var c = state.data.charCodeAt(state.tokenStart);
    if (c !== 83 && c !== 115)
        return false;
    // a/A
    c = state.data.charCodeAt(state.tokenStart + 1);
    if (c !== 65 && c !== 97)
        return false;
    // v/V
    c = state.data.charCodeAt(state.tokenStart + 2);
    if (c !== 86 && c !== 118)
        return false;
    // e/E
    c = state.data.charCodeAt(state.tokenStart + 3);
    if (c !== 69 && c !== 101)
        return false;
    return true;
}
function isLoop(state) {
    // here we already assume the 5th char is _ and that the length >= 5
    if (state.tokenEnd - state.tokenStart !== 5)
        return false;
    // l/L
    var c = state.data.charCodeAt(state.tokenStart);
    if (c !== 76 && c !== 108)
        return false;
    // o/O
    c = state.data.charCodeAt(state.tokenStart + 1);
    if (c !== 79 && c !== 111)
        return false;
    // o/O
    c = state.data.charCodeAt(state.tokenStart + 2);
    if (c !== 79 && c !== 111)
        return false;
    // p/P
    c = state.data.charCodeAt(state.tokenStart + 3);
    if (c !== 80 && c !== 112)
        return false;
    return true;
}
function isImportGet(state) {
    // _import.get [{'save':orient_matrix  'file':templ_attr.cif}]
    if (state.tokenEnd - state.tokenStart !== 11)
        return false;
    if (state.data.charCodeAt(state.tokenStart + 1) !== 105)
        return false; // i
    if (state.data.charCodeAt(state.tokenStart + 2) !== 109)
        return false; // m
    if (state.data.charCodeAt(state.tokenStart + 3) !== 112)
        return false; // p
    if (state.data.charCodeAt(state.tokenStart + 4) !== 111)
        return false; // o
    if (state.data.charCodeAt(state.tokenStart + 5) !== 114)
        return false; // r
    if (state.data.charCodeAt(state.tokenStart + 6) !== 116)
        return false; // t
    if (state.data.charCodeAt(state.tokenStart + 7) !== 46)
        return false; // .
    if (state.data.charCodeAt(state.tokenStart + 8) !== 103)
        return false; // g
    if (state.data.charCodeAt(state.tokenStart + 9) !== 101)
        return false; // e
    if (state.data.charCodeAt(state.tokenStart + 10) !== 116)
        return false; // t
    return true;
}
/**
 * Checks if the current token shares the namespace with string at <start,end).
 */
function isNamespace(state, start, end) {
    var i, nsLen = end - start, offset = state.tokenStart - start, tokenLen = state.tokenEnd - state.tokenStart;
    if (tokenLen < nsLen)
        return false;
    for (i = start; i < end; ++i) {
        if (state.data.charCodeAt(i) !== state.data.charCodeAt(i + offset))
            return false;
    }
    if (nsLen === tokenLen)
        return true;
    if (state.data.charCodeAt(i + offset) === 46) { // .
        return true;
    }
    return false;
}
/**
 * Returns the index of '.' in the current token. If no '.' is present, returns currentTokenEnd.
 */
function getNamespaceEnd(state) {
    var i;
    for (i = state.tokenStart; i < state.tokenEnd; ++i) {
        if (state.data.charCodeAt(i) === 46)
            return i;
    }
    return i;
}
/**
 * Get the namespace string. endIndex is obtained by the getNamespaceEnd() function.
 */
function getNamespace(state, endIndex) {
    return state.data.substring(state.tokenStart, endIndex);
}
/**
 * Returns true if the current token contain no '.', otherwise returns false.
 */
function isFlatNamespace(state) {
    var i;
    for (i = state.tokenStart; i < state.tokenEnd; ++i) {
        if (state.data.charCodeAt(i) === 46)
            return false;
    }
    return true;
}
/**
 * String representation of the current token.
 */
function getTokenString(state) {
    return state.data.substring(state.tokenStart, state.tokenEnd);
}
/**
 * Move to the next token.
 */
function moveNextInternal(state) {
    var prev = skipWhitespace(state);
    if (state.position >= state.length) {
        state.tokenType = 6 /* End */;
        return;
    }
    state.tokenStart = state.position;
    state.tokenEnd = state.position;
    state.isEscaped = false;
    var c = state.data.charCodeAt(state.position);
    switch (c) {
        case 35: // #, comment
            skipCommentLine(state);
            state.tokenType = 5 /* Comment */;
            break;
        case 39: // ', escaped value
            if (isTripleQuoteAtPosition(state)) {
                eatTripleQuote(state);
                state.tokenType = 3 /* Value */;
                break;
            }
        case 34: // ", escaped value
            eatEscaped(state, c);
            state.tokenType = 3 /* Value */;
            break;
        case 59: // ;, possible multiline value
            // multiline value must start at the beginning of the line.
            if (prev === 10 || prev === 13) { // /n or /r
                eatMultiline(state);
            }
            else {
                eatValue(state);
            }
            state.tokenType = 3 /* Value */;
            break;
        default:
            if (state.isImportGet) {
                eatImportGet(state);
            }
            else {
                eatValue(state);
            }
            // escaped is always Value
            if (state.isEscaped) {
                state.tokenType = 3 /* Value */;
                // _ means column name, including _import.get
            }
            else if (state.data.charCodeAt(state.tokenStart) === 95) { // _
                if (state.inSaveFrame && isImportGet(state)) {
                    state.isImportGet = true;
                }
                state.tokenType = 4 /* ColumnName */;
                // 5th char needs to be _ for data_, save_ or loop_
            }
            else if (state.tokenEnd - state.tokenStart >= 5 && state.data.charCodeAt(state.tokenStart + 4) === 95) {
                if (isData(state))
                    state.tokenType = 0 /* Data */;
                else if (isSave(state))
                    state.tokenType = 1 /* Save */;
                else if (isLoop(state))
                    state.tokenType = 2 /* Loop */;
                else
                    state.tokenType = 3 /* Value */;
                // all other tests failed, we are at Value token.
            }
            else {
                state.tokenType = 3 /* Value */;
            }
            break;
    }
}
/**
 * Moves to the next non-comment token.
 */
function moveNext(state) {
    moveNextInternal(state);
    while (state.tokenType === 5 /* Comment */)
        moveNextInternal(state);
}
function createTokenizer(data, runtimeCtx) {
    return {
        data: data,
        length: data.length,
        position: 0,
        tokenStart: 0,
        tokenEnd: 0,
        tokenType: 6 /* End */,
        lineNumber: 1,
        isEscaped: false,
        isImportGet: false,
        inSaveFrame: false,
        runtimeCtx: runtimeCtx
    };
}
function FrameContext() {
    return { categoryNames: [], categoryData: Object.create(null) };
}
function CifCategories(categoryNames, categoryData) {
    var categories = Object.create(null);
    for (var _i = 0, categoryNames_1 = categoryNames; _i < categoryNames_1.length; _i++) {
        var name_1 = categoryNames_1[_i];
        var d = categoryData[name_1];
        categories[name_1] = data_model["b" /* CifCategory */](d.name, d.rowCount, d.fieldNames, d.fields);
    }
    return categories;
}
function CifBlock(ctx, header, saveFrames) {
    return data_model["a" /* CifBlock */](ctx.categoryNames, CifCategories(ctx.categoryNames, ctx.categoryData), header, saveFrames);
}
function CifSaveFrame(ctx, header) {
    return data_model["a" /* CifBlock */](ctx.categoryNames, CifCategories(ctx.categoryNames, ctx.categoryData), header);
}
function addFields(ctx, name, rowCount, fieldNames, fields) {
    var _a;
    if (name in ctx.categoryData) {
        var cat = ctx.categoryData[name];
        (_a = cat.fieldNames).push.apply(_a, fieldNames);
        Object.assign(cat.fields, fields);
    }
    else {
        ctx.categoryData[name] = { name: name, rowCount: rowCount, fieldNames: fieldNames, fields: fields };
        ctx.categoryNames.push(name);
    }
}
/**
 * Reads a category containing a single row.
 */
function handleSingle(tokenizer, ctx) {
    var nsStart = tokenizer.tokenStart, nsEnd = getNamespaceEnd(tokenizer);
    var name = getNamespace(tokenizer, nsEnd);
    var fields = Object.create(null);
    var fieldNames = [];
    var readingNames = true;
    while (readingNames) {
        if (tokenizer.tokenType !== 4 /* ColumnName */ || !isNamespace(tokenizer, nsStart, nsEnd)) {
            readingNames = false;
            break;
        }
        var fieldName = getTokenString(tokenizer).substring(name.length + 1);
        moveNext(tokenizer);
        if (tokenizer.tokenType !== 3 /* Value */) {
            return {
                hasError: true,
                errorLine: tokenizer.lineNumber,
                errorMessage: 'Expected value.'
            };
        }
        fields[fieldName] = data_model["c" /* CifField */].ofTokens({ data: tokenizer.data, indices: [tokenizer.tokenStart, tokenizer.tokenEnd], count: 1 });
        fieldNames[fieldNames.length] = fieldName;
        moveNext(tokenizer);
    }
    addFields(ctx, name.substr(1), 1, fieldNames, fields);
    return {
        hasError: false,
        errorLine: 0,
        errorMessage: ''
    };
}
function readLoopChunk(chunkSize, state) {
    var tokenizer = state.tokenizer, tokens = state.tokens, fieldCount = state.fieldCount;
    var tokenCount = state.tokenCount;
    var counter = 0;
    while (tokenizer.tokenType === 3 /* Value */ && counter < chunkSize) {
        text_tokenizer["a" /* TokenBuilder */].add(tokens[(tokenCount++) % fieldCount], tokenizer.tokenStart, tokenizer.tokenEnd);
        moveNext(tokenizer);
        counter++;
    }
    state.tokenCount = tokenCount;
    return counter;
}
function updateLoopChunk(ctx, state) {
    return ctx.update({ message: 'Parsing...', current: state.tokenizer.position, max: state.tokenizer.data.length });
}
// const readLoopChunks = ChunkedSubtask(1000000,
//     (size, state: LoopReadState) => readLoopChunk(state, size),
//     (ctx, state) => ctx.update({ message: 'Parsing...', current: state.tokenizer.position, max: state.tokenizer.data.length }));
/**
 * Reads a loop.
 */
function handleLoop(tokenizer, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var loopLine, name, isFlat, fieldNames, rowCountEstimate, tokens, fieldCount, i, state, rowCount, i, fields, fields, i;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    loopLine = tokenizer.lineNumber;
                    moveNext(tokenizer);
                    name = getNamespace(tokenizer, getNamespaceEnd(tokenizer));
                    isFlat = isFlatNamespace(tokenizer);
                    fieldNames = [];
                    while (tokenizer.tokenType === 4 /* ColumnName */) {
                        fieldNames[fieldNames.length] = isFlat
                            ? getTokenString(tokenizer)
                            : getTokenString(tokenizer).substring(name.length + 1);
                        moveNext(tokenizer);
                    }
                    rowCountEstimate = name === '_atom_site' ? (tokenizer.data.length / 100) | 0 : 32;
                    tokens = [];
                    fieldCount = fieldNames.length;
                    for (i = 0; i < fieldCount; i++)
                        tokens[i] = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, rowCountEstimate);
                    state = {
                        fieldCount: fieldCount,
                        tokenCount: 0,
                        tokenizer: tokenizer,
                        tokens: tokens
                    };
                    return [4 /*yield*/, Object(mol_task["c" /* chunkedSubtask */])(tokenizer.runtimeCtx, 1000000, state, readLoopChunk, updateLoopChunk)];
                case 1:
                    _a.sent();
                    if (state.tokenCount % fieldCount !== 0) {
                        return [2 /*return*/, {
                                hasError: true,
                                errorLine: tokenizer.lineNumber,
                                errorMessage: "The number of values for loop starting at line " + loopLine + " is not a multiple of the number of columns."
                            }];
                    }
                    rowCount = (state.tokenCount / fieldCount) | 0;
                    if (isFlat) {
                        for (i = 0; i < fieldCount; i++) {
                            fields = { '': data_model["c" /* CifField */].ofTokens(tokens[i]) };
                            addFields(ctx, fieldNames[i].substr(1), rowCount, [''], fields);
                        }
                    }
                    else {
                        fields = Object.create(null);
                        for (i = 0; i < fieldCount; i++) {
                            fields[fieldNames[i]] = data_model["c" /* CifField */].ofTokens(tokens[i]);
                        }
                        addFields(ctx, name.substr(1), rowCount, fieldNames, fields);
                    }
                    return [2 /*return*/, {
                            hasError: false,
                            errorLine: 0,
                            errorMessage: ''
                        }];
            }
        });
    });
}
/**
 * Creates an error result.
 */
function error(line, message) {
    return result["a" /* ReaderResult */].error(message, line);
}
/**
 * Creates a data result.
 */
function parser_result(data) {
    return result["a" /* ReaderResult */].success(data);
}
/**
 * Parses an mmCIF file.
 *
 * @returns CifParserResult wrapper of the result.
 */
function parseInternal(data, runtimeCtx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var dataBlocks, tokenizer, blockHeader, blockCtx, saveFrames, saveCtx, saveFrame, saveHeader, token, cat, cat;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    dataBlocks = [];
                    tokenizer = createTokenizer(data, runtimeCtx);
                    blockHeader = '';
                    blockCtx = FrameContext();
                    saveFrames = [];
                    saveCtx = FrameContext();
                    saveFrame = data_model["e" /* CifSaveFrame */](saveCtx.categoryNames, CifCategories(saveCtx.categoryNames, saveCtx.categoryData), '');
                    saveHeader = '';
                    runtimeCtx.update({ message: 'Parsing...', current: 0, max: data.length });
                    moveNext(tokenizer);
                    _a.label = 1;
                case 1:
                    if (!(tokenizer.tokenType !== 6 /* End */)) return [3 /*break*/, 7];
                    token = tokenizer.tokenType;
                    if (!(token === 0 /* Data */)) return [3 /*break*/, 2];
                    if (tokenizer.inSaveFrame) {
                        return [2 /*return*/, error(tokenizer.lineNumber, 'Unexpected data block inside a save frame.')];
                    }
                    if (blockCtx.categoryNames.length > 0) {
                        dataBlocks.push(CifBlock(blockCtx, blockHeader, saveFrames));
                    }
                    blockHeader = data.substring(tokenizer.tokenStart + 5, tokenizer.tokenEnd);
                    blockCtx = FrameContext();
                    saveFrames = [];
                    moveNext(tokenizer);
                    return [3 /*break*/, 6];
                case 2:
                    if (!(token === 1 /* Save */)) return [3 /*break*/, 3];
                    if (tokenizer.tokenEnd - tokenizer.tokenStart === 5) { // end of save frame
                        if (saveCtx.categoryNames.length > 0) {
                            saveFrames[saveFrames.length] = CifSaveFrame(saveCtx, saveHeader);
                        }
                        tokenizer.inSaveFrame = false;
                    }
                    else { // start of save frame
                        if (tokenizer.inSaveFrame) {
                            return [2 /*return*/, error(tokenizer.lineNumber, 'Save frames cannot be nested.')];
                        }
                        tokenizer.inSaveFrame = true;
                        saveHeader = data.substring(tokenizer.tokenStart + 5, tokenizer.tokenEnd);
                        saveCtx = FrameContext();
                        // saveFrame = CifSaveFrame(saveCtx, saveHeader);
                    }
                    moveNext(tokenizer);
                    return [3 /*break*/, 6];
                case 3:
                    if (!(token === 2 /* Loop */)) return [3 /*break*/, 5];
                    return [4 /*yield*/, handleLoop(tokenizer, tokenizer.inSaveFrame ? saveCtx : blockCtx)];
                case 4:
                    cat = _a.sent();
                    if (cat.hasError) {
                        return [2 /*return*/, error(cat.errorLine, cat.errorMessage)];
                    }
                    return [3 /*break*/, 6];
                case 5:
                    if (token === 4 /* ColumnName */) {
                        cat = handleSingle(tokenizer, tokenizer.inSaveFrame ? saveCtx : blockCtx);
                        if (cat.hasError) {
                            return [2 /*return*/, error(cat.errorLine, cat.errorMessage)];
                        }
                        // Out of options
                    }
                    else {
                        console.log(tokenizer.tokenType, text_tokenizer["b" /* Tokenizer */].getTokenString(tokenizer));
                        return [2 /*return*/, error(tokenizer.lineNumber, 'Unexpected token. Expected data_, loop_, or data name.')];
                    }
                    _a.label = 6;
                case 6: return [3 /*break*/, 1];
                case 7:
                    // Check if the latest save frame was closed.
                    if (tokenizer.inSaveFrame) {
                        return [2 /*return*/, error(tokenizer.lineNumber, "Unfinished save frame (" + saveFrame.header + ").")];
                    }
                    if (blockCtx.categoryNames.length > 0 || saveFrames.length > 0) {
                        dataBlocks.push(CifBlock(blockCtx, blockHeader, saveFrames));
                    }
                    return [2 /*return*/, parser_result(data_model["d" /* CifFile */](dataBlocks))];
            }
        });
    });
}
function parse(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse CIF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, parseInternal(data, ctx)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif.js + 1 modules
var binary_cif = __webpack_require__(121);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/number-parser.js
var number_parser = __webpack_require__(97);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/binary/field.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function Field(column) {
    var mask = column.mask ? Object(binary_cif["d" /* decode */])(column.mask) : void 0;
    var data = Object(binary_cif["d" /* decode */])(column.data);
    var isNumeric = db["ColumnHelpers"].isTypedArray(data);
    var str = isNumeric
        ? mask
            ? function (row) { return mask[row] === 0 /* Present */ ? '' + data[row] : ''; }
            : function (row) { return '' + data[row]; }
        : mask
            ? function (row) { return mask[row] === 0 /* Present */ ? data[row] : ''; }
            : function (row) { return data[row]; };
    var int = isNumeric
        ? function (row) { return data[row]; }
        : function (row) { var v = data[row]; return Object(number_parser["d" /* parseInt */])(v, 0, v.length); };
    var float = isNumeric
        ? function (row) { return data[row]; }
        : function (row) { var v = data[row]; return Object(number_parser["b" /* parseFloat */])(v, 0, v.length); };
    var valueKind = mask
        ? function (row) { return mask[row]; }
        : function (row) { return 0 /* Present */; };
    var rowCount = data.length;
    return {
        __array: data,
        binaryEncoding: column.data.encoding,
        isDefined: true,
        rowCount: rowCount,
        str: str,
        int: int,
        float: float,
        valueKind: valueKind,
        areValuesEqual: function (rowA, rowB) { return data[rowA] === data[rowB]; },
        toStringArray: function (params) { return db["ColumnHelpers"].createAndFillArray(rowCount, str, params); },
        toIntArray: isNumeric
            ? function (params) { return db["ColumnHelpers"].typedArrayWindow(data, params); }
            : function (params) { return db["ColumnHelpers"].createAndFillArray(rowCount, int, params); },
        toFloatArray: isNumeric
            ? function (params) { return db["ColumnHelpers"].typedArrayWindow(data, params); }
            : function (params) { return db["ColumnHelpers"].createAndFillArray(rowCount, float, params); }
    };
}
//# sourceMappingURL=field.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/msgpack/decode.js
var decode = __webpack_require__(357);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/binary/parser.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






function checkVersions(min, current) {
    for (var i = 0; i < 2; i++) {
        if (min[i] > current[i])
            return false;
    }
    return true;
}
function Category(data) {
    var map = Object.create(null);
    var cache = Object.create(null);
    for (var _i = 0, _a = data.columns; _i < _a.length; _i++) {
        var col = _a[_i];
        map[col.name] = col;
    }
    return {
        rowCount: data.rowCount,
        name: data.name.substr(1),
        fieldNames: data.columns.map(function (c) { return c.name; }),
        getField: function (name) {
            var col = map[name];
            if (!col)
                return void 0;
            if (!!cache[name])
                return cache[name];
            cache[name] = Field(col);
            return cache[name];
        }
    };
}
function parser_parse(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse BinaryCIF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var minVersion, unpacked, file;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            minVersion = [0, 3];
            try {
                unpacked = Object(decode["a" /* default */])(data);
                if (!checkVersions(minVersion, unpacked.version.match(/(\d)\.(\d)\.\d/).slice(1).map(function (v) { return +v; }))) {
                    return [2 /*return*/, result["a" /* ReaderResult */].error("Unsupported format version. Current " + unpacked.version + ", required " + minVersion.join('.') + ".")];
                }
                file = data_model["d" /* CifFile */](unpacked.dataBlocks.map(function (block) {
                    var cats = Object.create(null);
                    for (var _i = 0, _a = block.categories; _i < _a.length; _i++) {
                        var cat = _a[_i];
                        cats[cat.name.substr(1)] = Category(cat);
                    }
                    return data_model["a" /* CifBlock */](block.categories.map(function (c) { return c.name.substr(1); }), cats, block.header);
                }));
                return [2 /*return*/, result["a" /* ReaderResult */].success(file)];
            }
            catch (e) {
                return [2 /*return*/, result["a" /* ReaderResult */].error('' + e)];
            }
            return [2 /*return*/];
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema.js
var schema = __webpack_require__(135);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/mmcif.js
var mmcif = __webpack_require__(57);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/ccd.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Code-generated 'CCD' schema file. Dictionary versions: mmCIF 5.326, IHM 1.09, CARB draft.
 *
 * @author molstar/ciftools package
 */

var Schema = db["Column"].Schema;
var ccd_str = Schema.str;
var ccd_float = Schema.float;
var List = Schema.List;
var Aliased = Schema.Aliased;
var ccd_int = Schema.int;
var coord = Schema.coord;
var CCD_Schema = {
    /**
     * Data items in the CHEM_COMP category give details about each
     * of the chemical components from which the relevant chemical
     * structures can be constructed, such as name, mass or charge.
     *
     * The related categories CHEM_COMP_ATOM, CHEM_COMP_BOND,
     * CHEM_COMP_ANGLE etc. describe the detailed geometry of these
     * chemical components.
     */
    chem_comp: {
        /**
         * The formula for the chemical component. Formulae are written
         * according to the following rules:
         *
         * (1) Only recognized element symbols may be used.
         *
         * (2) Each element symbol is followed by a 'count' number. A count
         * of '1' may be omitted.
         *
         * (3) A space or parenthesis must separate each cluster of
         * (element symbol + count), but in general parentheses are
         * not used.
         *
         * (4) The order of elements depends on whether carbon is
         * present or not. If carbon is present, the order should be:
         * C, then H, then the other elements in alphabetical order
         * of their symbol. If carbon is not present, the elements
         * are listed purely in alphabetic order of their symbol. This
         * is the 'Hill' system used by Chemical Abstracts.
         */
        formula: ccd_str,
        /**
         * Formula mass in daltons of the chemical component.
         */
        formula_weight: ccd_float,
        /**
         * The value of _chem_comp.id must uniquely identify each item in
         * the CHEM_COMP list.
         *
         * For protein polymer entities, this is the three-letter code for
         * the amino acid.
         *
         * For nucleic acid polymer entities, this is the one-letter code
         * for the base.
         */
        id: ccd_str,
        /**
         * The identifier for the parent component of the nonstandard
         * component. May be be a comma separated list if this component
         * is derived from multiple components.
         *
         * Items in this indirectly point to _chem_comp.id in
         * the CHEM_COMP category.
         */
        mon_nstd_parent_comp_id: List(',', function (x) { return x; }),
        /**
         * The full name of the component.
         */
        name: ccd_str,
        /**
         * For standard polymer components, the one-letter code for
         * the component.   For non-standard polymer components, the
         * one-letter code for parent component if this exists;
         * otherwise, the one-letter code should be given as 'X'.
         *
         * Components that derived from multiple parents components
         * are described by a sequence of one-letter-codes.
         */
        one_letter_code: ccd_str,
        /**
         * For standard polymer components, the common three-letter code for
         * the component.   Non-standard polymer components and non-polymer
         * components are also assigned three-letter-codes.
         *
         * For ambiguous polymer components three-letter code should
         * be given as 'UNK'.  Ambiguous ions are assigned the code 'UNX'.
         * Ambiguous non-polymer components are assigned the code 'UNL'.
         */
        three_letter_code: ccd_str,
        /**
         * For standard polymer components, the type of the monomer.
         * Note that monomers that will form polymers are of three types:
         * linking monomers, monomers with some type of N-terminal (or 5')
         * cap and monomers with some type of C-terminal (or 3') cap.
         */
        type: Aliased(ccd_str),
        /**
         * Synonym list for the component.
         */
        pdbx_synonyms: List(';', function (x) { return x; }),
        /**
         * A preliminary classification used by PDB.
         */
        pdbx_type: ccd_str,
        /**
         * A preliminary classification used by PDB to indicate
         * that the chemistry of this component while described
         * as clearly as possible is still ambiguous.  Software
         * tools may not be able to process this component
         * definition.
         */
        pdbx_ambiguous_flag: ccd_str,
        /**
         * Identifies the _chem_comp.id of the component that
         * has replaced this component.
         */
        pdbx_replaced_by: ccd_str,
        /**
         * Identifies the _chem_comp.id's of the components
         * which have been replaced by this component.
         * Multiple id codes should be separated by commas.
         */
        pdbx_replaces: ccd_str,
        /**
         * The net integer charge assigned to this component. This is the
         * formal charge assignment normally found in chemical diagrams.
         */
        pdbx_formal_charge: ccd_int,
        /**
         * This data item provides additional details about the model coordinates
         * in the component definition.
         */
        pdbx_model_coordinates_details: ccd_str,
        /**
         * This data item identifies the PDB database code from which the heavy
         * atom model coordinates were obtained.
         */
        pdbx_model_coordinates_db_code: ccd_str,
        /**
         * This data item identifies the source of the ideal coordinates in the
         * component definition.
         */
        pdbx_ideal_coordinates_details: ccd_str,
        /**
         * This data item identifies if ideal coordinates are missing in this definition.
         */
        pdbx_ideal_coordinates_missing_flag: Aliased(ccd_str),
        /**
         * This data item identifies if model coordinates are missing in this definition.
         */
        pdbx_model_coordinates_missing_flag: Aliased(ccd_str),
        /**
         * Date component was added to database.
         */
        pdbx_initial_date: ccd_str,
        /**
         * Date component was last modified.
         */
        pdbx_modified_date: ccd_str,
        /**
         * This data item holds the current release status for the component.
         */
        pdbx_release_status: Aliased(ccd_str),
        /**
         * This data item identifies the deposition site that processed
         * this chemical component defintion.
         */
        pdbx_processing_site: Aliased(ccd_str),
    },
    /**
     * Data items in the CHEM_COMP_ATOM category record details about
     * the atoms in a chemical component. Specifying the atomic
     * coordinates for the components in this category is an
     * alternative to specifying the structure of the component
     * via bonds, angles, planes etc. in the appropriate
     * CHEM_COMP subcategories.
     */
    chem_comp_atom: {
        /**
         * An alternative identifier for the atom. This data item would be
         * used in cases where alternative nomenclatures exist for labelling
         * atoms in a group.
         */
        alt_atom_id: ccd_str,
        /**
         * The value of _chem_comp_atom.atom_id must uniquely identify
         * each atom in each monomer in the CHEM_COMP_ATOM list.
         *
         * The atom identifiers need not be unique over all atoms in the
         * data block; they need only be unique for each atom in a
         * component.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        atom_id: ccd_str,
        /**
         * The net integer charge assigned to this atom. This is the
         * formal charge assignment normally found in chemical diagrams.
         */
        charge: ccd_int,
        /**
         * The x component of the coordinates for this atom in this
         * component specified as orthogonal angstroms. The choice of
         * reference axis frame for the coordinates is arbitrary.
         *
         * The set of coordinates input for the entity here is intended to
         * correspond to the atomic model used to generate restraints for
         * structure refinement, not to atom sites in the ATOM_SITE
         * list.
         */
        model_Cartn_x: coord,
        /**
         * The y component of the coordinates for this atom in this
         * component specified as orthogonal angstroms. The choice of
         * reference axis frame for the coordinates is arbitrary.
         *
         * The set of coordinates input for the entity here is intended to
         * correspond to the atomic model used to generate restraints for
         * structure refinement, not to atom sites in the ATOM_SITE
         * list.
         */
        model_Cartn_y: coord,
        /**
         * The z component of the coordinates for this atom in this
         * component specified as orthogonal angstroms. The choice of
         * reference axis frame for the coordinates is arbitrary.
         *
         * The set of coordinates input for the entity here is intended to
         * correspond to the atomic model used to generate restraints for
         * structure refinement, not to atom sites in the ATOM_SITE
         * list.
         */
        model_Cartn_z: coord,
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: ccd_str,
        /**
         * The code used to identify the atom species representing
         * this atom type. Normally this code is the element
         * symbol.
         */
        type_symbol: ccd_str,
        /**
         * Atom name alignment offset in PDB atom field.
         */
        pdbx_align: ccd_int,
        /**
         * Ordinal index for the component atom list.
         */
        pdbx_ordinal: ccd_int,
        /**
         * An alternative x component of the coordinates for this atom in this
         * component specified as orthogonal angstroms.
         */
        pdbx_model_Cartn_x_ideal: coord,
        /**
         * An alternative y component of the coordinates for this atom in this
         * component specified as orthogonal angstroms.
         */
        pdbx_model_Cartn_y_ideal: coord,
        /**
         * An alternative z component of the coordinates for this atom in this
         * component specified as orthogonal angstroms.
         */
        pdbx_model_Cartn_z_ideal: coord,
        /**
         * The chiral configuration of the atom that is a chiral center.
         */
        pdbx_stereo_config: Aliased(ccd_str),
        /**
         * A flag indicating an aromatic atom.
         */
        pdbx_aromatic_flag: Aliased(ccd_str),
        /**
         * A flag indicating a leaving atom.
         */
        pdbx_leaving_atom_flag: Aliased(ccd_str),
    },
    /**
     * Data items in the CHEM_COMP_BOND category record details about
     * the bonds between atoms in a chemical component. Target values
     * may be specified as bond orders, as a distance between the two
     * atoms, or both.
     */
    chem_comp_bond: {
        /**
         * The ID of the first of the two atoms that define the bond.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_1: ccd_str,
        /**
         * The ID of the second of the two atoms that define the bond.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_2: ccd_str,
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: ccd_str,
        /**
         * The value that should be taken as the target for the chemical
         * bond associated with the specified atoms, expressed as a bond
         * order.
         */
        value_order: Aliased(ccd_str),
        /**
         * Ordinal index for the component bond list.
         */
        pdbx_ordinal: ccd_int,
        /**
         * Stereochemical configuration across a double bond.
         */
        pdbx_stereo_config: Aliased(ccd_str),
        /**
         * A flag indicating an aromatic bond.
         */
        pdbx_aromatic_flag: Aliased(ccd_str),
    },
    /**
     * Data items in the CHEM_COMP_DESCRIPTOR category provide
     * string descriptors of component chemical structure.
     */
    pdbx_chem_comp_descriptor: {
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: ccd_str,
        /**
         * This data item contains the descriptor value for this
         * component.
         */
        descriptor: ccd_str,
        /**
         * This data item contains the descriptor type.
         */
        type: Aliased(ccd_str),
        /**
         * This data item contains the name of the program
         * or library used to compute the descriptor.
         */
        program: ccd_str,
        /**
         * This data item contains the version of the program
         * or library used to compute the descriptor.
         */
        program_version: ccd_str,
    },
    /**
     * Data items in the CHEM_COMP_IDENTIFIER category provide
     * identifiers for chemical components.
     */
    pdbx_chem_comp_identifier: {
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: ccd_str,
        /**
         * This data item contains the identifier value for this
         * component.
         */
        identifier: ccd_str,
        /**
         * This data item contains the identifier type.
         */
        type: Aliased(ccd_str),
        /**
         * This data item contains the name of the program
         * or library used to compute the identifier.
         */
        program: ccd_str,
        /**
         * This data item contains the version of the program
         * or library used to compute the identifier.
         */
        program_version: ccd_str,
    },
};
;
//# sourceMappingURL=ccd.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/bird.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Code-generated 'BIRD' schema file. Dictionary versions: mmCIF 5.326, IHM 1.09, CARB draft.
 *
 * @author molstar/ciftools package
 */

var bird_Schema = db["Column"].Schema;
var bird_str = bird_Schema.str;
var bird_float = bird_Schema.float;
var bird_Aliased = bird_Schema.Aliased;
var bird_int = bird_Schema.int;
var BIRD_Schema = {
    /**
     * Data items in the PDBX_REFERENCE_MOLECULE category record
     * reference information about small polymer molecules.
     */
    pdbx_reference_molecule: {
        /**
         * The value of _pdbx_reference_molecule.prd_id is the unique identifier
         * for the reference molecule in this family.
         *
         * By convention this ID uniquely identifies the reference molecule in
         * in the PDB reference dictionary.
         *
         * The ID has the template form PRD_dddddd (e.g. PRD_000001)
         */
        prd_id: bird_str,
        /**
         * Formula mass in daltons of the entity.
         */
        formula_weight: bird_float,
        /**
         * The formula for the reference entity. Formulae are written
         * according to the rules:
         *
         * 1. Only recognised element symbols may be used.
         *
         * 2. Each element symbol is followed by a 'count' number. A count
         * of '1' may be omitted.
         *
         * 3. A space or parenthesis must separate each element symbol and
         * its count, but in general parentheses are not used.
         *
         * 4. The order of elements depends on whether or not carbon is
         * present. If carbon is present, the order should be: C, then
         * H, then the other elements in alphabetical order of their
         * symbol. If carbon is not present, the elements are listed
         * purely in alphabetic order of their symbol. This is the
         * 'Hill' system used by Chemical Abstracts.
         */
        formula: bird_str,
        /**
         * Defines the structural classification of the entity.
         */
        type: bird_Aliased(bird_str),
        /**
         * Evidence for the assignment of _pdbx_reference_molecule.type
         */
        type_evidence_code: bird_str,
        /**
         * Broadly defines the function of the entity.
         */
        class: bird_Aliased(bird_str),
        /**
         * Evidence for the assignment of _pdbx_reference_molecule.class
         */
        class_evidence_code: bird_str,
        /**
         * A name of the entity.
         */
        name: bird_str,
        /**
         * Defines how this entity is represented in PDB data files.
         */
        represent_as: bird_Aliased(bird_str),
        /**
         * For entities represented as single molecules, the identifier
         * corresponding to the chemical definition for the molecule.
         */
        chem_comp_id: bird_str,
        /**
         * Special details about this molecule.
         */
        compound_details: bird_str,
        /**
         * Description of this molecule.
         */
        description: bird_str,
        /**
         * The PDB accession code for the entry containing a representative example of this molecule.
         */
        representative_PDB_id_code: bird_str,
        /**
         * Defines the current PDB release status for this molecule definition.
         */
        release_status: bird_Aliased(bird_str),
        /**
         * Assigns the identifier for the reference molecule which have been replaced
         * by this reference molecule.
         * Multiple molecule identifier codes should be separated by commas.
         */
        replaces: bird_str,
        /**
         * Assigns the identifier of the reference molecule that has replaced this molecule.
         */
        replaced_by: bird_str,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_LIST category record
     * the list of entities within each reference molecule.
     */
    pdbx_reference_entity_list: {
        /**
         * The value of _pdbx_reference_entity_list.prd_id is a reference
         * _pdbx_reference_molecule.prd_id in the PDBX_REFERENCE_MOLECULE category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_list.ref_entity_id is a unique identifier
         * the a constituent entity within this reference molecule.
         */
        ref_entity_id: bird_str,
        /**
         * Defines the polymer characteristic of the entity.
         */
        type: bird_Aliased(bird_str),
        /**
         * Additional details about this entity.
         */
        details: bird_str,
        /**
         * The component number of this entity within the molecule.
         */
        component_id: bird_int,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_NONPOLY category record
     * the list of entities within each reference molecule.
     */
    pdbx_reference_entity_nonpoly: {
        /**
         * The value of _pdbx_reference_entity_nonpoly.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_nonpoly.ref_entity_id is a reference
         * to _pdbx_reference_entity_list.ref_entity_id in PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id: bird_str,
        /**
         * A name of the non-polymer entity.
         */
        name: bird_str,
        /**
         * For non-polymer entities, the identifier corresponding
         * to the chemical definition for the molecule.
         */
        chem_comp_id: bird_str,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_LINK category give details about
     * the linkages between entities within reference molecules.
     */
    pdbx_reference_entity_link: {
        /**
         * The value of _pdbx_reference_entity_link.link_id uniquely identifies
         * linkages between entities with a molecule.
         */
        link_id: bird_int,
        /**
         * The value of _pdbx_reference_entity_link.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: bird_str,
        /**
         * A description of special aspects of a linkage between
         * chemical components in the structure.
         */
        details: bird_str,
        /**
         * The reference entity id of the first of the two entities joined by the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_list.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id_1: bird_str,
        /**
         * The reference entity id of the second of the two entities joined by the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_list.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id_2: bird_str,
        /**
         * For a polymer entity, the sequence number in the first of
         * the two entities containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_1: bird_int,
        /**
         * For a polymer entity, the sequence number in the second of
         * the two entities containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_2: bird_int,
        /**
         * The component identifier in the first of the two entities containing the linkage.
         *
         * For polymer entities, this data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         *
         * For non-polymer entities, this data item is a pointer to
         * _pdbx_reference_entity_nonpoly.chem_comp_id in the
         * PDBX_REFERENCE_ENTITY_NONPOLY category.
         */
        comp_id_1: bird_str,
        /**
         * The component identifier in the second of the two entities containing the linkage.
         *
         * For polymer entities, this data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         *
         * For non-polymer entities, this data item is a pointer to
         * _pdbx_reference_entity_nonpoly.chem_comp_id in the
         * PDBX_REFERENCE_ENTITY_NONPOLY category.
         */
        comp_id_2: bird_str,
        /**
         * The atom identifier/name in the first of the two entities containing the linkage.
         */
        atom_id_1: bird_str,
        /**
         * The atom identifier/name in the second of the two entities containing the linkage.
         */
        atom_id_2: bird_str,
        /**
         * The bond order target for the chemical linkage.
         */
        value_order: bird_Aliased(bird_str),
        /**
         * The entity component identifier for the first of two entities containing the linkage.
         */
        component_1: bird_int,
        /**
         * The entity component identifier for the second of two entities containing the linkage.
         */
        component_2: bird_int,
        /**
         * A code indicating the entity types involved in the linkage.
         */
        link_class: bird_Aliased(bird_str),
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_POLY_LINK category give details about
     * polymer linkages including both standard and non-standard linkages between
     * polymer componnents.
     */
    pdbx_reference_entity_poly_link: {
        /**
         * The value of _pdbx_reference_entity_poly_link.link_id uniquely identifies
         * a linkage within a polymer entity.
         */
        link_id: bird_int,
        /**
         * The value of _pdbx_reference_entity_poly_link.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the PDBX_REFERENCE_ENTITY_POLY category.
         */
        prd_id: bird_str,
        /**
         * The reference entity id of the polymer entity containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_POLY category.
         */
        ref_entity_id: bird_str,
        /**
         * The entity component identifier entity containing the linkage.
         */
        component_id: bird_int,
        /**
         * For a polymer entity, the sequence number in the first of
         * the two components making the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_1: bird_int,
        /**
         * For a polymer entity, the sequence number in the second of
         * the two components making the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_2: bird_int,
        /**
         * The component identifier in the first of the two components making the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        comp_id_1: bird_str,
        /**
         * The component identifier in the second of the two components making the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        comp_id_2: bird_str,
        /**
         * The atom identifier/name in the first of the two components making
         * the linkage.
         */
        atom_id_1: bird_str,
        /**
         * The atom identifier/name in the second of the two components making
         * the linkage.
         */
        atom_id_2: bird_str,
        /**
         * The bond order target for the non-standard linkage.
         */
        value_order: bird_Aliased(bird_str),
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_POLY category record details about
     * the polymer, such as the type of the polymer, the number of
     * monomers and whether it has nonstandard features.
     */
    pdbx_reference_entity_poly: {
        /**
         * The value of _pdbx_reference_entity_poly.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the  PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_poly.ref_entity_id is a reference
         * to _pdbx_reference_entity_list.ref_entity_id in PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id: bird_str,
        /**
         * The type of the polymer.
         */
        type: bird_Aliased(bird_str),
        /**
         * The database code for this source information
         */
        db_code: bird_str,
        /**
         * The database name for this source information
         */
        db_name: bird_str,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_POLY_SEQ category specify the sequence
     * of monomers in a polymer.
     */
    pdbx_reference_entity_poly_seq: {
        /**
         * The value of _pdbx_reference_entity_poly_seq.prd_id is a reference
         * _pdbx_reference_entity_poly.prd_id in the  PDBX_REFERENCE_ENTITY_POLY category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_poly_seq.ref_entity_id is a reference
         * to _pdbx_reference_entity_poly.ref_entity_id in PDBX_REFERENCE_ENTITY_POLY category.
         */
        ref_entity_id: bird_str,
        /**
         * This data item is the chemical component identifier of monomer.
         */
        mon_id: bird_str,
        /**
         * This data item is the chemical component identifier for the parent component corresponding to this monomer.
         */
        parent_mon_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_poly_seq.num must uniquely and sequentially
         * identify a record in the PDBX_REFERENCE_ENTITY_POLY_SEQ list.
         *
         * This value is conforms to author numbering conventions and does not map directly
         * to the numbering conventions used for _entity_poly_seq.num.
         */
        num: bird_int,
        /**
         * A flag to indicate that this monomer is observed in the instance example.
         */
        observed: bird_Aliased(bird_str),
        /**
         * A flag to indicate that sequence heterogeneity at this monomer position.
         */
        hetero: bird_Aliased(bird_str),
    },
    /**
     * Additional features associated with the reference entity.
     */
    pdbx_reference_entity_sequence: {
        /**
         * The value of _pdbx_reference_entity_sequence.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the  PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_sequence.ref_entity_id is a reference
         * to _pdbx_reference_entity_list.ref_entity_id in PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id: bird_str,
        /**
         * The monomer type for the sequence.
         */
        type: bird_Aliased(bird_str),
        /**
         * A flag to indicate a non-ribosomal entity.
         */
        NRP_flag: bird_Aliased(bird_str),
        /**
         * The one-letter-code sequence for this entity.  Non-standard monomers are represented as 'X'.
         */
        one_letter_codes: bird_str,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_SRC_NAT category record
     * details of the source from which the entity was obtained.
     */
    pdbx_reference_entity_src_nat: {
        /**
         * The value of _pdbx_reference_entity_src_nat.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the  PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_src_nat.ref_entity_id is a reference
         * to _pdbx_reference_entity_list.ref_entity_id in PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id: bird_str,
        /**
         * The value of _pdbx_reference_entity_src_nat.ordinal distinguishes
         * source details for this entity.
         */
        ordinal: bird_int,
        /**
         * The scientific name of the organism from which the entity was isolated.
         */
        organism_scientific: bird_str,
        /**
         * The NCBI TaxId of the organism from which the entity was isolated.
         */
        taxid: bird_str,
        /**
         * The database code for this source information
         */
        db_code: bird_str,
        /**
         * The database name for this source information
         */
        db_name: bird_str,
    },
    /**
     * Data items in the PDBX_PRD_AUDIT category records
     * the status and tracking information for this molecule.
     */
    pdbx_prd_audit: {
        /**
         * This data item is a pointer to _pdbx_reference_molecule.prd_id in the
         * pdbx_reference_molecule category.
         */
        prd_id: bird_str,
        /**
         * The date associated with this audit record.
         */
        date: bird_str,
        /**
         * An identifier for the wwPDB site creating or modifying the molecule.
         */
        processing_site: bird_Aliased(bird_str),
        /**
         * The action associated with this audit record.
         */
        action_type: bird_Aliased(bird_str),
    },
};
;
//# sourceMappingURL=bird.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/dic.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var dic_Schema = db["Column"].Schema;
var dic_str = dic_Schema.str;
var dic_float = dic_Schema.float;
var datablock = {
    id: dic_str,
    description: dic_str
};
var dictionary = {
    title: dic_str,
    datablock_id: dic_str,
    version: dic_str
};
var dictionary_history = {
    version: dic_str,
    update: dic_str,
    revision: dic_str
};
var sub_category = {
    id: dic_str,
    description: dic_str
};
var category_group_list = {
    id: dic_str,
    parent_id: dic_str,
    description: dic_str
};
var item_type_list = {
    code: dic_str,
    primitive_code: dic_str,
    construct: dic_str,
    detail: dic_str
};
var item_units_list = {
    code: dic_str,
    detail: dic_str
};
var item_units_conversion = {
    from_code: dic_str,
    to_code: dic_str,
    operator: dic_str,
    factor: dic_float
};
// TODO save frame dic schema
var dic_dic_Schema = {
    datablock: datablock,
    dictionary: dictionary,
    dictionary_history: dictionary_history,
    sub_category: sub_category,
    category_group_list: category_group_list,
    item_type_list: item_type_list,
    item_units_list: item_units_list,
    item_units_conversion: item_units_conversion
};
//# sourceMappingURL=dic.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/density-server.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var density_server_Schema = db["Column"].Schema;
var density_server_str = density_server_Schema.str;
var density_server_int = density_server_Schema.int;
var density_server_float = density_server_Schema.float;
var density_server_Aliased = density_server_Schema.Aliased;
var Vector = density_server_Schema.Vector;
var DensityServer_Header_Schema = {
    density_server_result: {
        'server_version': density_server_str,
        'datetime_utc': density_server_str,
        'guid': density_server_str,
        'is_empty': density_server_Aliased(density_server_str),
        'has_error': density_server_Aliased(density_server_str),
        'error': density_server_str,
        'query_source_id': density_server_str,
        'query_type': density_server_Aliased(density_server_str),
        'query_box_type': density_server_Aliased(density_server_str),
        'query_box_a': Vector(3),
        'query_box_b': Vector(3)
    }
};
var DensityServer_Data_Schema = {
    volume_data_3d_info: {
        'name': density_server_str,
        // zero indexed axis order of the data
        'axis_order': Vector(3, density_server_int),
        // Origin in fractional coords
        'origin': Vector(3),
        // Dimension in fractional coords
        'dimensions': Vector(3),
        'sample_rate': density_server_int,
        // number of samples along each axis
        'sample_count': Vector(3, density_server_int),
        'spacegroup_number': density_server_int,
        'spacegroup_cell_size': Vector(3),
        // angles in degrees
        'spacegroup_cell_angles': Vector(3),
        'mean_source': density_server_float,
        'mean_sampled': density_server_float,
        'sigma_source': density_server_float,
        'sigma_sampled': density_server_float,
        'min_source': density_server_float,
        'min_sampled': density_server_float,
        'max_source': density_server_float,
        'max_sampled': density_server_float
    },
    volume_data_3d: {
        values: density_server_float
    }
};
//# sourceMappingURL=density-server.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/cif-core.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Code-generated 'CifCore' schema file. Dictionary versions: CifCore 3.0.13.
 *
 * @author molstar/ciftools package
 */

var cif_core_Schema = db["Column"].Schema;
var cif_core_int = cif_core_Schema.int;
var cif_core_float = cif_core_Schema.float;
var cif_core_str = cif_core_Schema.str;
var Matrix = cif_core_Schema.Matrix;
var CifCore_Schema = {
    /**
     * The CATEGORY of data items used to describe the parameters of
     * the crystal unit cell and their measurement.
     */
    cell: {
        /**
         * The number of the formula units in the unit cell as specified
         * by _chemical_formula.structural, _chemical_formula.moiety or
         * _chemical_formula.sum.
         */
        formula_units_Z: cif_core_int,
        /**
         * Volume of the crystal unit cell.
         */
        volume: cif_core_float,
        /**
         * The angle between the bounding cell axes.
         */
        angle_alpha: cif_core_float,
        /**
         * The angle between the bounding cell axes.
         */
        angle_beta: cif_core_float,
        /**
         * The angle between the bounding cell axes.
         */
        angle_gamma: cif_core_float,
        /**
         * The length of each cell axis.
         */
        length_a: cif_core_float,
        /**
         * The length of each cell axis.
         */
        length_b: cif_core_float,
        /**
         * The length of each cell axis.
         */
        length_c: cif_core_float,
    },
    /**
     * The CATEGORY of data items which describe the composition and
     * chemical properties of the compound under study. The formula data
     * items must be consistent with the density, unit-cell and Z values.
     */
    chemical: {
        /**
         * The temperature at which a crystalline solid changes to a liquid.
         */
        melting_point: cif_core_float,
        /**
         * Trivial name by which the compound is commonly known.
         */
        name_common: cif_core_str,
        /**
         * IUPAC or Chemical Abstracts full name of compound.
         */
        name_systematic: cif_core_str,
    },
    /**
     * The CATEGORY of data items which specify the composition and chemical
     * properties of the compound. The formula data items must agree
     * with those that specify the density, unit-cell and Z values.
     *
     * The following rules apply to the construction of the data items
     * _chemical_formula.analytical, *.structural and *.sum. For the
     * data item *.moiety the formula construction is broken up into
     * residues or moieties, i.e. groups of atoms that form a molecular
     * unit or molecular ion. The  rules given below apply within each
     * moiety but different requirements apply to the way that moieties
     * are connected (see _chemical_formula.moiety).
     *
     * 1. Only recognized element symbols may be used.
     *
     * 2. Each element symbol is followed by a 'count' number. A count of
     * '1' may be omitted.
     *
     * 3. A space or parenthesis must separate each cluster of (element
     * symbol + count).
     *
     * 4. Where a group of elements is enclosed in parentheses, the
     * multiplier for the group must follow the closing parentheses.
     * That is, all element and group multipliers are assumed to be
     * printed as subscripted numbers. [An exception to this rule
     * exists for *.moiety formulae where pre- and post-multipliers
     * are permitted for molecular units].
     *
     * 5. Unless the elements are ordered in a manner that corresponds to
     * their chemical structure, as in _chemical_formula.structural,
     * the order of the elements within any group or moiety
     * depends on whether or not carbon is present. If carbon is
     * present, the order should be: C, then H, then the other
     * elements in alphabetical order of their symbol. If carbon is
     * not present, the elements are listed purely in alphabetic order
     * of their symbol. This is the 'Hill' system used by Chemical
     * Abstracts. This ordering is used in _chemical_formula.moiety
     * and _chemical_formula.sum.
     *
     * _chemical_formula.iupac      '[Mo (C O)4 (C18 H33 P)2]'
     * _chemical_formula.moiety     'C40 H66 Mo O4 P2'
     * _chemical_formula.structural '((C O)4 (P (C6 H11)3)2)Mo'
     * _chemical_formula.sum         'C40 H66 Mo O4 P2'
     * _chemical_formula.weight      768.81
     */
    chemical_formula: {
        /**
         * Formula with each discrete bonded residue or ion shown as a
         * separate moiety. See above CHEMICAL_FORMULA for rules
         * for writing chemical formulae. In addition to the general
         * formulae requirements, the following rules apply:
         * 1. Moieties are separated by commas ','.
         * 2. The order of elements within a moiety follows general rule
         * 5 in CHEMICAL_FORMULA.
         * 3. Parentheses are not used within moieties but may surround
         * a moiety. Parentheses may not be nested.
         * 4. Charges should be placed at the end of the moiety. The
         * Singlege '+' or '-' may be preceded by a numerical multiplier
         * and should be separated from the last (element symbol +
         * count) by a space. Pre- or post-multipliers may be used for
         * individual moieties.
         */
        moiety: cif_core_str,
        /**
         * Chemical formulae in which all discrete bonded residues and ions are
         * summed over the constituent elements, following the ordering given
         * in rule 5 of the CATEGORY description. Parentheses normally not used.
         */
        sum: cif_core_str,
        /**
         * Mass corresponding to the formulae _chemical_formula.structural,
         * *_iupac, *_moiety or *_sum and, together with the Z value and cell
         * parameters yield the density given as _exptl_crystal.density_diffrn.
         */
        weight: cif_core_float,
    },
    /**
     * The CATEGORY of data items used to specify space group
     * information about the crystal used in the diffraction measurements.
     *
     * Space-group types are identified by their number as listed in
     * International Tables for Crystallography Volume A, or by their
     * Schoenflies symbol. Specific settings of the space groups can
     * be identified by their Hall symbol, by specifying their
     * symmetry operations or generators, or by giving the
     * transformation that relates the specific setting to the
     * reference setting based on International Tables Volume A and
     * stored in this dictionary.
     *
     * The commonly used Hermann-Mauguin symbol determines the
     * space-group type uniquely but several different Hermann-Mauguin
     * symbols may refer to the same space-group type. A
     * Hermann-Mauguin symbol contains information on the choice of
     * the basis, but not on the choice of origin.
     *
     * Ref: International Tables for Crystallography (2002). Volume A,
     * Space-group symmetry, edited by Th. Hahn, 5th ed.
     * Dordrecht: Kluwer Academic Publishers.
     */
    space_group: {
        /**
         * The name of the system of geometric crystal classes of space
         * groups (crystal system) to which the space group belongs.
         * Note that rhombohedral space groups belong to the
         * trigonal system.
         */
        crystal_system: cif_core_str,
        /**
         * The number as assigned in International Tables for Crystallography
         * Vol A, specifying the proper affine class (i.e. the orientation
         * preserving affine class) of space groups (crystallographic space
         * group type) to which the space group belongs. This number defines
         * the space group type but not the coordinate system expressed.
         */
        IT_number: cif_core_int,
        /**
         * The full international Hermann-Mauguin space-group symbol as
         * defined in Section 2.2.3 and given as the second item of the
         * second line of each of the space-group tables of Part 7 of
         * International Tables for Crystallography Volume A (2002).
         *
         * Each component of the space-group name is separated by a
         * space or an underscore character. The use of a space is
         * strongly recommended.  The underscore is only retained
         * because it was used in old CIFs. It should not be used in
         * new CIFs.
         *
         * Subscripts should appear without special symbols. Bars should
         * be given as negative signs before the numbers to which they
         * apply. The commonly used Hermann-Mauguin symbol determines the
         * space-group type uniquely but a given space-group type may
         * be described by more than one Hermann-Mauguin symbol. The
         * space-group type is best described using
         * _space_group.IT_number or _space_group.name_Schoenflies. The
         * full international Hermann-Mauguin symbol contains information
         * about the choice of basis for monoclinic and orthorhombic
         * space groups but does not give information about the choice
         * of origin. To define the setting uniquely use
         * _space_group.name_Hall, or list the symmetry operations
         * or generators.
         *
         * Ref: International Tables for Crystallography (2002). Volume A,
         * Space-group symmetry, edited by Th. Hahn, 5th ed.
         * Dordrecht: Kluwer Academic Publishers.
         */
        'name_H-M_full': cif_core_str,
    },
    /**
     * The CATEGORY of data items used to describe symmetry equivalent sites
     * in the crystal unit cell.
     */
    space_group_symop: {
        /**
         * A parsable string giving one of the symmetry operations of the
         * space group in algebraic form.  If W is a matrix representation
         * of the rotational part of the symmetry operation defined by the
         * positions and signs of x, y and z, and w is a column of
         * translations defined by fractions, an equivalent position
         * X' is generated from a given position X by the equation
         *
         * X' = WX + w
         *
         * (Note: X is used to represent bold_italics_x in International
         * Tables for Crystallography Vol. A, Part 5)
         *
         * When a list of symmetry operations is given, it must contain
         * a complete set of coordinate representatives which generates
         * all the operations of the space group by the addition of
         * all primitive translations of the space group. Such
         * representatives are to be found as the coordinates of
         * the general-equivalent position in International Tables for
         * Crystallography Vol. A (2002), to which it is necessary to
         * add any centring translations shown above the
         * general-equivalent position.
         *
         * That is to say, it is necessary to list explicitly all the
         * symmetry operations required to generate all the atoms in
         * the unit cell defined by the setting used.
         */
        operation_xyz: cif_core_str,
    },
    /**
     * The CATEGORY of data items used to specify the geometry bonds in the
     * structural model as derived from the atomic sites.
     */
    geom_bond: {
        /**
         * This label is a unique identifier for a particular site in the
         * asymmetric unit of the crystal unit cell.
         */
        atom_site_label_1: cif_core_str,
        /**
         * This label is a unique identifier for a particular site in the
         * asymmetric unit of the crystal unit cell.
         */
        atom_site_label_2: cif_core_str,
        /**
         * Intramolecular bond distance between the sites identified
         * by _geom_bond.id
         */
        distance: cif_core_float,
        /**
         * This code signals whether the angle is referred to in a
         * publication or should be placed in a table of significant angles.
         */
        publ_flag: cif_core_str,
        /**
         * The set of data items which specify the symmetry operation codes
         * which must be applied to the atom sites involved in the geometry angle.
         *
         * The symmetry code of each atom site as the symmetry-equivalent position
         * number 'n' and the cell translation number 'pqr'. These numbers are
         * combined to form the code 'n pqr' or n_pqr.
         *
         * The character string n_pqr is composed as follows:
         *
         * n refers to the symmetry operation that is applied to the
         * coordinates stored in _atom_site.fract_xyz. It must match a
         * number given in _symmetry_equiv.pos_site_id.
         *
         * p, q and r refer to the translations that are subsequently
         * applied to the symmetry transformed coordinates to generate
         * the atom used in calculating the angle. These translations
         * (x,y,z) are related to (p,q,r) by the relations
         * p = 5 + x
         * q = 5 + y
         * r = 5 + z
         */
        site_symmetry_1: cif_core_str,
        /**
         * The set of data items which specify the symmetry operation codes
         * which must be applied to the atom sites involved in the geometry angle.
         *
         * The symmetry code of each atom site as the symmetry-equivalent position
         * number 'n' and the cell translation number 'pqr'. These numbers are
         * combined to form the code 'n pqr' or n_pqr.
         *
         * The character string n_pqr is composed as follows:
         *
         * n refers to the symmetry operation that is applied to the
         * coordinates stored in _atom_site.fract_xyz. It must match a
         * number given in _symmetry_equiv.pos_site_id.
         *
         * p, q and r refer to the translations that are subsequently
         * applied to the symmetry transformed coordinates to generate
         * the atom used in calculating the angle. These translations
         * (x,y,z) are related to (p,q,r) by the relations
         * p = 5 + x
         * q = 5 + y
         * r = 5 + z
         */
        site_symmetry_2: cif_core_str,
        /**
         * Bond valence calculated from the bond distance.
         */
        valence: cif_core_float,
    },
    /**
     * The CATEGORY of data items used to record details about the
     * creation and subsequent updating of the data block.
     */
    audit: {
        /**
         * The digital object identifier (DOI) registered to identify
         * the data set publication represented by the current
         * datablock. This can be used as a unique identifier for
         * the datablock so long as the code used is a valid DOI
         * (i.e. begins with a valid publisher prefix assigned by a
         * Registration Agency and a suffix guaranteed to be unique
         * by the publisher) and has had its metadata deposited
         * with a DOI Registration Agency.
         *
         * A DOI is a unique character string identifying any
         * object of intellectual property. It provides a
         * persistent identifier for an object on a digital network
         * and permits the association of related current data in a
         * structured extensible way. A DOI is an implementation
         * of the Internet concepts of Uniform Resource Name and
         * Universal Resource Locator managed according to the
         * specifications of the International DOI Foundation (see
         * http://www.doi.org).
         */
        block_doi: cif_core_str,
    },
    /**
     * The CATEGORY of data items recording database deposition. These data items
     * are assigned by database managers and should only appear in a CIF if they
     * originate from that source.
     */
    database_code: {
        /**
         * Code assigned by Crystallography Open Database (COD).
         */
        COD: cif_core_str,
        /**
         * Code assigned by the Cambridge Structural Database.
         */
        CSD: cif_core_str,
        /**
         * Deposition numbers assigned by the Cambridge Crystallographic
         * Data Centre (CCDC) to files containing structural information
         * archived by the CCDC.
         */
        depnum_ccdc_archive: cif_core_str,
        /**
         * Deposition numbers assigned by the Fachinformationszentrum
         * Karlsruhe (FIZ) to files containing structural information
         * archived by the Cambridge Crystallographic Data Centre (CCDC).
         */
        depnum_ccdc_fiz: cif_core_str,
        /**
         * Code assigned by the Inorganic Crystal Structure Database.
         */
        ICSD: cif_core_str,
        /**
         * Code assigned in the Metals Data File.
         */
        MDF: cif_core_str,
        /**
         * Code assigned by the NBS (NIST) Crystal Data Database.
         */
        NBS: cif_core_str,
    },
    /**
     * The CATEGORY of data items used to describe atom site information
     * used in crystallographic structure studies.
     */
    atom_site: {
        /**
         * Code for type of atomic displacement parameters used for the site.
         */
        adp_type: cif_core_str,
        /**
         * A standard code to signal if the site coordinates have been
         * determined from the intensities or calculated from the geometry
         * of surrounding sites, or have been assigned dummy coordinates.
         */
        calc_flag: cif_core_str,
        /**
         * A code which identifies a cluster of atoms that show long range
         * positional disorder but are locally ordered. Within each such
         * cluster of atoms, _atom_site.disorder_group is used to identify
         * the sites that are simultaneously occupied. This field is only
         * needed if there is more than one cluster of disordered atoms
         * showing independent local order.
         */
        disorder_assembly: cif_core_str,
        /**
         * A code that identifies a group of positionally disordered atom
         * sites that are locally simultaneously occupied. Atoms that are
         * positionally disordered over two or more sites (e.g. the H
         * atoms of a methyl group that exists in two orientations) can
         * be assigned to two or more groups. Sites belonging to the same
         * group are simultaneously occupied, but those belonging to
         * different groups are not. A minus prefix (e.g. "-1") is used to
         * indicate sites disordered about a special position.
         */
        disorder_group: cif_core_str,
        /**
         * Atom site coordinates as fractions of the cell length values.
         */
        fract_x: cif_core_float,
        /**
         * Atom site coordinates as fractions of the cell length values.
         */
        fract_y: cif_core_float,
        /**
         * Atom site coordinates as fractions of the cell length values.
         */
        fract_z: cif_core_float,
        /**
         * This label is a unique identifier for a particular site in the
         * asymmetric unit of the crystal unit cell. It is made up of
         * components, _atom_site.label_component_0 to *_6, which may be
         * specified as separate data items. Component 0 usually matches one
         * of the specified _atom_type.symbol codes. This is not mandatory
         * if an _atom_site.type_symbol item is included in the atom site
         * list. The _atom_site.type_symbol always takes precedence over
         * an _atom_site.label in the identification of the atom type. The
         * label components 1 to 6 are optional, and normally only
         * components 0 and 1 are used. Note that components 0 and 1 are
         * concatenated, while all other components, if specified, are
         * separated by an underline character. Underline separators are
         * only used if higher-order components exist. If an intermediate
         * component is not used it may be omitted provided the underline
         * separators are inserted. For example the label 'C233__ggg' is
         * acceptable and represents the components C, 233, '', and ggg.
         * Each label may have a different number of components.
         */
        label: cif_core_str,
        /**
         * The fraction of the atom type present at this site.
         * The sum of the occupancies of all the atom types at this site
         * may not significantly exceed 1.0 unless it is a dummy site. The
         * value must lie in the 99.97% Gaussian confidence interval
         * -3u =< x =< 1 + 3u. The _enumeration.range of 0.0:1.0 is thus
         * correctly interpreted as meaning (0.0 - 3u) =< x =< (1.0 + 3u).
         */
        occupancy: cif_core_float,
        /**
         * A concatenated series of single-letter codes which indicate the
         * refinement restraints or constraints applied to this site. This
         * item should not be used. It has been replaced by
         * _atom_site.refinement_flags_posn, _adp and _occupancy. It is
         * retained in this dictionary only to provide compatibility with
         * legacy CIFs.
         */
        refinement_flags: cif_core_str,
        /**
         * The number of different sites that are generated by the
         * application of the space-group symmetry to the coordinates
         * given for this site. It is equal to the multiplicity given
         * for this Wyckoff site in International Tables for Cryst.
         * Vol. A (2002). It is equal to the multiplicity of the general
         * position divided by the order of the site symmetry given in
         * _atom_site.site_symmetry_order.
         */
        site_symmetry_multiplicity: cif_core_int,
        /**
         * A code to identify the atom specie(s) occupying this site.
         * This code must match a corresponding _atom_type.symbol. The
         * specification of this code is optional if component_0 of the
         * _atom_site.label is used for this purpose. See _atom_type.symbol.
         */
        type_symbol: cif_core_str,
        /**
         * Isotropic atomic displacement parameter, or equivalent isotropic
         * atomic  displacement parameter, U(equiv), in angstroms squared,
         * calculated from anisotropic atomic displacement  parameters.
         *
         * U(equiv) = (1/3) sum~i~[sum~j~(U^ij^ a*~i~ a*~j~ a~i~ a~j~)]
         *
         * a  = the real-space cell lengths
         * a* = the reciprocal-space cell lengths
         * Ref: Fischer, R. X. & Tillmanns, E. (1988). Acta Cryst. C44, 775-776.
         */
        U_iso_or_equiv: cif_core_float,
    },
    /**
     * The CATEGORY of data items used to describe the anisotropic
     * thermal parameters of the atomic sites in a crystal structure.
     */
    atom_site_aniso: {
        /**
         * Anisotropic atomic displacement parameters are usually looped in
         * a separate list. If this is the case, this code must match the
         * _atom_site.label of the associated atom in the atom coordinate
         * list and conform with the same rules described in _atom_site.label.
         */
        label: cif_core_str,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_11: cif_core_float,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U: Matrix(3, 3),
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_11_su: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_su: Matrix(3, 3),
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_12: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_12_su: cif_core_float,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_13: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_13_su: cif_core_float,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_22: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_22_su: cif_core_float,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_23: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_23_su: cif_core_float,
        /**
         * These are the standard anisotropic atomic displacement
         * components in angstroms squared which appear in the
         * structure factor term:
         *
         * T = exp{-2pi^2^ sum~i~ [sum~j~ (U^ij^ h~i~ h~j~ a*~i~ a*~j~) ] }
         *
         * h = the Miller indices
         * a* = the reciprocal-space cell lengths
         *
         * The unique elements of the real symmetric matrix are entered by row.
         */
        U_33: cif_core_float,
        /**
         * These are the standard uncertainty values (SU) for the standard
         * form of the Uij anisotropic atomic displacement components (see
         * _aniso_UIJ. Because these values are TYPE measurand, the su values
         * may in practice be auto generated as part of the Uij calculation.
         */
        U_33_su: cif_core_float,
    },
    /**
     * The CATEGORY of data items used to describe atomic type information
     * used in crystallographic structure studies.
     */
    atom_type: {
        /**
         * A description of the atom(s) designated by this atom type. In
         * most cases this will be the element name and oxidation state of
         * a single atom  species. For disordered or nonstoichiometric
         * structures it will describe a combination of atom species.
         */
        description: cif_core_str,
        /**
         * The identity of the atom specie(s) representing this atom type.
         * Normally this code is the element symbol followed by the charge
         * if there is one. The symbol may be composed of any character except
         * an underline or a blank, with the proviso that digits designate an
         * oxidation state and must be followed by a + or - character.
         */
        symbol: cif_core_str,
    },
    /**
     * The CATEGORY of data items used to describe atomic scattering
     * information used in crystallographic structure studies.
     */
    atom_type_scat: {
        /**
         * The imaginary component of the anomalous dispersion scattering factors
         * for this atom type and radiation by _diffrn_radiation_wavelength.value
         */
        dispersion_imag: cif_core_float,
        /**
         * The real component of the anomalous dispersion scattering factors
         * for this atom type and radiation by _diffrn_radiation_wavelength.value
         */
        dispersion_real: cif_core_float,
        /**
         * Reference to source of scattering factors used for this atom type.
         */
        source: cif_core_str,
    },
};
var CifCore_Aliases = {
    'atom_site_aniso.U': [
        'atom_site_anisotrop_U',
    ],
    'atom_site_aniso.U_su': [
        'atom_site_aniso_U_esd',
        'atom_site_anisotrop_U_esd',
    ],
    'space_group.IT_number': [
        'symmetry_Int_Tables_number',
    ],
    'space_group.name_H-M_full': [
        'symmetry_space_group_name_H-M',
    ],
    'space_group_symop.operation_xyz': [
        'symmetry_equiv_pos_as_xyz',
    ],
    'geom_bond.atom_site_label_1': [
        'geom_bond_atom_site_id_1',
    ],
    'geom_bond.atom_site_label_2': [
        'geom_bond_atom_site_id_2',
    ],
    'geom_bond.distance': [
        'geom_bond_dist',
    ],
    'atom_site.adp_type': [
        'atom_site_thermal_displace_type',
    ],
    'atom_site.label': [
        'atom_site_id',
    ],
    'atom_site.site_symmetry_multiplicity': [
        'atom_site_symmetry_multiplicity',
    ],
    'atom_site_aniso.label': [
        'atom_site_anisotrop_id',
    ],
    'atom_site_aniso.U_11': [
        'atom_site_anisotrop_U_11',
    ],
    'atom_site_aniso.U_11_su': [
        'atom_site_aniso_U_11_esd',
        'atom_site_anisotrop_U_11_esd',
    ],
    'atom_site_aniso.U_12': [
        'atom_site_anisotrop_U_12',
    ],
    'atom_site_aniso.U_12_su': [
        'atom_site_aniso_U_12_esd',
        'atom_site_anisotrop_U_12_esd',
    ],
    'atom_site_aniso.U_13': [
        'atom_site_anisotrop_U_13',
    ],
    'atom_site_aniso.U_13_su': [
        'atom_site_aniso_U_13_esd',
        'atom_site_anisotrop_U_13_esd',
    ],
    'atom_site_aniso.U_22': [
        'atom_site_anisotrop_U_22',
    ],
    'atom_site_aniso.U_22_su': [
        'atom_site_aniso_U_22_esd',
        'atom_site_anisotrop_U_22_esd',
    ],
    'atom_site_aniso.U_23': [
        'atom_site_anisotrop_U_23',
    ],
    'atom_site_aniso.U_23_su': [
        'atom_site_aniso_U_23_esd',
        'atom_site_anisotrop_U_23_esd',
    ],
    'atom_site_aniso.U_33': [
        'atom_site_anisotrop_U_33',
    ],
    'atom_site_aniso.U_33_su': [
        'atom_site_aniso_U_33_esd',
        'atom_site_anisotrop_U_33_esd',
    ],
};
;
//# sourceMappingURL=cif-core.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var CIF = {
    parse: function (data) { return typeof data === 'string' ? parse(data) : parser_parse(data); },
    parseText: parse,
    parseBinary: parser_parse,
    toDatabaseCollection: schema["toDatabaseCollection"],
    toDatabase: schema["toDatabase"],
    schema: {
        mmCIF: function (frame) { return Object(schema["toDatabase"])(mmcif["a" /* mmCIF_Schema */], frame); },
        CCD: function (frame) { return Object(schema["toDatabase"])(CCD_Schema, frame); },
        BIRD: function (frame) { return Object(schema["toDatabase"])(BIRD_Schema, frame); },
        dic: function (frame) { return Object(schema["toDatabase"])(dic_dic_Schema, frame); },
        cifCore: function (frame) { return Object(schema["toDatabase"])(CifCore_Schema, frame, CifCore_Aliases); },
        densityServer: function (frame) { return Object(schema["toDatabase"])(DensityServer_Data_Schema, frame); },
    }
};

//# sourceMappingURL=cif.js.map

/***/ }),
/* 32 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginReactContext", function() { return PluginReactContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginUIComponent", function() { return PluginUIComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PurePluginUIComponent", function() { return PurePluginUIComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CollapsableControls", function() { return CollapsableControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var PluginReactContext = react__WEBPACK_IMPORTED_MODULE_1__["createContext"](void 0);
var PluginUIComponent = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PluginUIComponent, _super);
    function PluginUIComponent(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.subs = void 0;
        _this.plugin = context;
        if (_this.init)
            _this.init();
        return _this;
    }
    PluginUIComponent.prototype.subscribe = function (obs, action) {
        if (typeof this.subs === 'undefined')
            this.subs = [];
        this.subs.push(obs.subscribe(action));
    };
    PluginUIComponent.prototype.componentWillUnmount = function () {
        if (!this.subs)
            return;
        for (var _i = 0, _a = this.subs; _i < _a.length; _i++) {
            var s = _a[_i];
            s.unsubscribe();
        }
        this.subs = void 0;
    };
    PluginUIComponent.contextType = PluginReactContext;
    return PluginUIComponent;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

var PurePluginUIComponent = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PurePluginUIComponent, _super);
    function PurePluginUIComponent(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.subs = void 0;
        _this.plugin = context;
        if (_this.init)
            _this.init();
        return _this;
    }
    PurePluginUIComponent.prototype.subscribe = function (obs, action) {
        if (typeof this.subs === 'undefined')
            this.subs = [];
        this.subs.push(obs.subscribe(action));
    };
    PurePluginUIComponent.prototype.componentWillUnmount = function () {
        if (!this.subs)
            return;
        for (var _i = 0, _a = this.subs; _i < _a.length; _i++) {
            var s = _a[_i];
            s.unsubscribe();
        }
        this.subs = void 0;
    };
    PurePluginUIComponent.contextType = PluginReactContext;
    return PurePluginUIComponent;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var CollapsableControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CollapsableControls, _super);
    function CollapsableControls(props, context) {
        var _this = _super.call(this, props, context) || this;
        _this.toggleCollapsed = function () {
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
        };
        var state = _this.defaultState();
        if (props.initiallyCollapsed !== undefined)
            state.isCollapsed = props.initiallyCollapsed;
        if (props.header !== undefined)
            state.header = props.header;
        _this.state = state;
        return _this;
    }
    CollapsableControls.prototype.componentDidUpdate = function (prevProps) {
        if (this.props.initiallyCollapsed !== undefined && prevProps.initiallyCollapsed !== this.props.initiallyCollapsed) {
            this.setState({ isCollapsed: this.props.initiallyCollapsed });
        }
    };
    CollapsableControls.prototype.render = function () {
        var _a;
        if (this.state.isHidden)
            return null;
        var wrapClass = this.state.isCollapsed
            ? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
            : 'msp-transform-wrapper';
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: wrapClass },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-transform-header' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { icon: this.state.brand ? void 0 : this.state.isCollapsed ? _controls_icons__WEBPACK_IMPORTED_MODULE_3__["ArrowRightSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_3__["ArrowDropDownSvg"], noOverflow: true, onClick: this.toggleCollapsed, className: this.state.brand ? "msp-transform-header-brand msp-transform-header-brand-" + this.state.brand.accent : void 0, title: "Click to " + (this.state.isCollapsed ? 'expand' : 'collapse') },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: (_a = this.state.brand) === null || _a === void 0 ? void 0 : _a.svg, inline: true }),
                    this.state.header,
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("small", { style: { margin: '0 6px' } }, this.state.isCollapsed ? '' : this.state.description))),
            !this.state.isCollapsed && this.renderControls());
    };
    return CollapsableControls;
}(PluginUIComponent));

//# sourceMappingURL=base.js.map

/***/ }),
/* 33 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export VisualQualityInfo */
/* unused harmony export VisualQualityNames */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return VisualQualityOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BaseGeometry; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _util_location_iterator__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(86);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _transform_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(182);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(47);
/* harmony import */ var _mol_model_location__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(144);
/* harmony import */ var _mol_theme_color_uniform__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(355);
/* harmony import */ var _mol_theme_size_uniform__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(356);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var VisualQualityInfo = {
    'custom': {},
    'auto': {},
    'highest': {},
    'higher': {},
    'high': {},
    'medium': {},
    'low': {},
    'lower': {},
    'lowest': {},
};
var VisualQualityNames = Object.keys(VisualQualityInfo);
var VisualQualityOptions = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].arrayToOptions(VisualQualityNames);
//
var BaseGeometry;
(function (BaseGeometry) {
    BaseGeometry.Params = {
        alpha: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Numeric(1, { min: 0, max: 1, step: 0.01 }, { label: 'Opacity', isEssential: true, description: 'How opaque/transparent the representation is rendered.' }),
        quality: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Select('auto', VisualQualityOptions, { isEssential: true, description: 'Visual/rendering quality of the representation.' }),
    };
    BaseGeometry.ShadingCategory = { category: 'Shading' };
    BaseGeometry.CustomQualityParamInfo = {
        category: 'Custom Quality',
        hideIf: function (params) { return typeof params.quality !== 'undefined' && params.quality !== 'custom'; }
    };
    function createSimple(colorValue, sizeValue, transform) {
        if (colorValue === void 0) { colorValue = _mol_util_color_names__WEBPACK_IMPORTED_MODULE_4__[/* ColorNames */ "a"].grey; }
        if (sizeValue === void 0) { sizeValue = 1; }
        if (!transform)
            transform = Object(_transform_data__WEBPACK_IMPORTED_MODULE_3__[/* createIdentityTransform */ "a"])();
        var locationIterator = Object(_util_location_iterator__WEBPACK_IMPORTED_MODULE_1__[/* LocationIterator */ "a"])(1, transform.instanceCount.ref.value, function () { return _mol_model_location__WEBPACK_IMPORTED_MODULE_5__[/* NullLocation */ "b"]; }, false, function () { return false; });
        var theme = {
            color: Object(_mol_theme_color_uniform__WEBPACK_IMPORTED_MODULE_6__[/* UniformColorTheme */ "a"])({}, { value: colorValue }),
            size: Object(_mol_theme_size_uniform__WEBPACK_IMPORTED_MODULE_7__[/* UniformSizeTheme */ "a"])({}, { value: sizeValue })
        };
        return { transform: transform, locationIterator: locationIterator, theme: theme };
    }
    BaseGeometry.createSimple = createSimple;
    function createValues(props, counts) {
        return {
            alpha: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(props.alpha),
            uAlpha: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(props.alpha),
            uGroupCount: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(counts.groupCount),
            drawCount: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(counts.drawCount),
        };
    }
    BaseGeometry.createValues = createValues;
    function updateValues(values, props) {
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].updateIfChanged(values.alpha, props.alpha); // `uAlpha` is set in renderable.render
    }
    BaseGeometry.updateValues = updateValues;
    function createRenderableState(props) {
        if (props === void 0) { props = {}; }
        var opaque = props.alpha === undefined ? true : props.alpha === 1;
        return {
            visible: true,
            alphaFactor: 1,
            pickable: true,
            opaque: opaque,
            writeDepth: opaque,
        };
    }
    BaseGeometry.createRenderableState = createRenderableState;
    function updateRenderableState(state, props) {
        state.opaque = props.alpha * state.alphaFactor >= 1;
        state.writeDepth = state.opaque;
    }
    BaseGeometry.updateRenderableState = updateRenderableState;
})(BaseGeometry || (BaseGeometry = {}));
//# sourceMappingURL=base.js.map

/***/ }),
/* 34 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MeshBuilder; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9);
/* harmony import */ var _mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(39);
/* harmony import */ var _builder_sphere__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(75);
/* harmony import */ var _builder_cylinder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(81);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var tmpV = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var tmpMat3 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat3"].zero();
var tmpVecA = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var tmpVecB = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var tmpVecC = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var tmpVecD = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var MeshBuilder;
(function (MeshBuilder) {
    function createState(initialCount, chunkSize, mesh) {
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        return {
            currentGroup: -1,
            vertices: _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].create(Float32Array, 3, chunkSize, mesh ? mesh.vertexBuffer.ref.value : initialCount),
            normals: _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].create(Float32Array, 3, chunkSize, mesh ? mesh.normalBuffer.ref.value : initialCount),
            indices: _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].create(Uint32Array, 3, chunkSize * 3, mesh ? mesh.indexBuffer.ref.value : initialCount * 3),
            groups: _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].create(Float32Array, 1, chunkSize, mesh ? mesh.groupBuffer.ref.value : initialCount),
            mesh: mesh
        };
    }
    MeshBuilder.createState = createState;
    function addTriangle(state, a, b, c) {
        var vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups, currentGroup = state.currentGroup;
        var offset = vertices.elementCount;
        // positions
        _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(vertices, a[0], a[1], a[2]);
        _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(vertices, b[0], b[1], b[2]);
        _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(vertices, c[0], c[1], c[2]);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].triangleNormal(tmpV, a, b, c);
        for (var i = 0; i < 3; ++i) {
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(normals, tmpV[0], tmpV[1], tmpV[2]); // normal
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add(groups, currentGroup); // group
        }
        _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(indices, offset, offset + 1, offset + 2);
    }
    MeshBuilder.addTriangle = addTriangle;
    function addTriangleStrip(state, vertices, indices) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecC, vertices, indices[0] * 3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecD, vertices, indices[1] * 3);
        for (var i = 2, il = indices.length; i < il; i += 2) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].copy(tmpVecA, tmpVecC);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].copy(tmpVecB, tmpVecD);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecC, vertices, indices[i] * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecD, vertices, indices[i + 1] * 3);
            addTriangle(state, tmpVecA, tmpVecB, tmpVecC);
            addTriangle(state, tmpVecB, tmpVecD, tmpVecC);
        }
    }
    MeshBuilder.addTriangleStrip = addTriangleStrip;
    function addTriangleFan(state, vertices, indices) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecA, vertices, indices[0] * 3);
        for (var i = 2, il = indices.length; i < il; ++i) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecB, vertices, indices[i - 1] * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecC, vertices, indices[i] * 3);
            addTriangle(state, tmpVecA, tmpVecC, tmpVecB);
        }
    }
    MeshBuilder.addTriangleFan = addTriangleFan;
    function addPrimitive(state, t, primitive) {
        var va = primitive.vertices, na = primitive.normals, ia = primitive.indices;
        var vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups, currentGroup = state.currentGroup;
        var offset = vertices.elementCount;
        var n = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat3"].directionTransform(tmpMat3, t);
        for (var i = 0, il = va.length; i < il; i += 3) {
            // position
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, va, i), t);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(vertices, tmpV[0], tmpV[1], tmpV[2]);
            // normal
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat3(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, na, i), n);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(normals, tmpV[0], tmpV[1], tmpV[2]);
            // group
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add(groups, currentGroup);
        }
        for (var i = 0, il = ia.length; i < il; i += 3) {
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(indices, ia[i] + offset, ia[i + 1] + offset, ia[i + 2] + offset);
        }
    }
    MeshBuilder.addPrimitive = addPrimitive;
    /** Flips triangle normals and winding order */
    function addPrimitiveFlipped(state, t, primitive) {
        var va = primitive.vertices, na = primitive.normals, ia = primitive.indices;
        var vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups, currentGroup = state.currentGroup;
        var offset = vertices.elementCount;
        var n = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat3"].directionTransform(tmpMat3, t);
        for (var i = 0, il = va.length; i < il; i += 3) {
            // position
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, va, i), t);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(vertices, tmpV[0], tmpV[1], tmpV[2]);
            // normal
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat3(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, na, i), n);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(normals, -tmpV[0], -tmpV[1], -tmpV[2]);
            // group
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add(groups, currentGroup);
        }
        for (var i = 0, il = ia.length; i < il; i += 3) {
            _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].add3(indices, ia[i + 2] + offset, ia[i + 1] + offset, ia[i] + offset);
        }
    }
    MeshBuilder.addPrimitiveFlipped = addPrimitiveFlipped;
    function addCage(state, t, cage, radius, detail, radialSegments) {
        var va = cage.vertices, ea = cage.edges;
        var cylinderProps = { radiusTop: radius, radiusBottom: radius, radialSegments: radialSegments };
        for (var i = 0, il = ea.length; i < il; i += 2) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecA, va, ea[i] * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpVecB, va, ea[i + 1] * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpVecA, tmpVecA, t);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpVecB, tmpVecB, t);
            Object(_builder_sphere__WEBPACK_IMPORTED_MODULE_3__[/* addSphere */ "a"])(state, tmpVecA, radius, detail);
            Object(_builder_sphere__WEBPACK_IMPORTED_MODULE_3__[/* addSphere */ "a"])(state, tmpVecB, radius, detail);
            Object(_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addCylinder */ "a"])(state, tmpVecA, tmpVecB, 1, cylinderProps);
        }
    }
    MeshBuilder.addCage = addCage;
    function getMesh(state) {
        var vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups, mesh = state.mesh;
        var vb = _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].compact(vertices, true);
        var ib = _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].compact(indices, true);
        var nb = _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].compact(normals, true);
        var gb = _mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* ChunkedArray */ "a"].compact(groups, true);
        return _mesh__WEBPACK_IMPORTED_MODULE_2__[/* Mesh */ "a"].create(vb, ib, nb, gb, state.vertices.elementCount, state.indices.elementCount, mesh);
    }
    MeshBuilder.getMesh = getMesh;
})(MeshBuilder || (MeshBuilder = {}));
//# sourceMappingURL=mesh-builder.js.map

/***/ }),
/* 35 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscriber; });
/* unused harmony export SafeSubscriber */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(215);
/* harmony import */ var _Observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(313);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(277);
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(175);
/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(248);
/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */







var Subscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](Subscriber, _super);
    function Subscriber(destinationOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this.syncErrorValue = null;
        _this.syncErrorThrown = false;
        _this.syncErrorThrowable = false;
        _this.isStopped = false;
        switch (arguments.length) {
            case 0:
                _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__[/* empty */ "a"];
                break;
            case 1:
                if (!destinationOrNext) {
                    _this.destination = _Observer__WEBPACK_IMPORTED_MODULE_2__[/* empty */ "a"];
                    break;
                }
                if (typeof destinationOrNext === 'object') {
                    if (destinationOrNext instanceof Subscriber) {
                        _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;
                        _this.destination = destinationOrNext;
                        destinationOrNext.add(_this);
                    }
                    else {
                        _this.syncErrorThrowable = true;
                        _this.destination = new SafeSubscriber(_this, destinationOrNext);
                    }
                    break;
                }
            default:
                _this.syncErrorThrowable = true;
                _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete);
                break;
        }
        return _this;
    }
    Subscriber.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_4__[/* rxSubscriber */ "a"]] = function () { return this; };
    Subscriber.create = function (next, error, complete) {
        var subscriber = new Subscriber(next, error, complete);
        subscriber.syncErrorThrowable = false;
        return subscriber;
    };
    Subscriber.prototype.next = function (value) {
        if (!this.isStopped) {
            this._next(value);
        }
    };
    Subscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            this.isStopped = true;
            this._error(err);
        }
    };
    Subscriber.prototype.complete = function () {
        if (!this.isStopped) {
            this.isStopped = true;
            this._complete();
        }
    };
    Subscriber.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.isStopped = true;
        _super.prototype.unsubscribe.call(this);
    };
    Subscriber.prototype._next = function (value) {
        this.destination.next(value);
    };
    Subscriber.prototype._error = function (err) {
        this.destination.error(err);
        this.unsubscribe();
    };
    Subscriber.prototype._complete = function () {
        this.destination.complete();
        this.unsubscribe();
    };
    Subscriber.prototype._unsubscribeAndRecycle = function () {
        var _parentOrParents = this._parentOrParents;
        this._parentOrParents = null;
        this.unsubscribe();
        this.closed = false;
        this.isStopped = false;
        this._parentOrParents = _parentOrParents;
        return this;
    };
    return Subscriber;
}(_Subscription__WEBPACK_IMPORTED_MODULE_3__[/* Subscription */ "a"]));

var SafeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](SafeSubscriber, _super);
    function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) {
        var _this = _super.call(this) || this;
        _this._parentSubscriber = _parentSubscriber;
        var next;
        var context = _this;
        if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__[/* isFunction */ "a"])(observerOrNext)) {
            next = observerOrNext;
        }
        else if (observerOrNext) {
            next = observerOrNext.next;
            error = observerOrNext.error;
            complete = observerOrNext.complete;
            if (observerOrNext !== _Observer__WEBPACK_IMPORTED_MODULE_2__[/* empty */ "a"]) {
                context = Object.create(observerOrNext);
                if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_1__[/* isFunction */ "a"])(context.unsubscribe)) {
                    _this.add(context.unsubscribe.bind(context));
                }
                context.unsubscribe = _this.unsubscribe.bind(_this);
            }
        }
        _this._context = context;
        _this._next = next;
        _this._error = error;
        _this._complete = complete;
        return _this;
    }
    SafeSubscriber.prototype.next = function (value) {
        if (!this.isStopped && this._next) {
            var _parentSubscriber = this._parentSubscriber;
            if (!_config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                this.__tryOrUnsub(this._next, value);
            }
            else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            var useDeprecatedSynchronousErrorHandling = _config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling;
            if (this._error) {
                if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(this._error, err);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, this._error, err);
                    this.unsubscribe();
                }
            }
            else if (!_parentSubscriber.syncErrorThrowable) {
                this.unsubscribe();
                if (useDeprecatedSynchronousErrorHandling) {
                    throw err;
                }
                Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__[/* hostReportError */ "a"])(err);
            }
            else {
                if (useDeprecatedSynchronousErrorHandling) {
                    _parentSubscriber.syncErrorValue = err;
                    _parentSubscriber.syncErrorThrown = true;
                }
                else {
                    Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__[/* hostReportError */ "a"])(err);
                }
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.complete = function () {
        var _this = this;
        if (!this.isStopped) {
            var _parentSubscriber = this._parentSubscriber;
            if (this._complete) {
                var wrappedComplete = function () { return _this._complete.call(_this._context); };
                if (!_config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {
                    this.__tryOrUnsub(wrappedComplete);
                    this.unsubscribe();
                }
                else {
                    this.__tryOrSetError(_parentSubscriber, wrappedComplete);
                    this.unsubscribe();
                }
            }
            else {
                this.unsubscribe();
            }
        }
    };
    SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) {
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            this.unsubscribe();
            if (_config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling) {
                throw err;
            }
            else {
                Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__[/* hostReportError */ "a"])(err);
            }
        }
    };
    SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) {
        if (!_config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling) {
            throw new Error('bad call');
        }
        try {
            fn.call(this._context, value);
        }
        catch (err) {
            if (_config__WEBPACK_IMPORTED_MODULE_5__[/* config */ "a"].useDeprecatedSynchronousErrorHandling) {
                parent.syncErrorValue = err;
                parent.syncErrorThrown = true;
                return true;
            }
            else {
                Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_6__[/* hostReportError */ "a"])(err);
                return true;
            }
        }
        return false;
    };
    SafeSubscriber.prototype._unsubscribe = function () {
        var _parentSubscriber = this._parentSubscriber;
        this._context = null;
        this._parentSubscriber = null;
        _parentSubscriber.unsubscribe();
    };
    return SafeSubscriber;
}(Subscriber));

//# sourceMappingURL=Subscriber.js.map


/***/ }),
/* 36 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _volume_volume__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(138);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "b", function() { return _volume_volume__WEBPACK_IMPORTED_MODULE_0__["a"]; });

/* harmony import */ var _volume_grid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(249);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _volume_grid__WEBPACK_IMPORTED_MODULE_1__["a"]; });

/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


//# sourceMappingURL=volume.js.map

/***/ }),
/* 37 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/symmetry-operator.js
var symmetry_operator = __webpack_require__(136);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds.js + 3 modules
var bonds = __webpack_require__(159);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/rings.js + 1 modules
var rings = __webpack_require__(201);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int/sorted-ranges.js
var sorted_ranges = __webpack_require__(79);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/polymer.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getAtomicPolymerElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model;
    var residueAtomSegments = unit.model.atomicHierarchy.residueAtomSegments;
    var traceElementIndex = model.atomicHierarchy.derived.residue.traceElementIndex;
    var polymerIt = sorted_ranges["a" /* default */].transientSegments(unit.model.atomicRanges.polymerRanges, elements);
    var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
    while (polymerIt.hasNext) {
        var polymerSegment = polymerIt.move();
        residueIt.setSegment(polymerSegment);
        while (residueIt.hasNext) {
            var residueSegment = residueIt.move();
            var start = residueSegment.start, end = residueSegment.end, index = residueSegment.index;
            if (mol_data_int["OrderedSet"].areIntersecting(mol_data_int["Interval"].ofRange(elements[start], elements[end - 1]), elements)) {
                var elementIndex = traceElementIndex[index];
                indices.push(elementIndex === -1 ? residueAtomSegments.offsets[index] : elementIndex);
            }
        }
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
function getCoarsePolymerElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model;
    var _a = model.coarseHierarchy, spheres = _a.spheres, gaussians = _a.gaussians;
    var polymerRanges = structure["Unit"].isSpheres(unit) ? spheres.polymerRanges : gaussians.polymerRanges;
    var polymerIt = sorted_ranges["a" /* default */].transientSegments(polymerRanges, elements);
    while (polymerIt.hasNext) {
        var _b = polymerIt.move(), start = _b.start, end = _b.end;
        for (var i = start; i < end; ++i) {
            indices.push(elements[i]);
        }
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
//
function getAtomicGapElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model, residueIndex = unit.residueIndex;
    var residueAtomSegments = unit.model.atomicHierarchy.residueAtomSegments;
    var traceElementIndex = model.atomicHierarchy.derived.residue.traceElementIndex;
    var gapIt = sorted_ranges["a" /* default */].transientSegments(unit.model.atomicRanges.gapRanges, unit.elements);
    while (gapIt.hasNext) {
        var gapSegment = gapIt.move();
        var indexStart = residueIndex[elements[gapSegment.start]];
        var indexEnd = residueIndex[elements[gapSegment.end - 1]];
        var elementIndexStart = traceElementIndex[indexStart];
        var elementIndexEnd = traceElementIndex[indexEnd];
        indices.push(elementIndexStart === -1 ? residueAtomSegments.offsets[indexStart] : elementIndexStart);
        indices.push(elementIndexEnd === -1 ? residueAtomSegments.offsets[indexEnd] : elementIndexEnd);
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
function getCoarseGapElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model;
    var _a = model.coarseHierarchy, spheres = _a.spheres, gaussians = _a.gaussians;
    var gapRanges = structure["Unit"].isSpheres(unit) ? spheres.gapRanges : gaussians.gapRanges;
    var gapIt = sorted_ranges["a" /* default */].transientSegments(gapRanges, elements);
    while (gapIt.hasNext) {
        var _b = gapIt.move(), start = _b.start, end = _b.end;
        indices.push(elements[start], elements[end - 1]);
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
//
function getNucleotideElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model;
    var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments;
    var _b = model.atomicHierarchy.derived.residue, moleculeType = _b.moleculeType, traceElementIndex = _b.traceElementIndex;
    var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, elements);
    var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
    while (chainIt.hasNext) {
        residueIt.setSegment(chainIt.move());
        while (residueIt.hasNext) {
            var index = residueIt.move().index;
            if (Object(types["isNucleic"])(moleculeType[index])) {
                var elementIndex = traceElementIndex[index];
                indices.push(elementIndex === -1 ? residueAtomSegments.offsets[index] : elementIndex);
            }
        }
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
function getProteinElements(unit) {
    var indices = [];
    var elements = unit.elements, model = unit.model;
    var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments;
    var _b = model.atomicHierarchy.derived.residue, moleculeType = _b.moleculeType, traceElementIndex = _b.traceElementIndex;
    var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, elements);
    var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
    while (chainIt.hasNext) {
        residueIt.setSegment(chainIt.move());
        while (residueIt.hasNext) {
            var index = residueIt.move().index;
            if (Object(types["isProtein"])(moleculeType[index])) {
                var elementIndex = traceElementIndex[index];
                indices.push(elementIndex === -1 ? residueAtomSegments.offsets[index] : elementIndex);
            }
        }
    }
    return mol_data_int["SortedArray"].ofSortedArray(indices);
}
//# sourceMappingURL=polymer.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/principal-axes.js + 1 modules
var principal_axes = __webpack_require__(227);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/principal-axes.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var tempPos = linear_algebra["Vec3"].zero();
function toPositionsArray(unit) {
    var pos = unit.conformation.invariantPosition;
    var elements = unit.elements;
    var positions = new Float32Array(elements.length * 3);
    for (var i = 0, il = elements.length; i < il; i++) {
        pos(elements[i], tempPos);
        linear_algebra["Vec3"].toArray(tempPos, positions, i * 3);
    }
    return positions;
}
function getPrincipalAxes(unit) {
    var positions = toPositionsArray(unit);
    return principal_axes["a" /* PrincipalAxes */].ofPositions(positions);
}
//# sourceMappingURL=principal-axes.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary.js
var boundary = __webpack_require__(185);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var unit_Unit;
(function (Unit) {
    function isAtomic(u) { return u.kind === 0 /* Atomic */; }
    Unit.isAtomic = isAtomic;
    function isCoarse(u) { return u.kind === 1 /* Spheres */ || u.kind === 2 /* Gaussians */; }
    Unit.isCoarse = isCoarse;
    function isSpheres(u) { return u.kind === 1 /* Spheres */; }
    Unit.isSpheres = isSpheres;
    function isGaussians(u) { return u.kind === 2 /* Gaussians */; }
    Unit.isGaussians = isGaussians;
    function create(id, invariantId, chainGroupId, traits, kind, model, operator, elements) {
        switch (kind) {
            case 0 /* Atomic */: return new Atomic(id, invariantId, chainGroupId, traits, model, elements, symmetry_operator["a" /* SymmetryOperator */].createMapping(operator, model.atomicConformation, void 0), AtomicProperties());
            case 1 /* Spheres */: return createCoarse(id, invariantId, chainGroupId, traits, model, 1 /* Spheres */, elements, symmetry_operator["a" /* SymmetryOperator */].createMapping(operator, model.coarseConformation.spheres, getSphereRadiusFunc(model)), CoarseProperties());
            case 2 /* Gaussians */: return createCoarse(id, invariantId, chainGroupId, traits, model, 2 /* Gaussians */, elements, symmetry_operator["a" /* SymmetryOperator */].createMapping(operator, model.coarseConformation.gaussians, getGaussianRadiusFunc(model)), CoarseProperties());
        }
    }
    Unit.create = create;
    function getUnitIndexMap(units) {
        var unitIndexMap = mol_data_int["IntMap"].Mutable();
        for (var i = 0, _i = units.length; i < _i; i++) {
            unitIndexMap.set(units[i].id, i);
        }
        return unitIndexMap;
    }
    function SymmetryGroup(units) {
        var props = {};
        return {
            elements: units[0].elements,
            units: units,
            get unitIndexMap() {
                if (props.unitIndexMap)
                    return props.unitIndexMap;
                props.unitIndexMap = getUnitIndexMap(units);
                return props.unitIndexMap;
            },
            hashCode: hashUnit(units[0]),
            transformHash: Object(util["l" /* hashFnv32a */])(units.map(function (u) { return u.id; }))
        };
    }
    Unit.SymmetryGroup = SymmetryGroup;
    (function (SymmetryGroup) {
        function areInvariantElementsEqual(a, b) {
            if (a.hashCode !== b.hashCode)
                return false;
            return mol_data_int["SortedArray"].areEqual(a.elements, b.elements);
        }
        SymmetryGroup.areInvariantElementsEqual = areInvariantElementsEqual;
        function getUnitSymmetryGroupsIndexMap(symmetryGroups) {
            var unitSymmetryGroupsIndexMap = mol_data_int["IntMap"].Mutable();
            for (var i = 0, _i = symmetryGroups.length; i < _i; i++) {
                unitSymmetryGroupsIndexMap.set(symmetryGroups[i].units[0].invariantId, i);
            }
            return unitSymmetryGroupsIndexMap;
        }
        SymmetryGroup.getUnitSymmetryGroupsIndexMap = getUnitSymmetryGroupsIndexMap;
    })(SymmetryGroup = Unit.SymmetryGroup || (Unit.SymmetryGroup = {}));
    function conformationId(unit) {
        return Unit.isAtomic(unit) ? unit.model.atomicConformation.id : unit.model.coarseConformation.id;
    }
    Unit.conformationId = conformationId;
    function hashUnit(u) {
        return Object(util["i" /* hash2 */])(u.invariantId, mol_data_int["SortedArray"].hashCode(u.elements));
    }
    Unit.hashUnit = hashUnit;
    var Traits;
    (function (Traits) {
        Traits.is = mol_util["a" /* BitFlags */].has;
        Traits.create = mol_util["a" /* BitFlags */].create;
    })(Traits = Unit.Traits || (Unit.Traits = {}));
    function BaseProperties() {
        return {
            boundary: mol_util["f" /* ValueRef */].create(void 0),
            lookup3d: mol_util["f" /* ValueRef */].create(void 0),
            principalAxes: mol_util["f" /* ValueRef */].create(void 0),
            polymerElements: mol_util["f" /* ValueRef */].create(void 0),
            gapElements: mol_util["f" /* ValueRef */].create(void 0),
        };
    }
    function getSphereRadiusFunc(model) {
        var r = model.coarseConformation.spheres.radius;
        return function (i) { return r[i]; };
    }
    function getGaussianRadiusFunc(model) {
        // TODO: compute radius for gaussians
        return function (i) { return 0; };
    }
    /**
     * A bulding block of a structure that corresponds
     * to a "natural group of atoms" (most often a "chain")
     * together with a transformation (rotation and translation)
     * that is dynamically applied to the underlying atom set.
     *
     * An atom set can be referenced by multiple different units which
     * makes construction of assemblies and spacegroups very efficient.
     */
    var Atomic = /** @class */ (function () {
        function Atomic(id, invariantId, chainGroupId, traits, model, elements, conformation, props) {
            this.kind = 0 /* Atomic */;
            this.objectPrimitive = 'atomistic';
            this.id = id;
            this.invariantId = invariantId;
            this.chainGroupId = chainGroupId;
            this.traits = traits;
            this.model = model;
            this.elements = elements;
            this.conformation = conformation;
            this.residueIndex = model.atomicHierarchy.residueAtomSegments.index;
            this.chainIndex = model.atomicHierarchy.chainAtomSegments.index;
            this.props = props;
        }
        Atomic.prototype.getChild = function (elements) {
            if (elements.length === this.elements.length)
                return this;
            return new Atomic(this.id, this.invariantId, this.chainGroupId, this.traits, this.model, elements, this.conformation, AtomicProperties());
        };
        Atomic.prototype.applyOperator = function (id, operator, dontCompose) {
            if (dontCompose === void 0) { dontCompose = false; }
            var op = dontCompose ? operator : symmetry_operator["a" /* SymmetryOperator */].compose(this.conformation.operator, operator);
            return new Atomic(id, this.invariantId, this.chainGroupId, this.traits, this.model, this.elements, symmetry_operator["a" /* SymmetryOperator */].createMapping(op, this.model.atomicConformation, this.conformation.r), this.props);
        };
        Object.defineProperty(Atomic.prototype, "boundary", {
            get: function () {
                if (this.props.boundary.ref)
                    return this.props.boundary.ref;
                var _a = this.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
                this.props.boundary.ref = Object(boundary["a" /* getBoundary */])({ x: x, y: y, z: z, indices: this.elements });
                return this.props.boundary.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "lookup3d", {
            get: function () {
                if (this.props.lookup3d.ref)
                    return this.props.lookup3d.ref;
                var _a = this.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
                this.props.lookup3d.ref = Object(geometry["c" /* GridLookup3D */])({ x: x, y: y, z: z, indices: this.elements }, this.boundary);
                return this.props.lookup3d.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "principalAxes", {
            get: function () {
                if (this.props.principalAxes.ref)
                    return this.props.principalAxes.ref;
                this.props.principalAxes.ref = getPrincipalAxes(this);
                return this.props.principalAxes.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "bonds", {
            get: function () {
                if (this.props.bonds.ref)
                    return this.props.bonds.ref;
                this.props.bonds.ref = Object(bonds["c" /* computeIntraUnitBonds */])(this);
                return this.props.bonds.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "rings", {
            get: function () {
                if (this.props.rings.ref)
                    return this.props.rings.ref;
                this.props.rings.ref = rings["b" /* UnitRings */].create(this);
                return this.props.rings.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "polymerElements", {
            get: function () {
                if (this.props.polymerElements.ref)
                    return this.props.polymerElements.ref;
                this.props.polymerElements.ref = getAtomicPolymerElements(this);
                return this.props.polymerElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "gapElements", {
            get: function () {
                if (this.props.gapElements.ref)
                    return this.props.gapElements.ref;
                this.props.gapElements.ref = getAtomicGapElements(this);
                return this.props.gapElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "nucleotideElements", {
            get: function () {
                if (this.props.nucleotideElements.ref)
                    return this.props.nucleotideElements.ref;
                this.props.nucleotideElements.ref = getNucleotideElements(this);
                return this.props.nucleotideElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "proteinElements", {
            get: function () {
                if (this.props.proteinElements.ref)
                    return this.props.proteinElements.ref;
                this.props.proteinElements.ref = getProteinElements(this);
                return this.props.proteinElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Atomic.prototype, "residueCount", {
            get: function () {
                if (this.props.residueCount.ref !== undefined)
                    return this.props.residueCount.ref;
                var residueCount = 0;
                var residueIt = mol_data_int["Segmentation"].transientSegments(this.model.atomicHierarchy.residueAtomSegments, this.elements);
                while (residueIt.hasNext) {
                    residueIt.move();
                    residueCount += 1;
                }
                this.props.residueCount.ref = residueCount;
                return this.props.residueCount.ref;
            },
            enumerable: false,
            configurable: true
        });
        Atomic.prototype.getResidueIndex = function (elementIndex) {
            return this.residueIndex[this.elements[elementIndex]];
        };
        return Atomic;
    }());
    Unit.Atomic = Atomic;
    function AtomicProperties() {
        return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, BaseProperties()), { bonds: mol_util["f" /* ValueRef */].create(void 0), rings: mol_util["f" /* ValueRef */].create(void 0), nucleotideElements: mol_util["f" /* ValueRef */].create(void 0), proteinElements: mol_util["f" /* ValueRef */].create(void 0), residueCount: mol_util["f" /* ValueRef */].create(void 0) });
    }
    var Coarse = /** @class */ (function () {
        function Coarse(id, invariantId, chainGroupId, traits, model, kind, elements, conformation, props) {
            this.kind = kind;
            this.objectPrimitive = kind === 1 /* Spheres */ ? 'sphere' : 'gaussian';
            this.id = id;
            this.invariantId = invariantId;
            this.chainGroupId = chainGroupId;
            this.traits = traits;
            this.model = model;
            this.elements = elements;
            this.conformation = conformation;
            this.coarseElements = kind === 1 /* Spheres */ ? model.coarseHierarchy.spheres : model.coarseHierarchy.gaussians;
            this.coarseConformation = (kind === 1 /* Spheres */ ? model.coarseConformation.spheres : model.coarseConformation.gaussians);
            this.props = props;
        }
        Coarse.prototype.getChild = function (elements) {
            if (elements.length === this.elements.length)
                return this /** lets call this an ugly temporary hack */;
            return createCoarse(this.id, this.invariantId, this.chainGroupId, this.traits, this.model, this.kind, elements, this.conformation, CoarseProperties());
        };
        Coarse.prototype.applyOperator = function (id, operator, dontCompose) {
            if (dontCompose === void 0) { dontCompose = false; }
            var op = dontCompose ? operator : symmetry_operator["a" /* SymmetryOperator */].compose(this.conformation.operator, operator);
            var ret = createCoarse(id, this.invariantId, this.chainGroupId, this.traits, this.model, this.kind, this.elements, symmetry_operator["a" /* SymmetryOperator */].createMapping(op, this.getCoarseConformation(), this.conformation.r), this.props);
            // (ret as Coarse<K, C>)._lookup3d = this._lookup3d;
            return ret;
        };
        Object.defineProperty(Coarse.prototype, "boundary", {
            get: function () {
                if (this.props.boundary.ref)
                    return this.props.boundary.ref;
                // TODO: support sphere radius?
                var _a = this.getCoarseConformation(), x = _a.x, y = _a.y, z = _a.z;
                this.props.boundary.ref = Object(boundary["a" /* getBoundary */])({ x: x, y: y, z: z, indices: this.elements });
                return this.props.boundary.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Coarse.prototype, "lookup3d", {
            get: function () {
                if (this.props.lookup3d.ref)
                    return this.props.lookup3d.ref;
                // TODO: support sphere radius?
                var _a = this.getCoarseConformation(), x = _a.x, y = _a.y, z = _a.z;
                this.props.lookup3d.ref = Object(geometry["c" /* GridLookup3D */])({ x: x, y: y, z: z, indices: this.elements }, this.boundary);
                return this.props.lookup3d.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Coarse.prototype, "principalAxes", {
            get: function () {
                if (this.props.principalAxes.ref)
                    return this.props.principalAxes.ref;
                this.props.principalAxes.ref = getPrincipalAxes(this); // TODO get rid of casting
                return this.props.principalAxes.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Coarse.prototype, "polymerElements", {
            get: function () {
                if (this.props.polymerElements.ref)
                    return this.props.polymerElements.ref;
                this.props.polymerElements.ref = getCoarsePolymerElements(this); // TODO get rid of casting
                return this.props.polymerElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(Coarse.prototype, "gapElements", {
            get: function () {
                if (this.props.gapElements.ref)
                    return this.props.gapElements.ref;
                this.props.gapElements.ref = getCoarseGapElements(this); // TODO get rid of casting
                return this.props.gapElements.ref;
            },
            enumerable: false,
            configurable: true
        });
        Coarse.prototype.getCoarseConformation = function () {
            return this.kind === 1 /* Spheres */ ? this.model.coarseConformation.spheres : this.model.coarseConformation.gaussians;
        };
        return Coarse;
    }());
    function CoarseProperties() {
        return BaseProperties();
    }
    function createCoarse(id, invariantId, chainGroupId, traits, model, kind, elements, conformation, props) {
        return new Coarse(id, invariantId, chainGroupId, traits, model, kind, elements, conformation, props) /** lets call this an ugly temporary hack */;
    }
    var Spheres = /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(Spheres, _super);
        function Spheres() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Spheres;
    }(Coarse));
    Unit.Spheres = Spheres;
    var Gaussians = /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(Gaussians, _super);
        function Gaussians() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Gaussians;
    }(Coarse));
    Unit.Gaussians = Gaussians;
    function areSameChainOperatorGroup(a, b) {
        return a.chainGroupId === b.chainGroupId && a.conformation.operator.name === b.conformation.operator.name;
    }
    Unit.areSameChainOperatorGroup = areSameChainOperatorGroup;
})(unit_Unit || (unit_Unit = {}));
/* harmony default export */ var structure_unit = __webpack_exports__["a"] = (unit_Unit);
//# sourceMappingURL=unit.js.map

/***/ }),
/* 38 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructureSelection; });
/* harmony import */ var _mol_data_generic__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(55);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/* harmony import */ var _utils_structure_set__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(156);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var StructureSelection;
(function (StructureSelection) {
    function Singletons(source, structure) { return { kind: 'singletons', source: source, structure: structure }; }
    StructureSelection.Singletons = Singletons;
    function Sequence(source, structures) { return { kind: 'sequence', source: source, structures: structures }; }
    StructureSelection.Sequence = Sequence;
    function Empty(source) { return Singletons(source, _structure__WEBPACK_IMPORTED_MODULE_1__[/* Structure */ "c"].Empty); }
    StructureSelection.Empty = Empty;
    ;
    function isSingleton(s) { return s.kind === 'singletons'; }
    StructureSelection.isSingleton = isSingleton;
    function isEmpty(s) { return isSingleton(s) ? s.structure.units.length === 0 : s.structures.length === 0; }
    StructureSelection.isEmpty = isEmpty;
    function structureCount(sel) {
        if (isSingleton(sel))
            return sel.structure.elementCount;
        return sel.structures.length;
    }
    StructureSelection.structureCount = structureCount;
    function unionStructure(sel) {
        if (isEmpty(sel))
            return _structure__WEBPACK_IMPORTED_MODULE_1__[/* Structure */ "c"].Empty;
        if (isSingleton(sel))
            return sel.structure;
        return Object(_utils_structure_set__WEBPACK_IMPORTED_MODULE_2__[/* structureUnion */ "e"])(sel.source, sel.structures);
    }
    StructureSelection.unionStructure = unionStructure;
    /** Convert selection to loci and use "current structure units" in Loci elements */
    function toLociWithCurrentUnits(sel) {
        var elements = [];
        var unitMap = sel.source.unitMap;
        for (var _a = 0, _b = unionStructure(sel).units; _a < _b.length; _a++) {
            var unit = _b[_a];
            if (unit === unitMap.get(unit.id)) {
                elements[elements.length] = {
                    unit: unit,
                    indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofBounds(0, unit.elements.length)
                };
            }
            else {
                elements[elements.length] = {
                    unit: unit,
                    indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofSortedArray(_mol_data_int__WEBPACK_IMPORTED_MODULE_3__["SortedArray"].indicesOf(unitMap.get(unit.id).elements, unit.elements))
                };
            }
        }
        return _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureElement */ "d"].Loci(sel.source, elements);
    }
    StructureSelection.toLociWithCurrentUnits = toLociWithCurrentUnits;
    /** use source unit in loci.elements */
    function toLociWithSourceUnits(sel) {
        var elements = [];
        var unitMap = sel.source.unitMap;
        for (var _a = 0, _b = unionStructure(sel).units; _a < _b.length; _a++) {
            var _unit = _b[_a];
            var unit = unitMap.get(_unit.id);
            if (unit === _unit) {
                elements[elements.length] = {
                    unit: unit,
                    indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofBounds(0, unit.elements.length)
                };
            }
            else {
                elements[elements.length] = {
                    unit: unit,
                    indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofSortedArray(_mol_data_int__WEBPACK_IMPORTED_MODULE_3__["SortedArray"].indicesOf(unit.elements, _unit.elements))
                };
            }
        }
        return _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureElement */ "d"].Loci(sel.source, elements);
    }
    StructureSelection.toLociWithSourceUnits = toLociWithSourceUnits;
    function getSelection(source, structures, allSingletons) {
        var len = structures.length;
        if (len === 0)
            return Empty(source);
        if (allSingletons)
            return Singletons(source, Object(_utils_structure_set__WEBPACK_IMPORTED_MODULE_2__[/* structureUnion */ "e"])(source, structures));
        return Sequence(source, structures);
    }
    var LinearBuilderImpl = /** @class */ (function () {
        function LinearBuilderImpl(source) {
            this.source = source;
            this.structures = [];
            this.allSingletons = true;
        }
        LinearBuilderImpl.prototype.add = function (structure) {
            var elementCount = structure.elementCount;
            if (elementCount === 0)
                return;
            this.structures[this.structures.length] = structure;
            if (elementCount !== 1)
                this.allSingletons = false;
        };
        LinearBuilderImpl.prototype.getSelection = function () { return getSelection(this.source, this.structures, this.allSingletons); };
        return LinearBuilderImpl;
    }());
    var HashBuilderImpl = /** @class */ (function () {
        function HashBuilderImpl(structure) {
            this.structure = structure;
            this.structures = [];
            this.allSingletons = true;
            this.uniqueSets = Object(_mol_data_generic__WEBPACK_IMPORTED_MODULE_0__[/* HashSet */ "a"])(_structure__WEBPACK_IMPORTED_MODULE_1__[/* Structure */ "c"].hashCode, _structure__WEBPACK_IMPORTED_MODULE_1__[/* Structure */ "c"].areUnitAndIndicesEqual);
        }
        HashBuilderImpl.prototype.add = function (structure) {
            var atomCount = structure.elementCount;
            if (atomCount === 0 || !this.uniqueSets.add(structure))
                return;
            this.structures[this.structures.length] = structure;
            if (atomCount !== 1)
                this.allSingletons = false;
        };
        HashBuilderImpl.prototype.getSelection = function () { return getSelection(this.structure, this.structures, this.allSingletons); };
        return HashBuilderImpl;
    }());
    function LinearBuilder(structure) { return new LinearBuilderImpl(structure); }
    StructureSelection.LinearBuilder = LinearBuilder;
    function UniqueBuilder(structure) { return new HashBuilderImpl(structure); }
    StructureSelection.UniqueBuilder = UniqueBuilder;
    // TODO: build timeout checking into this?
    function forEach(sel, fn) {
        var idx = 0;
        if (StructureSelection.isSingleton(sel)) {
            for (var _a = 0, _b = sel.structure.units; _a < _b.length; _a++) {
                var unit = _b[_a];
                var elements = unit.elements;
                for (var i = 0, _i = elements.length; i < _i; i++) {
                    // TODO: optimize this somehow???
                    var s = _structure__WEBPACK_IMPORTED_MODULE_1__[/* Structure */ "c"].create([unit.getChild(_mol_data_int__WEBPACK_IMPORTED_MODULE_3__["SortedArray"].ofSingleton(elements[i]))], { parent: sel.source });
                    fn(s, idx++);
                }
            }
        }
        else {
            for (var _c = 0, _d = sel.structures; _c < _d.length; _c++) {
                var s = _d[_c];
                fn(s, idx++);
            }
        }
    }
    StructureSelection.forEach = forEach;
    function withInputStructure(selection, structure) {
        if (isSingleton(selection))
            return Singletons(structure, selection.structure);
        return Sequence(structure, selection.structures);
    }
    StructureSelection.withInputStructure = withInputStructure;
    // TODO: spatial lookup?
})(StructureSelection || (StructureSelection = {}));

//# sourceMappingURL=selection.js.map

/***/ }),
/* 39 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Mesh; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(124);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(125);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(117);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(9);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(53);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(142);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(143);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */














var Mesh;
(function (Mesh) {
    function create(vertices, indices, normals, groups, vertexCount, triangleCount, mesh) {
        return mesh ?
            update(vertices, indices, normals, groups, vertexCount, triangleCount, mesh) :
            fromArrays(vertices, indices, normals, groups, vertexCount, triangleCount);
    }
    Mesh.create = create;
    function createEmpty(mesh) {
        var vb = mesh ? mesh.vertexBuffer.ref.value : new Float32Array(0);
        var ib = mesh ? mesh.indexBuffer.ref.value : new Uint32Array(0);
        var nb = mesh ? mesh.normalBuffer.ref.value : new Float32Array(0);
        var gb = mesh ? mesh.groupBuffer.ref.value : new Float32Array(0);
        return create(vb, ib, nb, gb, 0, 0, mesh);
    }
    Mesh.createEmpty = createEmpty;
    function hashCode(mesh) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* hashFnv32a */ "l"])([
            mesh.vertexCount, mesh.triangleCount,
            mesh.vertexBuffer.ref.version, mesh.indexBuffer.ref.version,
            mesh.normalBuffer.ref.version, mesh.groupBuffer.ref.version
        ]);
    }
    function fromArrays(vertices, indices, normals, groups, vertexCount, triangleCount) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"])();
        var groupMapping;
        var currentHash = -1;
        var currentGroup = -1;
        var mesh = {
            kind: 'mesh',
            vertexCount: vertexCount,
            triangleCount: triangleCount,
            vertexBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(vertices),
            indexBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(indices),
            normalBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(normals),
            groupBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(groups),
            get boundingSphere() {
                var newHash = hashCode(mesh);
                if (newHash !== currentHash) {
                    var b = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateInvariantBoundingSphere */ "a"])(mesh.vertexBuffer.ref.value, mesh.vertexCount, 1);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
            get groupMapping() {
                if (mesh.groupBuffer.ref.version !== currentGroup) {
                    groupMapping = Object(_util__WEBPACK_IMPORTED_MODULE_4__[/* createGroupMapping */ "c"])(mesh.groupBuffer.ref.value, mesh.vertexCount);
                    currentGroup = mesh.groupBuffer.ref.version;
                }
                return groupMapping;
            },
            setBoundingSphere: function (sphere) {
                _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, sphere);
                currentHash = hashCode(mesh);
            }
        };
        return mesh;
    }
    function update(vertices, indices, normals, groups, vertexCount, triangleCount, mesh) {
        mesh.vertexCount = vertexCount;
        mesh.triangleCount = triangleCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.vertexBuffer, vertices);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.indexBuffer, indices);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.normalBuffer, normals);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.groupBuffer, groups);
        return mesh;
    }
    function computeNormals(mesh) {
        var vertexCount = mesh.vertexCount, triangleCount = mesh.triangleCount;
        var vertices = mesh.vertexBuffer.ref.value;
        var indices = mesh.indexBuffer.ref.value;
        var normals = mesh.normalBuffer.ref.value.length >= vertexCount * 3
            ? mesh.normalBuffer.ref.value
            : new Float32Array(vertexCount * 3);
        if (normals === mesh.normalBuffer.ref.value) {
            normals.fill(0, 0, vertexCount * 3);
        }
        Object(_util__WEBPACK_IMPORTED_MODULE_4__[/* computeIndexedVertexNormals */ "b"])(vertices, indices, normals, vertexCount, triangleCount);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.normalBuffer, normals);
    }
    Mesh.computeNormals = computeNormals;
    function checkForDuplicateVertices(mesh, fractionDigits) {
        if (fractionDigits === void 0) { fractionDigits = 3; }
        var v = mesh.vertexBuffer.ref.value;
        var map = new Map();
        var hash = function (v, d) { return v[0].toFixed(d) + "|" + v[1].toFixed(d) + "|" + v[2].toFixed(d); };
        var duplicates = 0;
        var a = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        for (var i = 0, il = mesh.vertexCount; i < il; ++i) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(a, v, i * 3);
            var k = hash(a, fractionDigits);
            var count = map.get(k);
            if (count !== undefined) {
                duplicates += 1;
                map.set(k, count + 1);
            }
            else {
                map.set(k, 1);
            }
        }
        return duplicates;
    }
    Mesh.checkForDuplicateVertices = checkForDuplicateVertices;
    var tmpMat3 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat3"])();
    function transform(mesh, t) {
        var v = mesh.vertexBuffer.ref.value;
        Object(_util__WEBPACK_IMPORTED_MODULE_4__[/* transformPositionArray */ "e"])(t, v, 0, mesh.vertexCount);
        if (!_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat4"].isTranslationAndUniformScaling(t)) {
            var n = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat3"].directionTransform(tmpMat3, t);
            Object(_util__WEBPACK_IMPORTED_MODULE_4__[/* transformDirectionArray */ "d"])(n, mesh.normalBuffer.ref.value, 0, mesh.vertexCount);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(mesh.vertexBuffer, v);
    }
    Mesh.transform = transform;
    /**
     * Ensure that each vertices of each triangle have the same group id.
     * Note that normals are copied over and can't be re-created from the new mesh.
     */
    function uniformTriangleGroup(mesh, splitTriangles) {
        if (splitTriangles === void 0) { splitTriangles = true; }
        var indexBuffer = mesh.indexBuffer, vertexBuffer = mesh.vertexBuffer, groupBuffer = mesh.groupBuffer, normalBuffer = mesh.normalBuffer, triangleCount = mesh.triangleCount, vertexCount = mesh.vertexCount;
        var ib = indexBuffer.ref.value;
        var vb = vertexBuffer.ref.value;
        var gb = groupBuffer.ref.value;
        var nb = normalBuffer.ref.value;
        // new
        var index = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].create(Uint32Array, 3, 1024, triangleCount);
        // re-use
        var vertex = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].create(Float32Array, 3, 1024, vb);
        vertex.currentIndex = vertexCount * 3;
        vertex.elementCount = vertexCount;
        var normal = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].create(Float32Array, 3, 1024, nb);
        normal.currentIndex = vertexCount * 3;
        normal.elementCount = vertexCount;
        var group = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].create(Float32Array, 1, 1024, gb);
        group.currentIndex = vertexCount;
        group.elementCount = vertexCount;
        var vi = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        var vj = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        var vk = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        var ni = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        var nj = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        var nk = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
        function add(i) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vi, vb, i * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(ni, nb, i * 3);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(vertex, vi[0], vi[1], vi[2]);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(normal, ni[0], ni[1], ni[2]);
        }
        function addMid(i, j) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vi, vb, i * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vj, vb, j * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].scale(vi, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(vi, vi, vj), 0.5);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(ni, nb, i * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(nj, nb, j * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].scale(ni, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(ni, ni, nj), 0.5);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(vertex, vi[0], vi[1], vi[2]);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(normal, ni[0], ni[1], ni[2]);
        }
        function addCenter(i, j, k) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vi, vb, i * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vj, vb, j * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(vk, vb, k * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].scale(vi, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(vi, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(vi, vi, vj), vk), 1 / 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(ni, nb, i * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(nj, nb, j * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(nk, nb, k * 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].scale(ni, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(ni, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(ni, ni, nj), nk), 1 / 3);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(vertex, vi[0], vi[1], vi[2]);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(normal, ni[0], ni[1], ni[2]);
        }
        function split2(i0, i1, i2, g0, g1) {
            ++newTriangleCount;
            add(i0);
            addMid(i0, i1);
            addMid(i0, i2);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2);
            for (var j = 0; j < 3; ++j)
                _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g0);
            newVertexCount += 3;
            newTriangleCount += 2;
            add(i1);
            add(i2);
            addMid(i0, i1);
            addMid(i0, i2);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2);
            for (var j = 0; j < 4; ++j)
                _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g1);
            newVertexCount += 4;
        }
        var newVertexCount = vertexCount;
        var newTriangleCount = 0;
        if (splitTriangles) {
            for (var i = 0, il = triangleCount; i < il; ++i) {
                var i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2];
                var g0 = gb[i0], g1 = gb[i1], g2 = gb[i2];
                if (g0 === g1 && g0 === g2) {
                    ++newTriangleCount;
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, i0, i1, i2);
                }
                else if (g0 === g1) {
                    split2(i2, i0, i1, g2, g0);
                }
                else if (g0 === g2) {
                    split2(i1, i2, i0, g1, g2);
                }
                else if (g1 === g2) {
                    split2(i0, i1, i2, g0, g1);
                }
                else {
                    newTriangleCount += 2;
                    add(i0);
                    addMid(i0, i1);
                    addMid(i0, i2);
                    addCenter(i0, i1, i2);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2);
                    for (var j = 0; j < 4; ++j)
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g0);
                    newVertexCount += 4;
                    newTriangleCount += 2;
                    add(i1);
                    addMid(i1, i2);
                    addMid(i1, i0);
                    addCenter(i0, i1, i2);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2);
                    for (var j = 0; j < 4; ++j)
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g1);
                    newVertexCount += 4;
                    newTriangleCount += 2;
                    add(i2);
                    addMid(i2, i1);
                    addMid(i2, i0);
                    addCenter(i0, i1, i2);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount + 3, newVertexCount + 1, newVertexCount);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount + 2, newVertexCount + 3, newVertexCount);
                    for (var j = 0; j < 4; ++j)
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g2);
                    newVertexCount += 4;
                }
            }
        }
        else {
            for (var i = 0, il = triangleCount; i < il; ++i) {
                var i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2];
                var g0 = gb[i0], g1 = gb[i1], g2 = gb[i2];
                if (g0 !== g1 || g0 !== g2) {
                    ++newTriangleCount;
                    add(i0);
                    add(i1);
                    add(i2);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2);
                    var g = g1 === g2 ? g1 : g0;
                    for (var j = 0; j < 3; ++j)
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add(group, g);
                    newVertexCount += 3;
                }
                else {
                    ++newTriangleCount;
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].add3(index, i0, i1, i2);
                }
            }
        }
        var newIb = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].compact(index);
        var newVb = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].compact(vertex);
        var newNb = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].compact(normal);
        var newGb = _mol_data_util__WEBPACK_IMPORTED_MODULE_7__[/* ChunkedArray */ "a"].compact(group);
        mesh.vertexCount = newVertexCount;
        mesh.triangleCount = newTriangleCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(vertexBuffer, newVb);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(groupBuffer, newGb);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(indexBuffer, newIb);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(normalBuffer, newNb);
        return mesh;
    }
    Mesh.uniformTriangleGroup = uniformTriangleGroup;
    //
    Mesh.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].Params), { doubleSided: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].CustomQualityParamInfo), flipSided: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].ShadingCategory), flatShaded: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].ShadingCategory), ignoreLight: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].ShadingCategory) });
    Mesh.Utils = {
        Params: Mesh.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createRenderableState,
        updateRenderableState: _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].updateRenderableState
    };
    function createValues(mesh, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        if (instanceCount !== transform.instanceCount.ref.value) {
            throw new Error('instanceCount values in TransformData and LocationIterator differ');
        }
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_6__[/* createColors */ "a"])(locationIt, theme.color);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_5__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_11__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_12__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_13__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: mesh.triangleCount * 3, groupCount: groupCount, instanceCount: instanceCount };
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].clone(mesh.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ aPosition: mesh.vertexBuffer, aNormal: mesh.normalBuffer, aGroup: mesh.groupBuffer, elements: mesh.indexBuffer, boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].ofSphere(invariantBoundingSphere)) }, color), marker), overpaint), transparency), clipping), transform), _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createValues(props, counts)), { dDoubleSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.doubleSided), dFlatShaded: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.flatShaded), dFlipSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.flipSided), dIgnoreLight: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.ignoreLight) });
    }
    function createValuesSimple(mesh, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].getDefaultValues(Mesh.Params)), props);
        return createValues(mesh, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dDoubleSided, props.doubleSided);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dFlatShaded, props.flatShaded);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dFlipSided, props.flipSided);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dIgnoreLight, props.ignoreLight);
    }
    function updateBoundingSphere(values, mesh) {
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].clone(mesh.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
})(Mesh || (Mesh = {}));
//# sourceMappingURL=mesh.js.map

/***/ }),
/* 40 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export RepresentationProvider */
/* unused harmony export EmptyRepresentationProvider */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return RepresentationRegistry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Representation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(89);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(60);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(45);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(23);
/* harmony import */ var _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(130);
/* harmony import */ var _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(131);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(164);
/* harmony import */ var _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(33);
/* harmony import */ var _visual__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(69);
/* harmony import */ var _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(77);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














var RepresentationProvider;
(function (RepresentationProvider) {
    function getDetaultParams(r, ctx, data) {
        return _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(r.getParams(ctx, data));
    }
    RepresentationProvider.getDetaultParams = getDetaultParams;
})(RepresentationProvider || (RepresentationProvider = {}));
var EmptyRepresentationProvider = {
    label: '',
    description: '',
    factory: function () { return Representation.Empty; },
    getParams: function () { return ({}); },
    defaultValues: {}
};
function getTypes(list) {
    return list.map(function (e) { return [e.name, e.provider.label]; });
}
var RepresentationRegistry = /** @class */ (function () {
    function RepresentationRegistry() {
        this._list = [];
        this._map = new Map();
        this._name = new Map();
    }
    Object.defineProperty(RepresentationRegistry.prototype, "default", {
        get: function () { return this._list[0]; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(RepresentationRegistry.prototype, "types", {
        get: function () { return getTypes(this._list); },
        enumerable: false,
        configurable: true
    });
    ;
    RepresentationRegistry.prototype.add = function (provider) {
        if (this._map.has(provider.name)) {
            throw new Error(provider.name + " already registered.");
        }
        this._list.push({ name: provider.name, provider: provider });
        this._map.set(provider.name, provider);
        this._name.set(provider, provider.name);
    };
    RepresentationRegistry.prototype.getName = function (provider) {
        if (!this._name.has(provider))
            throw new Error("'" + provider.label + "' is not a registered represenatation provider.");
        return this._name.get(provider);
    };
    RepresentationRegistry.prototype.remove = function (provider) {
        var name = provider.name;
        this._list.splice(this._list.findIndex(function (e) { return e.name === name; }), 1);
        var p = this._map.get(name);
        if (p) {
            this._map.delete(name);
            this._name.delete(p);
        }
    };
    RepresentationRegistry.prototype.get = function (name) {
        return this._map.get(name) || EmptyRepresentationProvider;
    };
    Object.defineProperty(RepresentationRegistry.prototype, "list", {
        get: function () {
            return this._list;
        },
        enumerable: false,
        configurable: true
    });
    RepresentationRegistry.prototype.getApplicableList = function (data) {
        return this._list.filter(function (e) { return e.provider.isApplicable(data); });
    };
    RepresentationRegistry.prototype.getApplicableTypes = function (data) {
        return getTypes(this.getApplicableList(data));
    };
    return RepresentationRegistry;
}());

//

var Representation;
(function (Representation) {
    var Loci;
    (function (Loci) {
        function areEqual(a, b) {
            return a.repr === b.repr && _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["Loci"].areEqual(a.loci, b.loci);
        }
        Loci.areEqual = areEqual;
        Loci.Empty = { loci: _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["EmptyLoci"] };
    })(Loci = Representation.Loci || (Representation.Loci = {}));
    function createState() {
        return { visible: true, alphaFactor: 1, pickable: true, syncManually: false, transform: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__["Mat4"].identity(), overpaint: _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_7__[/* Overpaint */ "a"].Empty, transparency: _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_8__[/* Transparency */ "a"].Empty, clipping: _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_13__[/* Clipping */ "a"].Empty, markerActions: _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_5__[/* MarkerActions */ "b"].All };
    }
    Representation.createState = createState;
    function updateState(state, update) {
        if (update.visible !== undefined)
            state.visible = update.visible;
        if (update.alphaFactor !== undefined)
            state.alphaFactor = update.alphaFactor;
        if (update.pickable !== undefined)
            state.pickable = update.pickable;
        if (update.overpaint !== undefined)
            state.overpaint = update.overpaint;
        if (update.transparency !== undefined)
            state.transparency = update.transparency;
        if (update.clipping !== undefined)
            state.clipping = update.clipping;
        if (update.syncManually !== undefined)
            state.syncManually = update.syncManually;
        if (update.transform !== undefined)
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__["Mat4"].copy(state.transform, update.transform);
        if (update.markerActions !== undefined)
            state.markerActions = update.markerActions;
    }
    Representation.updateState = updateState;
    Representation.StateBuilder = { create: createState, update: updateState };
    Representation.Empty = {
        label: '', groupCount: 0, renderObjects: [], props: {}, params: {}, updated: new rxjs__WEBPACK_IMPORTED_MODULE_3__[/* Subject */ "a"](), state: createState(), theme: _mol_theme_theme__WEBPACK_IMPORTED_MODULE_2__[/* Theme */ "a"].createEmpty(),
        createOrUpdate: function () { return _mol_task__WEBPACK_IMPORTED_MODULE_4__[/* Task */ "b"].constant('', undefined); },
        setState: function () { },
        setTheme: function () { },
        getLoci: function () { return _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["EmptyLoci"]; },
        mark: function () { return false; },
        destroy: function () { }
    };
    function createMulti(label, ctx, getParams, stateBuilder, reprDefs) {
        var _this = this;
        var version = 0;
        var updated = new rxjs__WEBPACK_IMPORTED_MODULE_3__[/* Subject */ "a"]();
        var currentState = stateBuilder.create();
        var currentTheme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_2__[/* Theme */ "a"].createEmpty();
        var currentParams;
        var currentProps;
        var currentData;
        var reprMap = {};
        var reprList = Object.keys(reprDefs).map(function (name, i) {
            reprMap[i] = name;
            var repr = reprDefs[name](ctx, getParams);
            repr.setState(currentState);
            return repr;
        });
        return {
            label: label,
            updated: updated,
            get groupCount() {
                var groupCount = 0;
                if (currentProps) {
                    var visuals = currentProps.visuals;
                    for (var i = 0, il = reprList.length; i < il; ++i) {
                        if (!visuals || visuals.includes(reprMap[i])) {
                            groupCount += reprList[i].groupCount;
                        }
                    }
                }
                return groupCount;
            },
            get renderObjects() {
                var renderObjects = [];
                if (currentProps) {
                    var visuals = currentProps.visuals;
                    for (var i = 0, il = reprList.length; i < il; ++i) {
                        if (!visuals || visuals.includes(reprMap[i])) {
                            renderObjects.push.apply(renderObjects, reprList[i].renderObjects);
                        }
                    }
                }
                return renderObjects;
            },
            get props() { return currentProps; },
            get params() { return currentParams; },
            createOrUpdate: function (props, data) {
                if (props === void 0) { props = {}; }
                if (data && data !== currentData) {
                    currentParams = getParams(ctx, data);
                    currentData = data;
                    if (!currentProps)
                        currentProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(currentParams);
                }
                var qualityProps = Object(_util__WEBPACK_IMPORTED_MODULE_10__[/* getQualityProps */ "b"])(Object.assign({}, currentProps, props), currentData);
                Object.assign(currentProps, props, qualityProps);
                var visuals = currentProps.visuals;
                return _mol_task__WEBPACK_IMPORTED_MODULE_4__[/* Task */ "b"].create("Creating or updating '" + label + "' representation", function (runtime) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                    var i, il;
                    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                i = 0, il = reprList.length;
                                _a.label = 1;
                            case 1:
                                if (!(i < il)) return [3 /*break*/, 4];
                                if (!(!visuals || visuals.includes(reprMap[i]))) return [3 /*break*/, 3];
                                return [4 /*yield*/, reprList[i].createOrUpdate(currentProps, currentData).runInContext(runtime)];
                            case 2:
                                _a.sent();
                                _a.label = 3;
                            case 3:
                                ++i;
                                return [3 /*break*/, 1];
                            case 4:
                                updated.next(version++);
                                return [2 /*return*/];
                        }
                    });
                }); });
            },
            get state() { return currentState; },
            get theme() { return currentTheme; },
            getLoci: function (pickingId) {
                var visuals = currentProps.visuals;
                for (var i = 0, il = reprList.length; i < il; ++i) {
                    if (!visuals || visuals.includes(reprMap[i])) {
                        var loci = reprList[i].getLoci(pickingId);
                        if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["isEmptyLoci"])(loci))
                            return loci;
                    }
                }
                return _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["EmptyLoci"];
            },
            mark: function (loci, action) {
                var marked = false;
                for (var i = 0, il = reprList.length; i < il; ++i) {
                    marked = reprList[i].mark(loci, action) || marked;
                }
                return marked;
            },
            setState: function (state) {
                stateBuilder.update(currentState, state);
                for (var i = 0, il = reprList.length; i < il; ++i) {
                    reprList[i].setState(currentState);
                }
            },
            setTheme: function (theme) {
                for (var i = 0, il = reprList.length; i < il; ++i) {
                    reprList[i].setTheme(theme);
                }
            },
            destroy: function () {
                for (var i = 0, il = reprList.length; i < il; ++i) {
                    reprList[i].destroy();
                }
            }
        };
    }
    Representation.createMulti = createMulti;
    function fromRenderObject(label, renderObject) {
        var _this = this;
        var version = 0;
        var updated = new rxjs__WEBPACK_IMPORTED_MODULE_3__[/* Subject */ "a"]();
        var currentState = Representation.createState();
        var currentTheme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_2__[/* Theme */ "a"].createEmpty();
        var currentParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].clone(_mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].Params);
        var currentProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(_mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].Params);
        return {
            label: label,
            updated: updated,
            get groupCount() { return renderObject.values.uGroupCount.ref.value; },
            get renderObjects() { return [renderObject]; },
            get props() { return currentProps; },
            get params() { return currentParams; },
            createOrUpdate: function (props) {
                if (props === void 0) { props = {}; }
                var qualityProps = Object(_util__WEBPACK_IMPORTED_MODULE_10__[/* getQualityProps */ "b"])(Object.assign({}, currentProps, props));
                Object.assign(currentProps, props, qualityProps);
                return _mol_task__WEBPACK_IMPORTED_MODULE_4__[/* Task */ "b"].create("Updating '" + label + "' representation", function (runtime) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                        // TODO
                        updated.next(version++);
                        return [2 /*return*/];
                    });
                }); });
            },
            get state() { return currentState; },
            get theme() { return currentTheme; },
            getLoci: function () {
                // TODO
                return _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["EmptyLoci"];
            },
            mark: function (loci, action) {
                // TODO
                return false;
            },
            setState: function (state) {
                if (state.visible !== undefined)
                    _visual__WEBPACK_IMPORTED_MODULE_12__[/* Visual */ "a"].setVisibility(renderObject, state.visible);
                if (state.alphaFactor !== undefined)
                    _visual__WEBPACK_IMPORTED_MODULE_12__[/* Visual */ "a"].setAlphaFactor(renderObject, state.alphaFactor);
                if (state.pickable !== undefined)
                    _visual__WEBPACK_IMPORTED_MODULE_12__[/* Visual */ "a"].setPickable(renderObject, state.pickable);
                if (state.overpaint !== undefined) {
                    // TODO
                }
                if (state.transparency !== undefined) {
                    // TODO
                }
                if (state.transform !== undefined)
                    _visual__WEBPACK_IMPORTED_MODULE_12__[/* Visual */ "a"].setTransform(renderObject, state.transform);
                Representation.updateState(currentState, state);
            },
            setTheme: function () { },
            destroy: function () { }
        };
    }
    Representation.fromRenderObject = fromRenderObject;
})(Representation || (Representation = {}));
//# sourceMappingURL=representation.js.map

/***/ }),
/* 41 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export indentString */
/* unused harmony export splitCamelCase */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return camelCaseToWords; });
/* unused harmony export lowerCase */
/* unused harmony export upperCase */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return upperCaseAny; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return capitalize; });
/* unused harmony export splitSnakeCase */
/* unused harmony export snakeCaseToWords */
/* unused harmony export splitKebabCase */
/* unused harmony export kebabCaseToWords */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return stringToWords; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return substringStartsWith; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return interpolate; });
/* unused harmony export trimChar */
/* unused harmony export trimCharStart */
/* unused harmony export trimCharEnd */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return stripTags; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var reLine = /^/mg;
function indentString(str, count, indent) {
    return count === 0 ? str : str.replace(reLine, indent.repeat(count));
}
/** Add space between camelCase text. */
function splitCamelCase(str, separator) {
    if (separator === void 0) { separator = ' '; }
    return str.replace(/([a-z\xE0-\xFF])([A-Z\xC0\xDF])/g, "$1" + separator + "$2");
}
/** Split camelCase text and capitalize. */
function camelCaseToWords(str) {
    return capitalize(splitCamelCase(str));
}
var lowerCase = function (str) { return str.toLowerCase(); };
var upperCase = function (str) { return str.toUpperCase(); };
/** Return upper case if string, otherwise return empty string */
function upperCaseAny(value) {
    if (!value)
        return '';
    return typeof value === 'string' ? value.toUpperCase() : ("" + value).toUpperCase();
}
/** Uppercase the first character of each word. */
function capitalize(str) {
    return str.toLowerCase().replace(/^\w|\s\w/g, upperCase);
}
function splitSnakeCase(str) {
    return str.replace(/_/g, ' ');
}
function snakeCaseToWords(str) {
    return capitalize(splitSnakeCase(str));
}
function splitKebabCase(str) {
    return str.replace(/-/g, ' ');
}
function kebabCaseToWords(str) {
    return capitalize(splitKebabCase(str));
}
function stringToWords(str) {
    return capitalize(splitCamelCase(splitSnakeCase(splitKebabCase(str))));
}
function substringStartsWith(str, start, end, target) {
    var len = target.length;
    if (len > end - start)
        return false;
    for (var i = 0; i < len; i++) {
        if (str.charCodeAt(start + i) !== target.charCodeAt(i))
            return false;
    }
    return true;
}
function interpolate(str, params) {
    var names = Object.keys(params);
    var values = Object.values(params);
    return new (Function.bind.apply(Function, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])([void 0], names, ["return `" + str + "`;"])))().apply(void 0, values);
}
function trimChar(str, char) {
    var start = 0;
    var end = str.length;
    while (start < end && str[start] === char)
        ++start;
    while (end > start && str[end - 1] === char)
        --end;
    return (start > 0 || end < str.length) ? str.substring(start, end) : str;
}
function trimCharStart(str, char) {
    var start = 0;
    var end = str.length;
    while (start < end && str[start] === char)
        ++start;
    return (start > 0) ? str.substring(start, end) : str;
}
function trimCharEnd(str, char) {
    var end = str.length;
    while (end > 0 && str[end - 1] === char)
        --end;
    return (end < str.length) ? str.substring(0, end) : str;
}
/** Simple function to strip tags from a string */
function stripTags(str) {
    return str.replace(/<\/?[^>]+>/g, '');
}
//# sourceMappingURL=string.js.map

/***/ }),
/* 42 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return symbol; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return normalizeTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return symbolList; });
/* harmony import */ var _symbol__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(18);
/*
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function symbol(args, type, description) {
    return Object(_symbol__WEBPACK_IMPORTED_MODULE_0__[/* MSymbol */ "d"])('', args, type, description);
}
function normalizeTable(table) {
    _normalizeTable('', '', table);
}
function symbolList(table) {
    var list = [];
    _symbolList(table, list);
    return list;
}
function formatKey(key) {
    var regex = /([a-z])([A-Z])([a-z]|$)/g;
    // do this twice because 'xXxX'
    return key.replace(regex, function (s, a, b, c) { return a + "-" + b.toLocaleLowerCase() + c; }).replace(regex, function (s, a, b, c) { return a + "-" + b.toLocaleLowerCase() + c; });
}
function _normalizeTable(namespace, key, obj) {
    if (Object(_symbol__WEBPACK_IMPORTED_MODULE_0__[/* isSymbol */ "e"])(obj)) {
        obj.info.namespace = namespace;
        obj.info.name = obj.info.name || formatKey(key);
        obj.id = obj.info.namespace + "." + obj.info.name;
        return;
    }
    var currentNs = "" + (obj['@namespace'] || formatKey(key));
    var newNs = namespace ? namespace + "." + currentNs : currentNs;
    for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
        var childKey = _a[_i];
        if (typeof obj[childKey] !== 'object' && !Object(_symbol__WEBPACK_IMPORTED_MODULE_0__[/* isSymbol */ "e"])(obj[childKey]))
            continue;
        _normalizeTable(newNs, childKey, obj[childKey]);
    }
}
function _symbolList(obj, list) {
    if (Object(_symbol__WEBPACK_IMPORTED_MODULE_0__[/* isSymbol */ "e"])(obj)) {
        list.push(obj);
        return;
    }
    for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
        var childKey = _a[_i];
        if (typeof obj[childKey] !== 'object' && !Object(_symbol__WEBPACK_IMPORTED_MODULE_0__[/* isSymbol */ "e"])(obj[childKey]))
            continue;
        _symbolList(obj[childKey], list);
    }
}
//# sourceMappingURL=helpers.js.map

/***/ }),
/* 43 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Color", function() { return Color; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorList", function() { return ColorList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorTable", function() { return ColorTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorMap", function() { return ColorMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getAdjustedColorMap", function() { return getAdjustedColorMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorSwatch", function() { return ColorSwatch; });
/* harmony import */ var _spaces_hcl__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(233);
/* harmony import */ var _spaces_lab__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(161);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function Color(hex) { return hex; }
(function (Color) {
    function toStyle(hexColor) {
        return "rgb(" + (hexColor >> 16 & 255) + ", " + (hexColor >> 8 & 255) + ", " + (hexColor & 255) + ")";
    }
    Color.toStyle = toStyle;
    function toHexString(hexColor) {
        return '0x' + ('000000' + hexColor.toString(16)).slice(-6);
    }
    Color.toHexString = toHexString;
    function toRgbString(hexColor) {
        return "RGB: " + Color.toRgb(hexColor).join(', ');
    }
    Color.toRgbString = toRgbString;
    function toRgb(hexColor) {
        return [hexColor >> 16 & 255, hexColor >> 8 & 255, hexColor & 255];
    }
    Color.toRgb = toRgb;
    function toRgbNormalized(hexColor) {
        return [(hexColor >> 16 & 255) / 255, (hexColor >> 8 & 255) / 255, (hexColor & 255) / 255];
    }
    Color.toRgbNormalized = toRgbNormalized;
    function fromRgb(r, g, b) {
        return ((r << 16) | (g << 8) | b);
    }
    Color.fromRgb = fromRgb;
    function fromNormalizedRgb(r, g, b) {
        return (((r * 255) << 16) | ((g * 255) << 8) | (b * 255));
    }
    Color.fromNormalizedRgb = fromNormalizedRgb;
    function fromArray(array, offset) {
        return fromRgb(array[offset], array[offset + 1], array[offset + 2]);
    }
    Color.fromArray = fromArray;
    function fromNormalizedArray(array, offset) {
        return fromNormalizedRgb(array[offset], array[offset + 1], array[offset + 2]);
    }
    Color.fromNormalizedArray = fromNormalizedArray;
    /** Copies hex color to rgb array */
    function toArray(hexColor, array, offset) {
        array[offset] = (hexColor >> 16 & 255);
        array[offset + 1] = (hexColor >> 8 & 255);
        array[offset + 2] = (hexColor & 255);
        return array;
    }
    Color.toArray = toArray;
    /** Copies normalized (0 to 1) hex color to rgb array */
    function toArrayNormalized(hexColor, array, offset) {
        array[offset] = (hexColor >> 16 & 255) / 255;
        array[offset + 1] = (hexColor >> 8 & 255) / 255;
        array[offset + 2] = (hexColor & 255) / 255;
        return array;
    }
    Color.toArrayNormalized = toArrayNormalized;
    /** Copies hex color to rgb vec3 */
    function toVec3(out, hexColor) {
        out[0] = (hexColor >> 16 & 255);
        out[1] = (hexColor >> 8 & 255);
        out[2] = (hexColor & 255);
        return out;
    }
    Color.toVec3 = toVec3;
    /** Copies normalized (0 to 1) hex color to rgb vec3 */
    function toVec3Normalized(out, hexColor) {
        out[0] = (hexColor >> 16 & 255) / 255;
        out[1] = (hexColor >> 8 & 255) / 255;
        out[2] = (hexColor & 255) / 255;
        return out;
    }
    Color.toVec3Normalized = toVec3Normalized;
    /** Linear interpolation between two colors in rgb space */
    function interpolate(c1, c2, t) {
        var r1 = c1 >> 16 & 255;
        var g1 = c1 >> 8 & 255;
        var b1 = c1 & 255;
        var r2 = c2 >> 16 & 255;
        var g2 = c2 >> 8 & 255;
        var b2 = c2 & 255;
        var r = r1 + (r2 - r1) * t;
        var g = g1 + (g2 - g1) * t;
        var b = b1 + (b2 - b1) * t;
        return ((r << 16) | (g << 8) | b);
    }
    Color.interpolate = interpolate;
    var tmpSaturateHcl = [0, 0, 0];
    function saturate(c, amount) {
        _spaces_hcl__WEBPACK_IMPORTED_MODULE_0__[/* Hcl */ "a"].fromColor(tmpSaturateHcl, c);
        return _spaces_hcl__WEBPACK_IMPORTED_MODULE_0__[/* Hcl */ "a"].toColor(_spaces_hcl__WEBPACK_IMPORTED_MODULE_0__[/* Hcl */ "a"].saturate(tmpSaturateHcl, tmpSaturateHcl, amount));
    }
    Color.saturate = saturate;
    function desaturate(c, amount) {
        return saturate(c, -amount);
    }
    Color.desaturate = desaturate;
    var tmpDarkenLab = [0, 0, 0];
    function darken(c, amount) {
        _spaces_lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].fromColor(tmpDarkenLab, c);
        return _spaces_lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].toColor(_spaces_lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].darken(tmpDarkenLab, tmpDarkenLab, amount));
    }
    Color.darken = darken;
    function lighten(c, amount) {
        return darken(c, -amount);
    }
    Color.lighten = lighten;
})(Color || (Color = {}));
function ColorList(label, type, description, list) {
    return { label: label, description: description, list: list, type: type };
}
function ColorTable(o) { return o; }
function ColorMap(o) { return o; }
function getAdjustedColorMap(map, saturation, lightness) {
    var adjustedMap = {};
    for (var e in map) {
        var c = map[e];
        c = Color.saturate(c, saturation);
        c = Color.darken(c, -lightness);
        adjustedMap[e] = c;
    }
    return adjustedMap;
}
function ColorSwatch(l) { return l; }
//# sourceMappingURL=color.js.map

/***/ }),
/* 44 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ Observable_Observable; });

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/canReportError.js
var canReportError = __webpack_require__(302);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscriber.js
var Subscriber = __webpack_require__(35);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/rxSubscriber.js
var rxSubscriber = __webpack_require__(277);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Observer.js
var Observer = __webpack_require__(313);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/toSubscriber.js
/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */



function toSubscriber(nextOrObserver, error, complete) {
    if (nextOrObserver) {
        if (nextOrObserver instanceof Subscriber["a" /* Subscriber */]) {
            return nextOrObserver;
        }
        if (nextOrObserver[rxSubscriber["a" /* rxSubscriber */]]) {
            return nextOrObserver[rxSubscriber["a" /* rxSubscriber */]]();
        }
    }
    if (!nextOrObserver && !error && !complete) {
        return new Subscriber["a" /* Subscriber */](Observer["a" /* empty */]);
    }
    return new Subscriber["a" /* Subscriber */](nextOrObserver, error, complete);
}
//# sourceMappingURL=toSubscriber.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/observable.js
var observable = __webpack_require__(203);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/pipe.js
var pipe = __webpack_require__(273);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/config.js
var config = __webpack_require__(175);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/Observable.js
/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */





var Observable_Observable = /*@__PURE__*/ (function () {
    function Observable(subscribe) {
        this._isScalar = false;
        if (subscribe) {
            this._subscribe = subscribe;
        }
    }
    Observable.prototype.lift = function (operator) {
        var observable = new Observable();
        observable.source = this;
        observable.operator = operator;
        return observable;
    };
    Observable.prototype.subscribe = function (observerOrNext, error, complete) {
        var operator = this.operator;
        var sink = toSubscriber(observerOrNext, error, complete);
        if (operator) {
            sink.add(operator.call(sink, this.source));
        }
        else {
            sink.add(this.source || (config["a" /* config */].useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?
                this._subscribe(sink) :
                this._trySubscribe(sink));
        }
        if (config["a" /* config */].useDeprecatedSynchronousErrorHandling) {
            if (sink.syncErrorThrowable) {
                sink.syncErrorThrowable = false;
                if (sink.syncErrorThrown) {
                    throw sink.syncErrorValue;
                }
            }
        }
        return sink;
    };
    Observable.prototype._trySubscribe = function (sink) {
        try {
            return this._subscribe(sink);
        }
        catch (err) {
            if (config["a" /* config */].useDeprecatedSynchronousErrorHandling) {
                sink.syncErrorThrown = true;
                sink.syncErrorValue = err;
            }
            if (Object(canReportError["a" /* canReportError */])(sink)) {
                sink.error(err);
            }
            else {
                console.warn(err);
            }
        }
    };
    Observable.prototype.forEach = function (next, promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var subscription;
            subscription = _this.subscribe(function (value) {
                try {
                    next(value);
                }
                catch (err) {
                    reject(err);
                    if (subscription) {
                        subscription.unsubscribe();
                    }
                }
            }, reject, resolve);
        });
    };
    Observable.prototype._subscribe = function (subscriber) {
        var source = this.source;
        return source && source.subscribe(subscriber);
    };
    Observable.prototype[observable["a" /* observable */]] = function () {
        return this;
    };
    Observable.prototype.pipe = function () {
        var operations = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            operations[_i] = arguments[_i];
        }
        if (operations.length === 0) {
            return this;
        }
        return Object(pipe["b" /* pipeFromArray */])(operations)(this);
    };
    Observable.prototype.toPromise = function (promiseCtor) {
        var _this = this;
        promiseCtor = getPromiseCtor(promiseCtor);
        return new promiseCtor(function (resolve, reject) {
            var value;
            _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); });
        });
    };
    Observable.create = function (subscribe) {
        return new Observable(subscribe);
    };
    return Observable;
}());

function getPromiseCtor(promiseCtor) {
    if (!promiseCtor) {
        promiseCtor = config["a" /* config */].Promise || Promise;
    }
    if (!promiseCtor) {
        throw new Error('no Promise impl found');
    }
    return promiseCtor;
}
//# sourceMappingURL=Observable.js.map


/***/ }),
/* 45 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MarkerAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return MarkerActions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return applyMarkerActionAtPosition; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return applyMarkerAction; });
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _bit_flags__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(207);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var MarkerAction;
(function (MarkerAction) {
    MarkerAction[MarkerAction["None"] = 0] = "None";
    MarkerAction[MarkerAction["Highlight"] = 1] = "Highlight";
    MarkerAction[MarkerAction["RemoveHighlight"] = 2] = "RemoveHighlight";
    MarkerAction[MarkerAction["Select"] = 4] = "Select";
    MarkerAction[MarkerAction["Deselect"] = 8] = "Deselect";
    MarkerAction[MarkerAction["Toggle"] = 16] = "Toggle";
    MarkerAction[MarkerAction["Clear"] = 32] = "Clear";
})(MarkerAction || (MarkerAction = {}));
var MarkerActions;
(function (MarkerActions) {
    MarkerActions.is = _bit_flags__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].has;
    MarkerActions.All = (MarkerAction.Highlight | MarkerAction.RemoveHighlight |
        MarkerAction.Select | MarkerAction.Deselect | MarkerAction.Toggle |
        MarkerAction.Clear);
    MarkerActions.Highlighting = (MarkerAction.Highlight | MarkerAction.RemoveHighlight |
        MarkerAction.Clear);
    MarkerActions.Selecting = (MarkerAction.Select | MarkerAction.Deselect | MarkerAction.Toggle |
        MarkerAction.Clear);
})(MarkerActions || (MarkerActions = {}));
function applyMarkerActionAtPosition(array, i, action) {
    var v = array[i];
    switch (action) {
        case MarkerAction.Highlight:
            if (v % 2 === 0) {
                array[i] = v + 1;
                return true;
            }
            return false;
        case MarkerAction.RemoveHighlight:
            if (v % 2 !== 0) {
                array[i] = v - 1;
                return true;
            }
            return false;
        case MarkerAction.Select:
            if (v < 2) {
                array[i] = v + 2;
                return true;
            }
            return false;
        case MarkerAction.Deselect:
            array[i] = v % 2;
            return array[i] !== v;
        case MarkerAction.Toggle:
            if (v >= 2)
                array[i] = v - 2;
            else
                array[i] = v + 2;
            return true;
        case MarkerAction.Clear:
            array[i] = 0;
            return v !== 0;
    }
    return false;
}
function applyMarkerAction(array, set, action) {
    var changed = false;
    if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].is(set)) {
        for (var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].start(set), _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].end(set); i < _i; i++) {
            changed = applyMarkerActionAtPosition(array, i, action) || changed;
        }
    }
    else {
        for (var i = 0, _i = set.length; i < _i; i++) {
            changed = applyMarkerActionAtPosition(array, set[i], action) || changed;
        }
    }
    return changed;
}
//# sourceMappingURL=marker-action.js.map

/***/ }),
/* 46 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return halfPI; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return degToRad; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return radToDeg; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isPowerOfTwo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return absMax; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return arcLength; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var halfPI = Math.PI / 2;
function degToRad(deg) {
    return deg * 0.01745; // deg * Math.PI / 180
}
function radToDeg(rad) {
    return rad * 57.29578; // rad * 180 / Math.PI
}
function isPowerOfTwo(x) {
    return (x !== 0) && (x & (x - 1)) === 0;
}
/** return the value that has the largest absolute value */
function absMax() {
    var values = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        values[_i] = arguments[_i];
    }
    var max = 0;
    var absMax = 0;
    for (var i = 0, il = values.length; i < il; ++i) {
        var value = values[i];
        var abs = Math.abs(value);
        if (abs > absMax) {
            max = value;
            absMax = abs;
        }
    }
    return max;
}
/** Length of an arc with angle in radians */
function arcLength(angle, radius) {
    return angle * radius;
}
//# sourceMappingURL=misc.js.map

/***/ }),
/* 47 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ColorNames; });
/* unused harmony export ColorNamesValueMap */
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(43);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/** X11 color names http://www.w3.org/TR/css3-color/#svg-color */
var ColorNames = Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorMap"])({
    aliceblue: 0xf0f8ff,
    antiquewhite: 0xfaebd7,
    aqua: 0x00ffff,
    aquamarine: 0x7fffd4,
    azure: 0xf0ffff,
    beige: 0xf5f5dc,
    bisque: 0xffe4c4,
    black: 0x000000,
    blanchedalmond: 0xffebcd,
    blue: 0x0000ff,
    blueviolet: 0x8a2be2,
    brown: 0xa52a2a,
    burlywood: 0xdeb887,
    cadetblue: 0x5f9ea0,
    chartreuse: 0x7fff00,
    chocolate: 0xd2691e,
    coral: 0xff7f50,
    cornflower: 0x6495ed,
    cornflowerblue: 0x6495ed,
    cornsilk: 0xfff8dc,
    crimson: 0xdc143c,
    cyan: 0x00ffff,
    darkblue: 0x00008b,
    darkcyan: 0x008b8b,
    darkgoldenrod: 0xb8860b,
    darkgray: 0xa9a9a9,
    darkgreen: 0x006400,
    darkgrey: 0xa9a9a9,
    darkkhaki: 0xbdb76b,
    darkmagenta: 0x8b008b,
    darkolivegreen: 0x556b2f,
    darkorange: 0xff8c00,
    darkorchid: 0x9932cc,
    darkred: 0x8b0000,
    darksalmon: 0xe9967a,
    darkseagreen: 0x8fbc8f,
    darkslateblue: 0x483d8b,
    darkslategray: 0x2f4f4f,
    darkslategrey: 0x2f4f4f,
    darkturquoise: 0x00ced1,
    darkviolet: 0x9400d3,
    deeppink: 0xff1493,
    deepskyblue: 0x00bfff,
    dimgray: 0x696969,
    dimgrey: 0x696969,
    dodgerblue: 0x1e90ff,
    firebrick: 0xb22222,
    floralwhite: 0xfffaf0,
    forestgreen: 0x228b22,
    fuchsia: 0xff00ff,
    gainsboro: 0xdcdcdc,
    ghostwhite: 0xf8f8ff,
    gold: 0xffd700,
    goldenrod: 0xdaa520,
    gray: 0x808080,
    green: 0x008000,
    greenyellow: 0xadff2f,
    grey: 0x808080,
    honeydew: 0xf0fff0,
    hotpink: 0xff69b4,
    indianred: 0xcd5c5c,
    indigo: 0x4b0082,
    ivory: 0xfffff0,
    khaki: 0xf0e68c,
    laserlemon: 0xffff54,
    lavender: 0xe6e6fa,
    lavenderblush: 0xfff0f5,
    lawngreen: 0x7cfc00,
    lemonchiffon: 0xfffacd,
    lightblue: 0xadd8e6,
    lightcoral: 0xf08080,
    lightcyan: 0xe0ffff,
    lightgoldenrod: 0xfafad2,
    lightgoldenrodyellow: 0xfafad2,
    lightgray: 0xd3d3d3,
    lightgreen: 0x90ee90,
    lightgrey: 0xd3d3d3,
    lightpink: 0xffb6c1,
    lightsalmon: 0xffa07a,
    lightseagreen: 0x20b2aa,
    lightskyblue: 0x87cefa,
    lightslategray: 0x778899,
    lightslategrey: 0x778899,
    lightsteelblue: 0xb0c4de,
    lightyellow: 0xffffe0,
    lime: 0x00ff00,
    limegreen: 0x32cd32,
    linen: 0xfaf0e6,
    magenta: 0xff00ff,
    maroon: 0x800000,
    maroon2: 0x7f0000,
    maroon3: 0xb03060,
    mediumaquamarine: 0x66cdaa,
    mediumblue: 0x0000cd,
    mediumorchid: 0xba55d3,
    mediumpurple: 0x9370db,
    mediumseagreen: 0x3cb371,
    mediumslateblue: 0x7b68ee,
    mediumspringgreen: 0x00fa9a,
    mediumturquoise: 0x48d1cc,
    mediumvioletred: 0xc71585,
    midnightblue: 0x191970,
    mintcream: 0xf5fffa,
    mistyrose: 0xffe4e1,
    moccasin: 0xffe4b5,
    navajowhite: 0xffdead,
    navy: 0x000080,
    oldlace: 0xfdf5e6,
    olive: 0x808000,
    olivedrab: 0x6b8e23,
    orange: 0xffa500,
    orangered: 0xff4500,
    orchid: 0xda70d6,
    palegoldenrod: 0xeee8aa,
    palegreen: 0x98fb98,
    paleturquoise: 0xafeeee,
    palevioletred: 0xdb7093,
    papayawhip: 0xffefd5,
    peachpuff: 0xffdab9,
    peru: 0xcd853f,
    pink: 0xffc0cb,
    plum: 0xdda0dd,
    powderblue: 0xb0e0e6,
    purple: 0x800080,
    purple2: 0x7f007f,
    purple3: 0xa020f0,
    rebeccapurple: 0x663399,
    red: 0xff0000,
    rosybrown: 0xbc8f8f,
    royalblue: 0x4169e1,
    saddlebrown: 0x8b4513,
    salmon: 0xfa8072,
    sandybrown: 0xf4a460,
    seagreen: 0x2e8b57,
    seashell: 0xfff5ee,
    sienna: 0xa0522d,
    silver: 0xc0c0c0,
    skyblue: 0x87ceeb,
    slateblue: 0x6a5acd,
    slategray: 0x708090,
    slategrey: 0x708090,
    snow: 0xfffafa,
    springgreen: 0x00ff7f,
    steelblue: 0x4682b4,
    tan: 0xd2b48c,
    teal: 0x008080,
    thistle: 0xd8bfd8,
    tomato: 0xff6347,
    turquoise: 0x40e0d0,
    violet: 0xee82ee,
    wheat: 0xf5deb3,
    white: 0xffffff,
    whitesmoke: 0xf5f5f5,
    yellow: 0xffff00,
    yellowgreen: 0x9acd32
});
var ColorNamesValueMap = (function () {
    var map = new Map();
    Object.keys(ColorNames).forEach(function (name) {
        map.set(ColorNames[name], name);
    });
    return map;
})();
//# sourceMappingURL=names.js.map

/***/ }),
/* 48 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export UnitsVisual */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return UnitsMeshParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return UnitsMeshVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return UnitsSpheresParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return UnitsSpheresVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return UnitsPointsParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return UnitsPointsVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UnitsLinesParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UnitsLinesVisual; });
/* unused harmony export UnitsTextParams */
/* unused harmony export UnitsTextVisual */
/* unused harmony export UnitsDirectVolumeParams */
/* unused harmony export UnitsDirectVolumeVisual */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return UnitsTextureMeshParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return UnitsTextureMeshVisual; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _visual__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69);
/* harmony import */ var _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(145);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(89);
/* harmony import */ var _visual_util_common__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(51);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(115);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(164);
/* harmony import */ var _mol_theme_color__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(196);
/* harmony import */ var _mol_geo_geometry_marker_data__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(125);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(5);
/* harmony import */ var _mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(146);
/* harmony import */ var _mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(117);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(39);
/* harmony import */ var _mol_theme_size__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(150);
/* harmony import */ var _mol_geo_geometry_spheres_spheres__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(258);
/* harmony import */ var _mol_geo_geometry_points_points__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(257);
/* harmony import */ var _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(74);
/* harmony import */ var _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(123);
/* harmony import */ var _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(265);
/* harmony import */ var _mol_geo_geometry_texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(259);
/* harmony import */ var _params__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(94);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
























function createUnitsRenderObject(group, geometry, locationIt, theme, props, materialId) {
    var _a = _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Geometry */ "a"].getUtils(geometry), createValues = _a.createValues, createRenderableState = _a.createRenderableState;
    var transform = Object(_visual_util_common__WEBPACK_IMPORTED_MODULE_5__[/* createUnitsTransform */ "c"])(group);
    var values = createValues(geometry, transform, locationIt, theme, props);
    var state = createRenderableState(props);
    return Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_6__[/* createRenderObject */ "a"])(geometry.kind, values, state, materialId);
}
function UnitsVisual(builder, materialId) {
    var defaultProps = builder.defaultProps, createGeometry = builder.createGeometry, createLocationIterator = builder.createLocationIterator, getLoci = builder.getLoci, eachLocation = builder.eachLocation, setUpdateState = builder.setUpdateState;
    var _a = builder.geometryUtils, createEmptyGeometry = _a.createEmpty, updateValues = _a.updateValues, updateBoundingSphere = _a.updateBoundingSphere, updateRenderableState = _a.updateRenderableState;
    var updateState = _util__WEBPACK_IMPORTED_MODULE_9__[/* VisualUpdateState */ "a"].create();
    var renderObject;
    var newProps = Object.assign({}, defaultProps);
    var newTheme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_4__[/* Theme */ "a"].createEmpty();
    var newStructureGroup;
    var currentProps;
    var currentTheme;
    var currentStructureGroup;
    var geometry;
    var locationIt;
    function prepareUpdate(theme, props, structureGroup) {
        if (props === void 0) { props = {}; }
        if (!structureGroup && !currentStructureGroup) {
            throw new Error('missing structureGroup');
        }
        newProps = Object.assign({}, currentProps, props);
        newTheme = theme;
        newStructureGroup = structureGroup;
        _util__WEBPACK_IMPORTED_MODULE_9__[/* VisualUpdateState */ "a"].reset(updateState);
        if (!renderObject) {
            updateState.createNew = true;
        }
        else if (!currentStructureGroup || !_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].SymmetryGroup.areInvariantElementsEqual(newStructureGroup.group, currentStructureGroup.group)) {
            updateState.createNew = true;
        }
        if (updateState.createNew) {
            updateState.createGeometry = true;
            return;
        }
        setUpdateState(updateState, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
        if (!_mol_theme_color__WEBPACK_IMPORTED_MODULE_10__[/* ColorTheme */ "a"].areEqual(newTheme.color, currentTheme.color)) {
            // console.log('new colorTheme')
            updateState.updateColor = true;
        }
        if (!Object(_mol_util__WEBPACK_IMPORTED_MODULE_12__[/* deepEqual */ "h"])(newProps.unitKinds, currentProps.unitKinds)) {
            // console.log('new unitKinds')
            updateState.createGeometry = true;
        }
        if (newStructureGroup.group.transformHash !== currentStructureGroup.group.transformHash) {
            // console.log('new transformHash')
            if (newStructureGroup.group.units.length !== currentStructureGroup.group.units.length || updateState.updateColor) {
                updateState.updateTransform = true;
            }
            else {
                updateState.updateMatrix = true;
            }
        }
        // check if the conformation of unit.model has changed
        var newUnit = newStructureGroup.group.units[0];
        var currentUnit = currentStructureGroup.group.units[0];
        // if (Unit.conformationId(newUnit) !== Unit.conformationId(currentUnit)) {
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].conformationId(newUnit) !== _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].conformationId(currentUnit)
            // TODO: this needs more attention
            || newUnit.conformation !== currentUnit.conformation) {
            // console.log('new conformation')
            updateState.updateTransform = true;
            updateState.createGeometry = true;
        }
        if (updateState.updateTransform) {
            updateState.updateColor = true;
            updateState.updateSize = true;
            updateState.updateMatrix = true;
        }
        if (updateState.createGeometry) {
            updateState.updateColor = true;
            updateState.updateSize = true;
        }
    }
    function update(newGeometry) {
        if (updateState.createNew) {
            locationIt = createLocationIterator(newStructureGroup);
            if (newGeometry) {
                renderObject = createUnitsRenderObject(newStructureGroup.group, newGeometry, locationIt, newTheme, newProps, materialId);
            }
            else {
                throw new Error('expected geometry to be given');
            }
        }
        else {
            if (!renderObject) {
                throw new Error('expected renderObject to be available');
            }
            if (updateState.updateTransform) {
                // console.log('update transform')
                locationIt = createLocationIterator(newStructureGroup);
                var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
                Object(_mol_geo_geometry_marker_data__WEBPACK_IMPORTED_MODULE_11__[/* createMarkers */ "a"])(instanceCount * groupCount, renderObject.values);
            }
            if (updateState.updateMatrix) {
                // console.log('update matrix')
                Object(_visual_util_common__WEBPACK_IMPORTED_MODULE_5__[/* createUnitsTransform */ "c"])(newStructureGroup.group, renderObject.values);
            }
            if (updateState.createGeometry) {
                // console.log('update geometry')
                if (newGeometry) {
                    _mol_util__WEBPACK_IMPORTED_MODULE_12__[/* ValueCell */ "e"].update(renderObject.values.drawCount, _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Geometry */ "a"].getDrawCount(newGeometry));
                }
                else {
                    throw new Error('expected geometry to be given');
                }
            }
            if (updateState.updateTransform || updateState.createGeometry) {
                // console.log('UnitsVisual.updateBoundingSphere')
                updateBoundingSphere(renderObject.values, newGeometry || geometry);
            }
            if (updateState.updateSize) {
                // not all geometries have size data, so check here
                if ('uSize' in renderObject.values) {
                    // console.log('update size')
                    Object(_mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_13__[/* createSizes */ "a"])(locationIt, newTheme.size, renderObject.values);
                }
            }
            if (updateState.updateColor) {
                // console.log('update color')
                Object(_mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_14__[/* createColors */ "a"])(locationIt, newTheme.color, renderObject.values);
            }
            updateValues(renderObject.values, newProps);
            updateRenderableState(renderObject.state, newProps);
        }
        currentProps = newProps;
        currentTheme = newTheme;
        currentStructureGroup = newStructureGroup;
        if (newGeometry)
            geometry = newGeometry;
    }
    function _createGeometry(ctx, unit, structure, theme, props, geometry) {
        return Object(_visual_util_common__WEBPACK_IMPORTED_MODULE_5__[/* includesUnitKind */ "j"])(props.unitKinds, unit)
            ? createGeometry(ctx, unit, structure, theme, props, geometry)
            : createEmptyGeometry(geometry);
    }
    function lociIsSuperset(loci) {
        if (Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_7__["isEveryLoci"])(loci))
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].isLoci(loci) && _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].areRootsEquivalent(loci.structure, currentStructureGroup.structure))
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.is(loci) && _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].areRootsEquivalent(loci.structure, currentStructureGroup.structure)) {
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isWholeStructure(loci))
                return true;
        }
        return false;
    }
    function lociApply(loci, apply, isMarking) {
        if (lociIsSuperset(loci)) {
            return apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_8__["Interval"].ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
        }
        else {
            return eachLocation(loci, currentStructureGroup, apply, isMarking);
        }
    }
    return {
        get groupCount() { return locationIt ? locationIt.count : 0; },
        get renderObject() { return locationIt && locationIt.count ? renderObject : undefined; },
        createOrUpdate: function (ctx, theme, props, structureGroup) {
            if (props === void 0) { props = {}; }
            prepareUpdate(theme, props, structureGroup || currentStructureGroup);
            if (updateState.createGeometry) {
                var newGeometry = _createGeometry(ctx, newStructureGroup.group.units[0], newStructureGroup.structure, newTheme, newProps, geometry);
                return newGeometry instanceof Promise ? newGeometry.then(update) : update(newGeometry);
            }
            else {
                update();
            }
        },
        getLoci: function (pickingId) {
            return renderObject ? getLoci(pickingId, currentStructureGroup, renderObject.id) : _mol_model_loci__WEBPACK_IMPORTED_MODULE_7__["EmptyLoci"];
        },
        mark: function (loci, action) {
            return _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].mark(renderObject, loci, action, lociApply);
        },
        setVisibility: function (visible) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setVisibility(renderObject, visible);
        },
        setAlphaFactor: function (alphaFactor) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setAlphaFactor(renderObject, alphaFactor);
        },
        setPickable: function (pickable) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setPickable(renderObject, pickable);
        },
        setTransform: function (matrix, instanceMatrices) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setTransform(renderObject, matrix, instanceMatrices);
        },
        setOverpaint: function (overpaint) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setOverpaint(renderObject, overpaint, lociApply, true);
        },
        setTransparency: function (transparency) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setTransparency(renderObject, transparency, lociApply, true);
        },
        setClipping: function (clipping) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setClipping(renderObject, clipping, lociApply, true);
        },
        destroy: function () {
            // TODO
            renderObject = undefined;
        }
    };
}
// mesh
var UnitsMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureMeshParams */ "c"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsMeshVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_15__[/* Mesh */ "a"].Utils }), materialId);
}
// spheres
var UnitsSpheresParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureSpheresParams */ "f"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsSpheresVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
        }, geometryUtils: _mol_geo_geometry_spheres_spheres__WEBPACK_IMPORTED_MODULE_17__[/* Spheres */ "a"].Utils }), materialId);
}
// points
var UnitsPointsParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructurePointsParams */ "e"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsPointsVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
        }, geometryUtils: _mol_geo_geometry_points_points__WEBPACK_IMPORTED_MODULE_18__[/* Points */ "a"].Utils }), materialId);
}
// lines
var UnitsLinesParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureLinesParams */ "b"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsLinesVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
        }, geometryUtils: _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_19__[/* Lines */ "a"].Utils }), materialId);
}
// text
var UnitsTextParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureTextParams */ "g"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsTextVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
            if (newProps.background !== currentProps.background)
                state.createGeometry = true;
            if (newProps.backgroundMargin !== currentProps.backgroundMargin)
                state.createGeometry = true;
            if (newProps.tether !== currentProps.tether)
                state.createGeometry = true;
            if (newProps.tetherLength !== currentProps.tetherLength)
                state.createGeometry = true;
            if (newProps.tetherBaseWidth !== currentProps.tetherBaseWidth)
                state.createGeometry = true;
            if (newProps.attachment !== currentProps.attachment)
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_20__[/* Text */ "a"].Utils }), materialId);
}
// direct-volume
var UnitsDirectVolumeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureDirectVolumeParams */ "a"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsDirectVolumeVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_21__[/* DirectVolume */ "a"].Utils }), materialId);
}
// texture-mesh
var UnitsTextureMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureTextureMeshParams */ "h"]), _params__WEBPACK_IMPORTED_MODULE_23__[/* StructureParams */ "d"]);
function UnitsTextureMeshVisual(builder, materialId) {
    return UnitsVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_22__[/* TextureMesh */ "a"].Utils }), materialId);
}
//# sourceMappingURL=units-visual.js.map

/***/ }),
/* 49 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ shape_Shape; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ shape_ShapeGroup; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/geometry.js
var geometry_geometry = __webpack_require__(145);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var mol_math_geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/centroid-helper.js
var centroid_helper = __webpack_require__(195);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size/shape-group.js
var shape_group = __webpack_require__(360);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color/shape-group.js
var color_shape_group = __webpack_require__(361);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/transform-data.js
var transform_data = __webpack_require__(182);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/render-object.js + 8 modules
var render_object = __webpack_require__(115);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/location-iterator.js
var location_iterator = __webpack_require__(86);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/shape/shape.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var shape_Shape;
(function (Shape) {
    function create(name, sourceData, geometry, getColor, getSize, getLabel, transforms) {
        return {
            id: mol_util["c" /* UUID */].create22(),
            name: name,
            sourceData: sourceData,
            geometry: geometry,
            transforms: transforms || [linear_algebra["Mat4"].identity()],
            get groupCount() { return geometry_geometry["a" /* Geometry */].getGroupCount(geometry); },
            getColor: getColor,
            getSize: getSize,
            getLabel: getLabel
        };
    }
    Shape.create = create;
    function getTheme(shape) {
        return {
            color: Object(color_shape_group["a" /* ShapeGroupColorTheme */])({ shape: shape }, {}),
            size: Object(shape_group["a" /* ShapeGroupSizeTheme */])({ shape: shape }, {})
        };
    }
    Shape.getTheme = getTheme;
    function groupIterator(shape) {
        var instanceCount = shape.transforms.length;
        var location = shape_ShapeGroup.Location(shape);
        var getLocation = function (groupIndex, instanceIndex) {
            location.group = groupIndex;
            location.instance = instanceIndex;
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(shape.groupCount, instanceCount, getLocation);
    }
    Shape.groupIterator = groupIterator;
    function createTransform(transforms, transformData) {
        var transformArray = transformData && transformData.aTransform.ref.value.length >= transforms.length * 16 ? transformData.aTransform.ref.value : new Float32Array(transforms.length * 16);
        for (var i = 0, il = transforms.length; i < il; ++i) {
            linear_algebra["Mat4"].toArray(transforms[i], transformArray, i * 16);
        }
        return Object(transform_data["b" /* createTransform */])(transformArray, transforms.length, transformData);
    }
    Shape.createTransform = createTransform;
    function createRenderObject(shape, props) {
        props;
        var theme = Shape.getTheme(shape);
        var utils = geometry_geometry["a" /* Geometry */].getUtils(shape.geometry);
        var materialId = Object(render_object["c" /* getNextMaterialId */])();
        var locationIt = groupIterator(shape);
        var transform = Shape.createTransform(shape.transforms);
        var values = utils.createValues(shape.geometry, transform, locationIt, theme, props);
        var state = utils.createRenderableState(props);
        return Object(render_object["a" /* createRenderObject */])(shape.geometry.kind, values, state, materialId);
    }
    Shape.createRenderObject = createRenderObject;
    function Loci(shape) { return { kind: 'shape-loci', shape: shape }; }
    Shape.Loci = Loci;
    function isLoci(x) { return !!x && x.kind === 'shape-loci'; }
    Shape.isLoci = isLoci;
    function areLociEqual(a, b) { return a.shape === b.shape; }
    Shape.areLociEqual = areLociEqual;
    function isLociEmpty(loci) { return loci.shape.groupCount === 0; }
    Shape.isLociEmpty = isLociEmpty;
})(shape_Shape || (shape_Shape = {}));
var shape_ShapeGroup;
(function (ShapeGroup) {
    function Location(shape, group, instance) {
        if (group === void 0) { group = 0; }
        if (instance === void 0) { instance = 0; }
        return { kind: 'group-location', shape: shape, group: group, instance: instance };
    }
    ShapeGroup.Location = Location;
    function isLocation(x) {
        return !!x && x.kind === 'group-location';
    }
    ShapeGroup.isLocation = isLocation;
    function Loci(shape, groups) {
        return { kind: 'group-loci', shape: shape, groups: groups };
    }
    ShapeGroup.Loci = Loci;
    function isLoci(x) {
        return !!x && x.kind === 'group-loci';
    }
    ShapeGroup.isLoci = isLoci;
    function areLociEqual(a, b) {
        if (a.shape !== b.shape)
            return false;
        if (a.groups.length !== b.groups.length)
            return false;
        for (var i = 0, il = a.groups.length; i < il; ++i) {
            var _a = a.groups[i], idsA = _a.ids, instanceA = _a.instance;
            var _b = b.groups[i], idsB = _b.ids, instanceB = _b.instance;
            if (instanceA !== instanceB)
                return false;
            if (!mol_data_int["OrderedSet"].areEqual(idsA, idsB))
                return false;
        }
        return true;
    }
    ShapeGroup.areLociEqual = areLociEqual;
    function isLociEmpty(loci) {
        return size(loci) === 0 ? true : false;
    }
    ShapeGroup.isLociEmpty = isLociEmpty;
    function size(loci) {
        var size = 0;
        for (var _i = 0, _a = loci.groups; _i < _a.length; _i++) {
            var group = _a[_i];
            size += mol_data_int["OrderedSet"].size(group.ids);
        }
        return size;
    }
    ShapeGroup.size = size;
    var sphereHelper = new centroid_helper["a" /* CentroidHelper */](), tmpPos = linear_algebra["Vec3"].zero();
    function sphereHelperInclude(groups, mapping, positions, transforms) {
        var indices = mapping.indices, offsets = mapping.offsets;
        var _loop_1 = function (ids, instance) {
            mol_data_int["OrderedSet"].forEach(ids, function (v) {
                for (var i = offsets[v], il = offsets[v + 1]; i < il; ++i) {
                    linear_algebra["Vec3"].fromArray(tmpPos, positions, indices[i] * 3);
                    linear_algebra["Vec3"].transformMat4(tmpPos, tmpPos, transforms[instance]);
                    sphereHelper.includeStep(tmpPos);
                }
            });
        };
        for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
            var _a = groups_1[_i], ids = _a.ids, instance = _a.instance;
            _loop_1(ids, instance);
        }
    }
    function sphereHelperRadius(groups, mapping, positions, transforms) {
        var indices = mapping.indices, offsets = mapping.offsets;
        var _loop_2 = function (ids, instance) {
            mol_data_int["OrderedSet"].forEach(ids, function (v) {
                for (var i = offsets[v], il = offsets[v + 1]; i < il; ++i) {
                    linear_algebra["Vec3"].fromArray(tmpPos, positions, indices[i] * 3);
                    linear_algebra["Vec3"].transformMat4(tmpPos, tmpPos, transforms[instance]);
                    sphereHelper.radiusStep(tmpPos);
                }
            });
        };
        for (var _i = 0, groups_2 = groups; _i < groups_2.length; _i++) {
            var _a = groups_2[_i], ids = _a.ids, instance = _a.instance;
            _loop_2(ids, instance);
        }
    }
    function getBoundingSphere(loci, boundingSphere) {
        if (!boundingSphere)
            boundingSphere = Object(mol_math_geometry["g" /* Sphere3D */])();
        sphereHelper.reset();
        var padding = 0;
        var _a = loci.shape, geometry = _a.geometry, transforms = _a.transforms;
        if (geometry.kind === 'mesh' || geometry.kind === 'points') {
            var positions = geometry.kind === 'mesh'
                ? geometry.vertexBuffer.ref.value
                : geometry.centerBuffer.ref.value;
            sphereHelperInclude(loci.groups, geometry.groupMapping, positions, transforms);
            sphereHelper.finishedIncludeStep();
            sphereHelperRadius(loci.groups, geometry.groupMapping, positions, transforms);
        }
        else if (geometry.kind === 'lines') {
            var start = geometry.startBuffer.ref.value;
            var end = geometry.endBuffer.ref.value;
            sphereHelperInclude(loci.groups, geometry.groupMapping, start, transforms);
            sphereHelperInclude(loci.groups, geometry.groupMapping, end, transforms);
            sphereHelper.finishedIncludeStep();
            sphereHelperRadius(loci.groups, geometry.groupMapping, start, transforms);
            sphereHelperRadius(loci.groups, geometry.groupMapping, end, transforms);
        }
        else if (geometry.kind === 'spheres' || geometry.kind === 'text') {
            var positions = geometry.centerBuffer.ref.value;
            sphereHelperInclude(loci.groups, geometry.groupMapping, positions, transforms);
            sphereHelper.finishedIncludeStep();
            sphereHelperRadius(loci.groups, geometry.groupMapping, positions, transforms);
            var _loop_3 = function (ids, instance) {
                mol_data_int["OrderedSet"].forEach(ids, function (v) {
                    var value = loci.shape.getSize(v, instance);
                    if (padding < value)
                        padding = value;
                });
            };
            for (var _i = 0, _b = loci.groups; _i < _b.length; _i++) {
                var _c = _b[_i], ids = _c.ids, instance = _c.instance;
                _loop_3(ids, instance);
            }
        }
        else {
            // use whole shape bounding-sphere for other geometry kinds
            return mol_math_geometry["g" /* Sphere3D */].copy(boundingSphere, geometry.boundingSphere);
        }
        linear_algebra["Vec3"].copy(boundingSphere.center, sphereHelper.center);
        boundingSphere.radius = Math.sqrt(sphereHelper.radiusSq);
        mol_math_geometry["g" /* Sphere3D */].expand(boundingSphere, boundingSphere, padding);
        return boundingSphere;
    }
    ShapeGroup.getBoundingSphere = getBoundingSphere;
})(shape_ShapeGroup || (shape_ShapeGroup = {}));
//# sourceMappingURL=shape.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/shape.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

//# sourceMappingURL=shape.js.map

/***/ }),
/* 50 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToResult; });
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(167);
/* harmony import */ var _subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(286);
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44);
/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */



function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) {
    if (innerSubscriber === void 0) {
        innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_0__[/* InnerSubscriber */ "a"](outerSubscriber, outerValue, outerIndex);
    }
    if (innerSubscriber.closed) {
        return undefined;
    }
    if (result instanceof _Observable__WEBPACK_IMPORTED_MODULE_2__[/* Observable */ "a"]) {
        return result.subscribe(innerSubscriber);
    }
    return Object(_subscribeTo__WEBPACK_IMPORTED_MODULE_1__[/* subscribeTo */ "a"])(result)(innerSubscriber);
}
//# sourceMappingURL=subscribeToResult.js.map


/***/ }),
/* 51 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getResidueLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getAltResidueLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getAltResidueLociFromId; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createUnitsTransform; });
/* unused harmony export UnitKindInfo */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UnitKindOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return includesUnitKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return ensureReasonableResolution; });
/* unused harmony export getConformation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CommonSurfaceParams; });
/* unused harmony export DefaultCommonSurfaceProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return getUnitConformationAndRadius; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getStructureConformationAndRadius; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return isHydrogen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return isTrace; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(182);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(6);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(23);
/* harmony import */ var _mol_theme_size_physical__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(282);
/* harmony import */ var _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(119);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(29);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2);
/* harmony import */ var _mol_math_geometry_boundary__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(185);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(11);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












/** Return a Loci for the elements of a whole residue the elementIndex belongs to. */
function getResidueLoci(structure, unit, elementIndex) {
    var elements = unit.elements, model = unit.model;
    if (_mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].indexOf(elements, elementIndex) !== -1) {
        var _a = model.atomicHierarchy.residueAtomSegments, index = _a.index, offsets = _a.offsets;
        var rI = index[elementIndex];
        var _indices = [];
        for (var i = offsets[rI], il = offsets[rI + 1]; i < il; ++i) {
            var unitIndex = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].indexOf(elements, i);
            if (unitIndex !== -1)
                _indices.push(unitIndex);
        }
        var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].ofSortedArray(_mol_data_int__WEBPACK_IMPORTED_MODULE_4__["SortedArray"].ofSortedArray(_indices));
        return _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
    }
    return _mol_model_loci__WEBPACK_IMPORTED_MODULE_5__["EmptyLoci"];
}
/**
 * Return a Loci for the elements of a whole residue the elementIndex belongs to but
 * restrict to elements that have the same label_alt_id or none
 */
function getAltResidueLoci(structure, unit, elementIndex) {
    var elements = unit.elements, model = unit.model;
    var label_alt_id = model.atomicHierarchy.atoms.label_alt_id;
    var elementAltId = label_alt_id.value(elementIndex);
    if (_mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].indexOf(elements, elementIndex) !== -1) {
        var index = model.atomicHierarchy.residueAtomSegments.index;
        var rI = index[elementIndex];
        return getAltResidueLociFromId(structure, unit, rI, elementAltId);
    }
    return _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci(structure, []);
}
function getAltResidueLociFromId(structure, unit, residueIndex, elementAltId) {
    var elements = unit.elements, model = unit.model;
    var label_alt_id = model.atomicHierarchy.atoms.label_alt_id;
    var offsets = model.atomicHierarchy.residueAtomSegments.offsets;
    var _indices = [];
    for (var i = offsets[residueIndex], il = offsets[residueIndex + 1]; i < il; ++i) {
        var unitIndex = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].indexOf(elements, i);
        if (unitIndex !== -1) {
            var altId = label_alt_id.value(i);
            if (elementAltId === altId || altId === '') {
                _indices.push(unitIndex);
            }
        }
    }
    var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].ofSortedArray(_mol_data_int__WEBPACK_IMPORTED_MODULE_4__["SortedArray"].ofSortedArray(_indices));
    return _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
}
//
function createUnitsTransform(_a, transformData) {
    var units = _a.units;
    var unitCount = units.length;
    var n = unitCount * 16;
    var array = transformData && transformData.aTransform.ref.value.length >= n ? transformData.aTransform.ref.value : new Float32Array(n);
    for (var i = 0; i < unitCount; i++) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat4"].toArray(units[i].conformation.operator.matrix, array, i * 16);
    }
    return Object(_mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_3__[/* createTransform */ "b"])(array, unitCount, transformData);
}
var UnitKindInfo = {
    'atomic': {},
    'spheres': {},
    'gaussians': {},
};
var UnitKindOptions = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].objectToOptions(UnitKindInfo);
function includesUnitKind(unitKinds, unit) {
    for (var i = 0, il = unitKinds.length; i < il; ++i) {
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isAtomic(unit) && unitKinds[i] === 'atomic')
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isSpheres(unit) && unitKinds[i] === 'spheres')
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isGaussians(unit) && unitKinds[i] === 'gaussians')
            return true;
    }
    return false;
}
//
var MaxCells = 500000000;
/** guard against overly high resolution for the given box size */
function ensureReasonableResolution(box, props) {
    var volume = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_11__[/* Box3D */ "b"].volume(box);
    var approxCells = volume / props.resolution;
    var resolution = approxCells > MaxCells ? volume / MaxCells : props.resolution;
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, props), { resolution: resolution });
}
function getConformation(unit) {
    switch (unit.kind) {
        case 0 /* Atomic */: return unit.model.atomicConformation;
        case 1 /* Spheres */: return unit.model.coarseConformation.spheres;
        case 2 /* Gaussians */: return unit.model.coarseConformation.gaussians;
    }
}
var CommonSurfaceParams = {
    ignoreHydrogens: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Boolean(false, { description: 'Whether or not to include hydrogen atoms in the surface calculation.' }),
    traceOnly: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Boolean(false, { description: 'Whether or not to only use trace atoms in the surface calculation.' }),
    includeParent: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Boolean(false, { description: 'Include elements of the parent structure in surface calculation to get a surface patch of the current structure.' }),
};
var DefaultCommonSurfaceProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].getDefaultValues(CommonSurfaceParams);
var v = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
function squaredDistance(x, y, z, center) {
    return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].squaredDistance(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].set(v, x, y, z), center);
}
/** marks `indices` for filtering/ignoring in `id` when not in `elements` */
function filterId(id, elements, indices) {
    var start = 0;
    var end = elements.length;
    for (var i = 0, il = indices.length; i < il; ++i) {
        var idx = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["SortedArray"].indexOfInRange(elements, indices[i], start, end);
        if (idx === -1) {
            id[i] = -2;
        }
        else {
            id[i] = idx;
            start = idx;
        }
    }
}
function getUnitConformationAndRadius(structure, unit, props) {
    var ignoreHydrogens = props.ignoreHydrogens, traceOnly = props.traceOnly, includeParent = props.includeParent;
    var rootUnit = includeParent ? structure.root.unitMap.get(unit.id) : unit;
    var _a = getConformation(rootUnit), x = _a.x, y = _a.y, z = _a.z;
    var elements = rootUnit.elements;
    var _b = unit.boundary.sphere, center = _b.center, sphereRadius = _b.radius;
    var extraRadius = (2 + 1.5) * 2; // TODO should be twice (the max vdW/sphere radius plus the probe radius)
    var radiusSq = (sphereRadius + extraRadius) * (sphereRadius + extraRadius);
    var indices;
    var id;
    if (ignoreHydrogens || (includeParent && rootUnit !== unit)) {
        var _indices = [];
        var _id = [];
        for (var i = 0, il = elements.length; i < il; ++i) {
            var eI = elements[i];
            if (ignoreHydrogens && isHydrogen(rootUnit, eI))
                continue;
            if (traceOnly && !isTrace(rootUnit, eI))
                continue;
            if (includeParent && squaredDistance(x[eI], y[eI], z[eI], center) > radiusSq)
                continue;
            _indices.push(eI);
            _id.push(i);
        }
        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["SortedArray"].ofSortedArray(_indices);
        id = _id;
    }
    else {
        indices = elements;
        id = Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_8__["fillSerial"])(new Int32Array(indices.length));
    }
    if (includeParent && rootUnit !== unit) {
        filterId(id, unit.elements, indices);
    }
    var position = { indices: indices, x: x, y: y, z: z, id: id };
    var boundary = unit === rootUnit ? unit.boundary : Object(_mol_math_geometry_boundary__WEBPACK_IMPORTED_MODULE_10__[/* getBoundary */ "a"])(position);
    var l = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.create(structure, rootUnit);
    var sizeTheme = Object(_mol_theme_size_physical__WEBPACK_IMPORTED_MODULE_6__[/* PhysicalSizeTheme */ "a"])({}, { scale: 1 });
    var radius = function (index) {
        l.element = index;
        return sizeTheme.size(l);
    };
    return { position: position, boundary: boundary, radius: radius };
}
function getStructureConformationAndRadius(structure, ignoreHydrogens, traceOnly) {
    var l = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.create(structure);
    var sizeTheme = Object(_mol_theme_size_physical__WEBPACK_IMPORTED_MODULE_6__[/* PhysicalSizeTheme */ "a"])({}, { scale: 1 });
    var xs;
    var ys;
    var zs;
    var rs;
    var id;
    if (ignoreHydrogens || traceOnly) {
        var _xs = [];
        var _ys = [];
        var _zs = [];
        var _rs = [];
        var _id = [];
        for (var i = 0, m = 0, il = structure.units.length; i < il; ++i) {
            var unit = structure.units[i];
            var elements = unit.elements;
            var _a = unit.conformation, x = _a.x, y = _a.y, z = _a.z;
            l.unit = unit;
            for (var j = 0, jl = elements.length; j < jl; ++j) {
                var eI = elements[j];
                if (ignoreHydrogens && isHydrogen(unit, eI))
                    continue;
                if (traceOnly && !isTrace(unit, eI))
                    continue;
                _xs.push(x(eI));
                _ys.push(y(eI));
                _zs.push(z(eI));
                l.element = eI;
                _rs.push(sizeTheme.size(l));
                _id.push(m + j);
            }
            m += elements.length;
        }
        xs = _xs, ys = _ys, zs = _zs, rs = _rs;
        id = _id;
    }
    else {
        var elementCount = structure.elementCount;
        var _xs = new Float32Array(elementCount);
        var _ys = new Float32Array(elementCount);
        var _zs = new Float32Array(elementCount);
        var _rs = new Float32Array(elementCount);
        for (var i = 0, m = 0, il = structure.units.length; i < il; ++i) {
            var unit = structure.units[i];
            var elements = unit.elements;
            var _b = unit.conformation, x = _b.x, y = _b.y, z = _b.z;
            l.unit = unit;
            for (var j = 0, jl = elements.length; j < jl; ++j) {
                var eI = elements[j];
                var mj = m + j;
                _xs[mj] = x(eI);
                _ys[mj] = y(eI);
                _zs[mj] = z(eI);
                l.element = eI;
                _rs[mj] = sizeTheme.size(l);
            }
            m += elements.length;
        }
        xs = _xs, ys = _ys, zs = _zs, rs = _rs;
        id = Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_8__["fillSerial"])(new Uint32Array(elementCount));
    }
    var position = { indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_4__["OrderedSet"].ofRange(0, id.length), x: xs, y: ys, z: zs, id: id };
    var radius = function (index) { return rs[index]; };
    return { position: position, radius: radius };
}
var _H = _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_7__["AtomicNumbers"]['H'];
function isHydrogen(unit, element) {
    if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isCoarse(unit))
        return false;
    if (Object(_mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_7__["AtomNumber"])(unit.model.atomicHierarchy.atoms.type_symbol.value(element)) === _H)
        return true;
    return false;
}
function isTrace(unit, element) {
    if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isCoarse(unit))
        return true;
    var atomId = unit.model.atomicHierarchy.atoms.label_atom_id.value(element);
    if (atomId === 'CA' || atomId === 'P')
        return true;
    return false;
}
//# sourceMappingURL=common.js.map

/***/ }),
/* 52 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return OuterSubscriber; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


var OuterSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](OuterSubscriber, _super);
    function OuterSubscriber() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(innerValue);
    };
    OuterSubscriber.prototype.notifyError = function (error, innerSub) {
        this.destination.error(error);
    };
    OuterSubscriber.prototype.notifyComplete = function (innerSub) {
        this.destination.complete();
    };
    return OuterSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));

//# sourceMappingURL=OuterSubscriber.js.map


/***/ }),
/* 53 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export calculateTextureInfo */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createTextureImage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return printTextureImage; });
/* unused harmony export printImageData */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return calculateInvariantBoundingSphere; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return calculateTransformBoundingSphere; });
/* unused harmony export calculateBoundingSphere */
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(126);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function calculateTextureInfo(n, itemSize) {
    var sqN = Math.sqrt(n);
    var width = Math.ceil(sqN);
    width = width + (itemSize - (width % itemSize)) % itemSize;
    var height = width > 0 ? Math.ceil(n / width) : 0;
    return { width: width, height: height, length: width * height * itemSize };
}
function createTextureImage(n, itemSize, arrayCtor, array) {
    var _a = calculateTextureInfo(n, itemSize), length = _a.length, width = _a.width, height = _a.height;
    array = array && array.length >= length ? array : new arrayCtor(length);
    return { array: array, width: width, height: height };
}
function printTextureImage(textureImage, scale) {
    if (scale === void 0) { scale = 1; }
    var array = textureImage.array, width = textureImage.width, height = textureImage.height;
    var itemSize = array.length / (width * height);
    var data = new Uint8ClampedArray(width * height * 4);
    if (itemSize === 1) {
        for (var y = 0; y < height; ++y) {
            for (var x = 0; x < width; ++x) {
                data[(y * width + x) * 4 + 3] = array[y * width + x];
            }
        }
    }
    else if (itemSize === 4) {
        data.set(array);
    }
    else {
        console.warn("itemSize '" + itemSize + "' not supported");
    }
    return printImageData(new ImageData(data, width, height), scale);
}
function printImageData(imageData, scale, pixelated) {
    if (scale === void 0) { scale = 1; }
    if (pixelated === void 0) { pixelated = false; }
    var canvas = document.createElement('canvas');
    canvas.width = imageData.width;
    canvas.height = imageData.height;
    var ctx = canvas.getContext('2d');
    if (!ctx)
        throw new Error('Could not create canvas 2d context');
    ctx.putImageData(imageData, 0, 0);
    canvas.toBlob(function (imgBlob) {
        var objectURL = window.URL.createObjectURL(imgBlob);
        var img = document.createElement('img');
        img.src = objectURL;
        img.style.width = imageData.width * scale + 'px';
        img.style.height = imageData.height * scale + 'px';
        if (pixelated) {
            // not supported in Firefox and IE
            img.style.imageRendering = 'pixelated';
        }
        img.style.position = 'absolute';
        img.style.top = '0px';
        img.style.left = '0px';
        img.style.border = 'solid grey';
        document.body.appendChild(img);
    }, 'image/png');
}
//
var v = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].zero();
var boundaryHelperCoarse = new _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_2__[/* BoundaryHelper */ "a"]('14');
var boundaryHelperFine = new _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_2__[/* BoundaryHelper */ "a"]('98');
function getHelper(count) {
    return count > 500000 ? boundaryHelperCoarse : boundaryHelperFine;
}
function calculateInvariantBoundingSphere(position, positionCount, stepFactor) {
    var step = stepFactor * 3;
    var boundaryHelper = getHelper(positionCount);
    boundaryHelper.reset();
    for (var i = 0, _i = positionCount * 3; i < _i; i += step) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].fromArray(v, position, i);
        boundaryHelper.includePosition(v);
    }
    boundaryHelper.finishedIncludeStep();
    for (var i = 0, _i = positionCount * 3; i < _i; i += step) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].fromArray(v, position, i);
        boundaryHelper.radiusPosition(v);
    }
    var sphere = boundaryHelper.getSphere();
    if (positionCount <= 98) {
        var extrema = [];
        for (var i = 0, _i = positionCount * 3; i < _i; i += step) {
            extrema.push(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].fromArray(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), position, i));
        }
        _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__[/* Sphere3D */ "g"].setExtrema(sphere, extrema);
    }
    return sphere;
}
function calculateTransformBoundingSphere(invariantBoundingSphere, transform, transformCount) {
    var boundaryHelper = getHelper(transformCount);
    boundaryHelper.reset();
    var center = invariantBoundingSphere.center, radius = invariantBoundingSphere.radius, extrema = invariantBoundingSphere.extrema;
    // only use extrema if there are not too many transforms
    if (extrema && transformCount < 50) {
        for (var i = 0, _i = transformCount; i < _i; ++i) {
            for (var _a = 0, extrema_1 = extrema; _a < extrema_1.length; _a++) {
                var e = extrema_1[_a];
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4Offset(v, e, transform, 0, 0, i * 16);
                boundaryHelper.includePosition(v);
            }
        }
        boundaryHelper.finishedIncludeStep();
        for (var i = 0, _i = transformCount; i < _i; ++i) {
            for (var _b = 0, extrema_2 = extrema; _b < extrema_2.length; _b++) {
                var e = extrema_2[_b];
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4Offset(v, e, transform, 0, 0, i * 16);
                boundaryHelper.radiusPosition(v);
            }
        }
    }
    else {
        for (var i = 0, _i = transformCount; i < _i; ++i) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4Offset(v, center, transform, 0, 0, i * 16);
            boundaryHelper.includePositionRadius(v, radius);
        }
        boundaryHelper.finishedIncludeStep();
        for (var i = 0, _i = transformCount; i < _i; ++i) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4Offset(v, center, transform, 0, 0, i * 16);
            boundaryHelper.radiusPositionRadius(v, radius);
        }
    }
    return boundaryHelper.getSphere();
}
function calculateBoundingSphere(position, positionCount, transform, transformCount, padding, stepFactor) {
    if (padding === void 0) { padding = 0; }
    if (stepFactor === void 0) { stepFactor = 1; }
    var invariantBoundingSphere = calculateInvariantBoundingSphere(position, positionCount, stepFactor);
    var boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, transform, transformCount);
    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__[/* Sphere3D */ "g"].expand(boundingSphere, boundingSphere, padding);
    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__[/* Sphere3D */ "g"].expand(invariantBoundingSphere, invariantBoundingSphere, padding);
    return { boundingSphere: boundingSphere, invariantBoundingSphere: invariantBoundingSphere };
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 54 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StructureRepresentationStateBuilder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StructureRepresentationProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40);
/* harmony import */ var _complex_representation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(222);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _complex_representation__WEBPACK_IMPORTED_MODULE_2__["a"]; });

/* harmony import */ var _complex_visual__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(110);
/* harmony import */ var _units_representation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(104);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "d", function() { return _units_representation__WEBPACK_IMPORTED_MODULE_4__["a"]; });

/* harmony import */ var _units_visual__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(48);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var StructureRepresentationStateBuilder = {
    create: function () {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _representation__WEBPACK_IMPORTED_MODULE_1__[/* Representation */ "a"].createState()), { unitTransforms: null, unitTransformsVersion: -1 });
    },
    update: function (state, update) {
        _representation__WEBPACK_IMPORTED_MODULE_1__[/* Representation */ "a"].updateState(state, update);
        if (update.unitTransforms !== undefined)
            state.unitTransforms = update.unitTransforms;
    }
};
function StructureRepresentationProvider(p) { return p; }
//




//# sourceMappingURL=representation.js.map

/***/ }),
/* 55 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ HashSet; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ LinkedList; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ UniqueArray; });

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/generic/hash-set.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var HashSetImpl = /** @class */ (function () {
    function HashSetImpl(getHash, areEqual) {
        this.getHash = getHash;
        this.areEqual = areEqual;
        this.size = 0;
        this.byHash = new Map();
    }
    HashSetImpl.prototype.add = function (a) {
        var hash = this.getHash(a);
        if (this.byHash.has(hash)) {
            var xs = this.byHash.get(hash);
            for (var i = 0, _i = xs.length; i < _i; i++) {
                if (this.areEqual(a, xs[i]))
                    return false;
            }
            xs[xs.length] = a;
            this.size++;
            return true;
        }
        else {
            this.byHash.set(hash, [a]);
            this.size++;
            return true;
        }
    };
    HashSetImpl.prototype.has = function (v) {
        var hash = this.getHash(v);
        if (!this.byHash.has(hash))
            return false;
        var xs = this.byHash.get(hash);
        for (var i = 0, _i = xs.length; i < _i; i++) {
            if (this.areEqual(v, xs[i]))
                return true;
        }
        return false;
    };
    return HashSetImpl;
}());
// TODO: add implementations with multilevel hashing support?
function HashSet(getHash, areEqual) {
    return new HashSetImpl(getHash, areEqual);
}
//# sourceMappingURL=hash-set.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/generic/linked-list.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function LinkedList() {
    return new LinkedListImpl();
}
function createListNode(value) {
    return { previous: null, next: null, inList: true, value: value };
}
var LinkedListImpl = /** @class */ (function () {
    function LinkedListImpl() {
        this.count = 0;
        this.first = null;
        this.last = null;
    }
    LinkedListImpl.prototype.addFirst = function (value) {
        var node = createListNode(value);
        node.inList = true;
        if (this.first)
            this.first.previous = node;
        node.next = this.first;
        this.first = node;
        this.count++;
        if (!this.last)
            this.last = node;
        return node;
    };
    LinkedListImpl.prototype.addLast = function (value) {
        var node = createListNode(value);
        if (this.last !== null) {
            this.last.next = node;
        }
        node.previous = this.last;
        this.last = node;
        if (this.first === null) {
            this.first = node;
        }
        node.inList = true;
        this.count++;
        return node;
    };
    LinkedListImpl.prototype.removeFirst = function () {
        var fst = this.first;
        if (fst) {
            this.remove(fst);
            return fst.value;
        }
        return void 0;
    };
    LinkedListImpl.prototype.removeLast = function () {
        var last = this.last;
        if (last) {
            this.remove(last);
            return last.value;
        }
        return void 0;
    };
    LinkedListImpl.prototype.remove = function (node) {
        if (!node.inList)
            return;
        node.inList = false;
        if (node.previous !== null) {
            node.previous.next = node.next;
        }
        else if ( /* first == item*/node.previous === null) {
            this.first = node.next;
        }
        if (node.next !== null) {
            node.next.previous = node.previous;
        }
        else if ( /* last == item*/node.next === null) {
            this.last = node.previous;
        }
        node.next = null;
        node.previous = null;
        this.count--;
    };
    LinkedListImpl.prototype.find = function (value) {
        var current = this.first;
        while (current !== null) {
            if (current.value === value)
                return current;
            current = current.next;
        }
        return void 0;
    };
    return LinkedListImpl;
}());

//# sourceMappingURL=linked-list.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/generic/unique-array.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var UniqueArray;
(function (UniqueArray) {
    function create() {
        return { keys: new Set(), array: [] };
    }
    UniqueArray.create = create;
    function add(_a, key, value) {
        var keys = _a.keys, array = _a.array;
        if (keys.has(key))
            return false;
        keys.add(key);
        array[array.length] = value;
        return true;
    }
    UniqueArray.add = add;
    function has(_a, key) {
        var keys = _a.keys;
        return keys.has(key);
    }
    UniqueArray.has = has;
})(UniqueArray || (UniqueArray = {}));

//# sourceMappingURL=unique-array.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/generic.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



//# sourceMappingURL=generic.js.map

/***/ }),
/* 56 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ActionMenu; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
/* harmony import */ var _icons__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var ActionMenu = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ActionMenu, _super);
    function ActionMenu() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.hide = function () { return _this.props.onSelect(void 0); };
        return _this;
    }
    ActionMenu.prototype.render = function () {
        var cmd = this.props;
        var section = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Section, { items: cmd.items, onSelect: cmd.onSelect, current: cmd.current, multiselect: this.props.multiselect, noOffset: this.props.noOffset, noAccent: this.props.noAccent });
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: "msp-action-menu-options" + (cmd.header ? '' : ' msp-action-menu-options-no-header') },
            cmd.header && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["ControlGroup"], { header: cmd.header, title: cmd.title, initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.hide, topRightIcon: _icons__WEBPACK_IMPORTED_MODULE_3__["CloseSvg"] }, section),
            !cmd.header && section);
    };
    return ActionMenu;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

(function (ActionMenu) {
    function Header(label, options) {
        return options ? Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ kind: 'header', label: label }, options) : { kind: 'header', label: label };
    }
    ActionMenu.Header = Header;
    function Item(label, value, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ kind: 'item', label: label, value: value }, options);
    }
    ActionMenu.Item = Item;
    function createItems(xs, params) {
        var _a = params || {}, label = _a.label, value = _a.value, category = _a.category, selected = _a.selected, icon = _a.icon, addOn = _a.addOn, description = _a.description;
        var cats = void 0;
        var items = [];
        for (var i = 0; i < xs.length; i++) {
            var x = xs[i];
            if ((params === null || params === void 0 ? void 0 : params.filter) && !params.filter(x))
                continue;
            var catName = category === null || category === void 0 ? void 0 : category(x);
            var l = label ? label(x) : '' + x;
            var v = value ? value(x) : x;
            var d = description ? description(x) :
                typeof x === 'string' ? x : undefined;
            var cat = void 0;
            if (!!catName) {
                if (!cats)
                    cats = new Map();
                cat = cats.get(catName);
                if (!cat) {
                    cat = [ActionMenu.Header(catName, { description: catName })];
                    cats.set(catName, cat);
                    items.push(cat);
                }
            }
            else {
                cat = items;
            }
            var ao = addOn === null || addOn === void 0 ? void 0 : addOn(x);
            cat.push({ kind: 'item', label: l, value: v, icon: icon ? icon(x) : void 0, selected: selected ? selected(x) : void 0, addOn: ao, description: d });
        }
        return items;
    }
    ActionMenu.createItems = createItems;
    var _selectOptions = { value: function (o) { return o[0]; }, label: function (o) { return o[1]; }, category: function (o) { return o[2]; } };
    function createItemsFromSelectOptions(options, params) {
        return createItems(options, params ? Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _selectOptions), params) : _selectOptions);
    }
    ActionMenu.createItemsFromSelectOptions = createItemsFromSelectOptions;
    function hasSelectedItem(items) {
        if (isHeader(items))
            return false;
        if (isItem(items))
            return !!items.selected;
        for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
            var s = items_1[_i];
            var found = hasSelectedItem(s);
            if (found)
                return true;
        }
        return false;
    }
    ActionMenu.hasSelectedItem = hasSelectedItem;
    function findItem(items, value) {
        if (isHeader(items))
            return;
        if (isItem(items))
            return items.value === value ? items : void 0;
        for (var _i = 0, items_2 = items; _i < items_2.length; _i++) {
            var s = items_2[_i];
            var found = findItem(s, value);
            if (found)
                return found;
        }
    }
    ActionMenu.findItem = findItem;
    function getFirstItem(items) {
        if (isHeader(items))
            return;
        if (isItem(items))
            return items;
        for (var _i = 0, items_3 = items; _i < items_3.length; _i++) {
            var s = items_3[_i];
            var found = getFirstItem(s);
            if (found)
                return found;
        }
    }
    ActionMenu.getFirstItem = getFirstItem;
    // export type SelectProps<T> = {
    //     items: Items,
    //     onSelect: (item: Item) => void,
    //     disabled?: boolean,
    //     label?: string,
    //     current?: Item,
    //     style?: React.CSSProperties
    // }
    // export class Select<T> extends React.PureComponent<SelectProps<T>, { isExpanded: boolean }> {
    //     state = { isExpanded: false };
    //     toggleExpanded = () => this.setState({ isExpanded: !this.state.isExpanded })
    //     onSelect: OnSelect = (item) => {
    //         this.setState({ isExpanded: false });
    //         if (!item) return;
    //         this.onSelect(item);
    //     }
    //     render() {
    //         const current = this.props.current;
    //         const label = this.props.label || current?.label || '';
    //         return <div className='msp-action-menu-select' style={this.props.style}>
    //             <ToggleButton disabled={this.props.disabled} style={{ textAlign: 'left' }} className='msp-no-overflow'
    //                 label={label} title={label as string} toggle={this.toggleExpanded} isSelected={this.state.isExpanded} />
    //             {this.state.isExpanded && <ActionMenu items={this.props.items} current={this.props.current} onSelect={this.onSelect} />}
    //         </div>
    //     }
    // }
})(ActionMenu || (ActionMenu = {}));
var Section = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Section, _super);
    function Section() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = Section.createState(_this.props);
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        _this.selectAll = function () {
            var items = collectItems(_this.props.items, []).filter(function (i) { return !i.selected; });
            _this.props.onSelect(items);
        };
        _this.selectNone = function () {
            var items = collectItems(_this.props.items, []).filter(function (i) { return !!i.selected; });
            _this.props.onSelect(items);
        };
        return _this;
    }
    Section.createState = function (props, isExpanded) {
        var header = isItems(props.items) && isHeader(props.items[0]) ? props.items[0] : void 0;
        var hasCurrent = (header === null || header === void 0 ? void 0 : header.isIndependent) ? false
            : props.multiselect
                ? ActionMenu.hasSelectedItem(props.items)
                : (!!props.current && !!ActionMenu.findItem(props.items, props.current.value)) || ActionMenu.hasSelectedItem(props.items);
        return {
            header: header,
            hasCurrent: hasCurrent,
            isExpanded: hasCurrent || (isExpanded !== null && isExpanded !== void 0 ? isExpanded : !!(header === null || header === void 0 ? void 0 : header.initiallyExpanded))
        };
    };
    Section.prototype.componentDidUpdate = function (prevProps) {
        if (this.props.items !== prevProps.items || this.props.current !== prevProps.current) {
            // keep previously expanded section if the header label is the same
            var isExpanded = (isItems(this.props.items) && isItems(prevProps.items) &&
                isHeader(this.props.items[0]) && isHeader(prevProps.items[0]) &&
                this.props.items[0].label === prevProps.items[0].label) ? this.state.isExpanded : undefined;
            this.setState(Section.createState(this.props, isExpanded));
        }
    };
    Object.defineProperty(Section.prototype, "multiselectHeader", {
        get: function () {
            var _a = this.state, header = _a.header, hasCurrent = _a.hasCurrent;
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row msp-control-group-header' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { icon: this.state.isExpanded ? _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowDropDownSvg"] : _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowRightSvg"], flex: true, noOverflow: true, onClick: this.toggleExpanded, title: "Click to " + (this.state.isExpanded ? 'collapse' : 'expand') + "." + ((header === null || header === void 0 ? void 0 : header.description) ? " " + (header === null || header === void 0 ? void 0 : header.description) : '') }, hasCurrent ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, header === null || header === void 0 ? void 0 : header.label) : header === null || header === void 0 ? void 0 : header.label),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { icon: _icons__WEBPACK_IMPORTED_MODULE_3__["CheckSvg"], flex: true, onClick: this.selectAll, style: { flex: '0 0 50px', textAlign: 'right' } }, "All"),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { icon: _icons__WEBPACK_IMPORTED_MODULE_3__["CloseSvg"], flex: true, onClick: this.selectNone, style: { flex: '0 0 50px', textAlign: 'right' } }, "None"));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Section.prototype, "basicHeader", {
        get: function () {
            var _a = this.state, header = _a.header, hasCurrent = _a.hasCurrent;
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-header', style: { marginTop: '1px' } },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { noOverflow: true, icon: this.state.isExpanded ? _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowDropDownSvg"] : _icons__WEBPACK_IMPORTED_MODULE_3__["ArrowRightSvg"], onClick: this.toggleExpanded, title: "Click to " + (this.state.isExpanded ? 'collapse' : 'expand') + ". " + ((header === null || header === void 0 ? void 0 : header.description) ? header === null || header === void 0 ? void 0 : header.description : '') }, hasCurrent ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, header === null || header === void 0 ? void 0 : header.label) : header === null || header === void 0 ? void 0 : header.label));
        },
        enumerable: false,
        configurable: true
    });
    Section.prototype.render = function () {
        var _this = this;
        var _a = this.props, items = _a.items, onSelect = _a.onSelect, current = _a.current;
        if (isHeader(items))
            return null;
        if (isItem(items))
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Action, { item: items, onSelect: onSelect, current: current, multiselect: this.props.multiselect });
        var header = this.state.header;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            header && (this.props.multiselect && this.state.isExpanded ? this.multiselectHeader : this.basicHeader),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: this.props.noOffset ? void 0 : this.props.noAccent ? 'msp-control-offset' : 'msp-accent-offset' }, (!header || this.state.isExpanded) && items.map(function (x, i) {
                if (isHeader(x))
                    return null;
                if (isItem(x))
                    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Action, { key: i, item: x, onSelect: onSelect, current: current, multiselect: _this.props.multiselect });
                return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Section, { key: i, items: x, onSelect: onSelect, current: current, multiselect: _this.props.multiselect, noAccent: true });
            })));
    };
    return Section;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));
var Action = function (_a) {
    var item = _a.item, onSelect = _a.onSelect, current = _a.current, multiselect = _a.multiselect;
    var isCurrent = current === item;
    var style = item.addOn ? { position: 'relative' } : void 0;
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["Button"], { icon: item.icon, noOverflow: true, className: 'msp-action-menu-button', onClick: function (e) { return onSelect(multiselect ? [item] : item, e); }, disabled: item.disabled, style: style, title: item.description },
        isCurrent || item.selected ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, item.label) : item.label,
        item.addOn);
};
function isItems(x) {
    return !!x && Array.isArray(x);
}
function isItem(x) {
    var v = x;
    return v && v.kind === 'item';
}
function isHeader(x) {
    var v = x;
    return v && v.kind === 'header';
}
function collectItems(items, target) {
    if (isHeader(items))
        return target;
    if (isItem(items)) {
        target.push(items);
        return target;
    }
    for (var _i = 0, items_4 = items; _i < items_4.length; _i++) {
        var i = items_4[_i];
        collectItems(i, target);
    }
    return target;
}
//# sourceMappingURL=action-menu.js.map

/***/ }),
/* 57 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mmCIF_Schema; });
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Code-generated 'mmCIF' schema file. Dictionary versions: mmCIF 5.326, IHM 1.09, CARB draft.
 *
 * @author molstar/ciftools package
 */

var Schema = _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].Schema;
var str = Schema.str;
var int = Schema.int;
var float = Schema.float;
var coord = Schema.coord;
var Aliased = Schema.Aliased;
var Matrix = Schema.Matrix;
var Vector = Schema.Vector;
var List = Schema.List;
var mmCIF_Schema = {
    /**
     * Data items in the ATOM_SITE category record details about
     * the atom sites in a macromolecular crystal structure, such as
     * the positional coordinates, atomic displacement parameters,
     * magnetic moments and directions.
     *
     * The data items for describing anisotropic atomic
     * displacement factors are only used if the corresponding items
     * are not given in the ATOM_SITE_ANISOTROP category.
     */
    atom_site: {
        /**
         * An alternative identifier for _atom_site.label_asym_id that
         * may be provided by an author in order to match the identification
         * used in the publication that describes the structure.
         */
        auth_asym_id: str,
        /**
         * An alternative identifier for _atom_site.label_atom_id that
         * may be provided by an author in order to match the identification
         * used in the publication that describes the structure.
         */
        auth_atom_id: str,
        /**
         * An alternative identifier for _atom_site.label_comp_id that
         * may be provided by an author in order to match the identification
         * used in the publication that describes the structure.
         */
        auth_comp_id: str,
        /**
         * An alternative identifier for _atom_site.label_seq_id that
         * may be provided by an author in order to match the identification
         * used in the publication that describes the structure.
         *
         * Note that this is not necessarily a number, that the values do
         * not have to be positive, and that the value does not have to
         * correspond to the value of _atom_site.label_seq_id. The value
         * of _atom_site.label_seq_id is required to be a sequential list
         * of positive integers.
         *
         * The author may assign values to _atom_site.auth_seq_id in any
         * desired way. For instance, the values may be used to relate
         * this structure to a numbering scheme in a homologous structure,
         * including sequence gaps or insertion codes. Alternatively, a
         * scheme may be used for a truncated polymer that maintains the
         * numbering scheme of the full length polymer. In all cases, the
         * scheme used here must match the scheme used in the publication
         * that describes the structure.
         */
        auth_seq_id: int,
        /**
         * Isotropic atomic displacement parameter, or equivalent isotropic
         * atomic displacement parameter, B~eq~, calculated from the
         * anisotropic displacement parameters.
         *
         * B~eq~ = (1/3) sum~i~[sum~j~(B^ij^ A~i~ A~j~ a*~i~ a*~j~)]
         *
         * A     = the real space cell lengths
         * a*    = the reciprocal space cell lengths
         * B^ij^ = 8 pi^2^ U^ij^
         *
         * Ref: Fischer, R. X. & Tillmanns, E. (1988). Acta Cryst. C44,
         * 775-776.
         *
         * The IUCr Commission on Nomenclature recommends against the use
         * of B for reporting atomic displacement parameters. U, being
         * directly proportional to B, is preferred.
         *
         * Note -
         *
         * The particular type of ADP stored in this item is qualified
         * by item _refine.pdbx_adp_type.
         */
        B_iso_or_equiv: float,
        /**
         * The x atom-site coordinate in angstroms specified according to
         * a set of orthogonal Cartesian axes related to the cell axes as
         * specified by the description given in
         * _atom_sites.Cartn_transform_axes.
         */
        Cartn_x: coord,
        /**
         * The y atom-site coordinate in angstroms specified according to
         * a set of orthogonal Cartesian axes related to the cell axes as
         * specified by the description given in
         * _atom_sites.Cartn_transform_axes.
         */
        Cartn_y: coord,
        /**
         * The z atom-site coordinate in angstroms specified according to
         * a set of orthogonal Cartesian axes related to the cell axes as
         * specified by the description given in
         * _atom_sites.Cartn_transform_axes.
         */
        Cartn_z: coord,
        /**
         * The group of atoms to which the atom site belongs. This data
         * item is provided for compatibility with the original Protein
         * Data Bank format, and only for that purpose.
         */
        group_PDB: Aliased(str),
        /**
         * The value of _atom_site.id must uniquely identify a record in the
         * ATOM_SITE list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         *
         * This data item was introduced to provide compatibility between
         * small-molecule and macromolecular CIFs. In a small-molecule
         * CIF, _atom_site_label is the identifier for the atom. In a
         * macromolecular CIF, the atom identifier is the aggregate of
         * _atom_site.label_alt_id, _atom_site.label_asym_id,
         * _atom_site.label_atom_id, _atom_site.label_comp_id and
         * _atom_site.label_seq_id. For the two types of files to be
         * compatible, a formal identifier for the category had to be
         * introduced that was independent of the different modes of
         * identifying the atoms. For compatibility with older CIFs,
         * _atom_site_label is aliased to _atom_site.id.
         */
        id: int,
        /**
         * A place holder to indicate alternate conformation. The alternate conformation
         * can be an entire polymer chain, or several residues or
         * partial residue (several atoms within one residue). If
         * an atom is provided in more than one position, then a
         * non-blank alternate location indicator must be used for
         * each of the atomic positions.
         */
        label_alt_id: str,
        /**
         * A component of the identifier for this atom site.
         * For further details, see the definition of the STRUCT_ASYM
         * category.
         *
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        label_asym_id: str,
        /**
         * A component of the identifier for this atom site.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        label_atom_id: str,
        /**
         * A component of the identifier for this atom site.
         *
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        label_comp_id: str,
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        label_entity_id: str,
        /**
         * This data item is a pointer to _entity_poly_seq.num in the
         * ENTITY_POLY_SEQ category.
         */
        label_seq_id: int,
        /**
         * The fraction of the atom type present at this site.
         * The sum of the occupancies of all the atom types at this site
         * may not exceed 1.0 unless it is a dummy site.
         */
        occupancy: float,
        /**
         * This data item is a pointer to _atom_type.symbol in the
         * ATOM_TYPE category.
         */
        type_symbol: str,
        /**
         * PDB insertion code.
         */
        pdbx_PDB_ins_code: str,
        /**
         * PDB model number.
         */
        pdbx_PDB_model_num: int,
        /**
         * The net integer charge assigned to this atom. This is the
         * formal charge assignment normally found in chemical diagrams.
         */
        pdbx_formal_charge: int,
        /**
         * The model id corresponding to the atom site.
         * This data item is a pointer to _ihm_model_list.model_id
         * in the IHM_MODEL_LIST category.
         */
        ihm_model_id: int,
    },
    /**
     * Data items in the ATOM_SITE_ANISOTROP category record details
     * about anisotropic displacement parameters.
     * If the ATOM_SITE_ANISOTROP category is used for storing these
     * data, the corresponding ATOM_SITE data items are not used.
     */
    atom_site_anisotrop: {
        /**
         * This data item is a pointer to _atom_site.id in the ATOM_SITE
         * category.
         */
        id: int,
        /**
         * This data item is a pointer to _atom_type.symbol in the
         * ATOM_TYPE category.
         */
        type_symbol: str,
        /**
         * The elements of the standard anisotropic atomic
         * displacement matrix U, which appears in the structure-factor
         * term as:
         *
         * T = exp{-2 pi^2^ sum~i~[sum~j~(U^ij^ h~i~ h~j~ a*~i~ a*~j~)]}
         *
         * h  = the Miller indices
         * a* = the reciprocal space cell lengths
         *
         * These matrix elements may appear with atomic coordinates
         * in the ATOM_SITE category, or they may appear in the separate
         * ATOM_SITE_ANISOTROP category, but they may not appear in both
         * places. Similarly, anisotropic displacements may appear as
         * either B's or U's, but not as both.
         *
         * The unique elements of the real symmetric matrix are
         * entered by row.
         */
        U: Matrix(3, 3),
        /**
         * The standard uncertainty (estimated standard deviation)
         * of _atom_site_anisotrop.U.
         */
        U_esd: Matrix(3, 3),
        /**
         * Pointer to _atom_site.auth_seq_id
         */
        pdbx_auth_seq_id: str,
        /**
         * Pointer to _atom_site.auth_asym_id
         */
        pdbx_auth_asym_id: str,
        /**
         * Pointer to _atom_site.auth_atom_id
         */
        pdbx_auth_atom_id: str,
        /**
         * Pointer to _atom_site.auth_comp_id
         */
        pdbx_auth_comp_id: str,
        /**
         * Pointer to _atom_site.label_seq_id
         */
        pdbx_label_seq_id: int,
        /**
         * Pointer to _atom_site.label_alt_id.
         */
        pdbx_label_alt_id: str,
        /**
         * Pointer to _atom_site.label_asym_id
         */
        pdbx_label_asym_id: str,
        /**
         * Pointer to _atom_site.label_atom_id
         */
        pdbx_label_atom_id: str,
        /**
         * Pointer to _atom_site.label_comp_id
         */
        pdbx_label_comp_id: str,
        /**
         * Pointer to _atom_site.pdbx_PDB_ins_code
         */
        pdbx_PDB_ins_code: str,
    },
    /**
     * Data items in the ATOM_SITES category record details about
     * the crystallographic cell and cell transformations, which are
     * common to all atom sites.
     */
    atom_sites: {
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * The elements of the 3x3 matrix used to transform Cartesian
         * coordinates in the ATOM_SITE category to fractional coordinates
         * in the same category. The axial alignments of this
         * transformation are described in _atom_sites.Cartn_transform_axes.
         * The 3x1 translation is defined in
         * _atom_sites.fract_transf_vector[].
         *
         * |x'|               |11 12 13| |x|              |1|
         * |y'|~fractional~ = |21 22 23| |y|~Cartesian~ + |2|
         * |z'|               |31 32 33| |z|              |3|
         */
        fract_transf_matrix: Matrix(3, 3),
        /**
         * The elements of the three-element vector used to transform
         * Cartesian coordinates in the ATOM_SITE category to fractional
         * coordinates in the same category. The axial alignments of this
         * transformation are described in _atom_sites.Cartn_transform_axes.
         * The 3x3 rotation is defined in
         * _atom_sites.fract_transf_matrix[][].
         *
         * |x'|               |11 12 13| |x|              |1|
         * |y'|~fractional~ = |21 22 23| |y|~Cartesian~ + |2|
         * |z'|               |31 32 33| |z|              |3|
         */
        fract_transf_vector: Vector(3),
    },
    /**
     * Data items in the AUDIT_AUTHOR category record details about
     * the author(s) of the data block.
     */
    audit_author: {
        /**
         * The name of an author of this data block. If there are multiple
         * authors, _audit_author.name is looped with _audit_author.address.
         * The family name(s), followed by a comma and including any
         * dynastic components, precedes the first name(s) or initial(s).
         */
        name: str,
        /**
         * This data item defines the order of the author's name in the
         * list of audit authors.
         */
        pdbx_ordinal: int,
        /**
         * The Open Researcher and Contributor ID (ORCID).
         */
        identifier_ORCID: str,
    },
    /**
     * Data items in the AUDIT_CONFORM category describe the
     * dictionary versions against which the data names appearing in
     * the current data block are conformant.
     */
    audit_conform: {
        /**
         * A file name or uniform resource locator (URL) for the
         * dictionary to which the current data block conforms.
         */
        dict_location: str,
        /**
         * The string identifying the highest-level dictionary defining
         * data names used in this file.
         */
        dict_name: str,
        /**
         * The version number of the dictionary to which the current
         * data block conforms.
         */
        dict_version: str,
    },
    /**
     * Data items in the CELL category record details about the
     * crystallographic cell parameters.
     */
    cell: {
        /**
         * Unit-cell angle alpha of the reported structure in degrees.
         */
        angle_alpha: float,
        /**
         * Unit-cell angle beta of the reported structure in degrees.
         */
        angle_beta: float,
        /**
         * Unit-cell angle gamma of the reported structure in degrees.
         */
        angle_gamma: float,
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * Unit-cell length a corresponding to the structure reported in
         * angstroms.
         */
        length_a: float,
        /**
         * Unit-cell length b corresponding to the structure reported in
         * angstroms.
         */
        length_b: float,
        /**
         * Unit-cell length c corresponding to the structure reported in
         * angstroms.
         */
        length_c: float,
        /**
         * The number of the polymeric chains in a unit cell. In the case
         * of heteropolymers, Z is the number of occurrences of the most
         * populous chain.
         *
         * This data item is provided for compatibility with the original
         * Protein Data Bank format, and only for that purpose.
         */
        Z_PDB: int,
        /**
         * To further identify unique axis if necessary.  E.g., P 21 with
         * an unique C axis will have 'C' in this field.
         */
        pdbx_unique_axis: str,
    },
    /**
     * Data items in the CHEM_COMP category give details about each
     * of the chemical components from which the relevant chemical
     * structures can be constructed, such as name, mass or charge.
     *
     * The related categories CHEM_COMP_ATOM, CHEM_COMP_BOND,
     * CHEM_COMP_ANGLE etc. describe the detailed geometry of these
     * chemical components.
     */
    chem_comp: {
        /**
         * The formula for the chemical component. Formulae are written
         * according to the following rules:
         *
         * (1) Only recognized element symbols may be used.
         *
         * (2) Each element symbol is followed by a 'count' number. A count
         * of '1' may be omitted.
         *
         * (3) A space or parenthesis must separate each cluster of
         * (element symbol + count), but in general parentheses are
         * not used.
         *
         * (4) The order of elements depends on whether carbon is
         * present or not. If carbon is present, the order should be:
         * C, then H, then the other elements in alphabetical order
         * of their symbol. If carbon is not present, the elements
         * are listed purely in alphabetic order of their symbol. This
         * is the 'Hill' system used by Chemical Abstracts.
         */
        formula: str,
        /**
         * Formula mass in daltons of the chemical component.
         */
        formula_weight: float,
        /**
         * The value of _chem_comp.id must uniquely identify each item in
         * the CHEM_COMP list.
         *
         * For protein polymer entities, this is the three-letter code for
         * the amino acid.
         *
         * For nucleic acid polymer entities, this is the one-letter code
         * for the base.
         */
        id: str,
        /**
         * 'yes' indicates that this is a 'standard' monomer, 'no'
         * indicates that it is 'nonstandard'. Nonstandard monomers
         * should be described in more detail using the
         * _chem_comp.mon_nstd_parent, _chem_comp.mon_nstd_class and
         * _chem_comp.mon_nstd_details data items.
         */
        mon_nstd_flag: Aliased(str),
        /**
         * The full name of the component.
         */
        name: str,
        /**
         * For standard polymer components, the type of the monomer.
         * Note that monomers that will form polymers are of three types:
         * linking monomers, monomers with some type of N-terminal (or 5')
         * cap and monomers with some type of C-terminal (or 3') cap.
         */
        type: Aliased(str),
        /**
         * Synonym list for the component.
         */
        pdbx_synonyms: List(';', function (x) { return x; }),
    },
    /**
     * Data items in the CHEM_COMP_BOND category record details about
     * the bonds between atoms in a chemical component. Target values
     * may be specified as bond orders, as a distance between the two
     * atoms, or both.
     */
    chem_comp_bond: {
        /**
         * The ID of the first of the two atoms that define the bond.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_1: str,
        /**
         * The ID of the second of the two atoms that define the bond.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_2: str,
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: str,
        /**
         * The value that should be taken as the target for the chemical
         * bond associated with the specified atoms, expressed as a bond
         * order.
         */
        value_order: Aliased(str),
        /**
         * Ordinal index for the component bond list.
         */
        pdbx_ordinal: int,
        /**
         * Stereochemical configuration across a double bond.
         */
        pdbx_stereo_config: Aliased(str),
        /**
         * A flag indicating an aromatic bond.
         */
        pdbx_aromatic_flag: Aliased(str),
    },
    /**
     * Data items in the CITATION category record details about the
     * literature cited as being relevant to the contents of the data
     * block.
     */
    citation: {
        /**
         * The name of the publisher of the citation; relevant
         * for books or book chapters.
         */
        book_publisher: str,
        /**
         * The country/region of publication; relevant for books
         * and book chapters.
         */
        country: str,
        /**
         * The value of _citation.id must uniquely identify a record in the
         * CITATION list.
         *
         * The _citation.id 'primary' should be used to indicate the
         * citation that the author(s) consider to be the most pertinent to
         * the contents of the data block.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * Abbreviated name of the cited journal as given in the
         * Chemical Abstracts Service Source Index.
         */
        journal_abbrev: str,
        /**
         * The American Society for Testing and Materials (ASTM) code
         * assigned to the journal cited (also referred to as the CODEN
         * designator of the Chemical Abstracts Service); relevant for
         * journal articles.
         */
        journal_id_ASTM: str,
        /**
         * The Cambridge Structural Database (CSD) code assigned to the
         * journal cited; relevant for journal articles. This is also the
         * system used at the Protein Data Bank (PDB).
         */
        journal_id_CSD: str,
        /**
         * The International Standard Serial Number (ISSN) code assigned to
         * the journal cited; relevant for journal articles.
         */
        journal_id_ISSN: str,
        /**
         * Volume number of the journal cited; relevant for journal
         * articles.
         */
        journal_volume: str,
        /**
         * The first page of the citation; relevant for journal
         * articles, books and book chapters.
         */
        page_first: str,
        /**
         * The last page of the citation; relevant for journal
         * articles, books and book chapters.
         */
        page_last: str,
        /**
         * The title of the citation; relevant for journal articles, books
         * and book chapters.
         */
        title: str,
        /**
         * The year of the citation; relevant for journal articles, books
         * and book chapters.
         */
        year: int,
        /**
         * Document Object Identifier used by doi.org to uniquely
         * specify bibliographic entry.
         */
        pdbx_database_id_DOI: str,
        /**
         * Ascession number used by PubMed to categorize a specific
         * bibliographic entry.
         */
        pdbx_database_id_PubMed: int,
    },
    /**
     * Data items in the CITATION_AUTHOR category record details
     * about the authors associated with the citations in the
     * CITATION list.
     */
    citation_author: {
        /**
         * This data item is a pointer to _citation.id in the CITATION
         * category.
         */
        citation_id: str,
        /**
         * Name of an author of the citation; relevant for journal
         * articles, books and book chapters.
         *
         * The family name(s), followed by a comma and including any
         * dynastic components, precedes the first name(s) or initial(s).
         */
        name: str,
        /**
         * This data item defines the order of the author's name in the
         * list of authors of a citation.
         */
        ordinal: int,
    },
    /**
     * Data items in the DATABASE_2 category record details about the
     * database identifiers of the data block.
     *
     * These data items are assigned by database managers and should
     * only appear in a data block if they originate from that source.
     *
     * The name of this category, DATABASE_2, arose because the
     * category name DATABASE was already in use in the core CIF
     * dictionary, but was used differently from the way it needed
     * to be used in the mmCIF dictionary. Since CIF data names
     * cannot be changed once they have been adopted, a new category
     * had to be created.
     */
    database_2: {
        /**
         * An abbreviation that identifies the database.
         */
        database_id: Aliased(str),
        /**
         * The code assigned by the database identified in
         * _database_2.database_id.
         */
        database_code: str,
    },
    /**
     * Data items in the ENTITY category record details (such as
     * chemical composition, name and source) about the molecular
     * entities that are present in the crystallographic structure.
     *
     * Items in the various ENTITY subcategories provide a full
     * chemical description of these molecular entities.
     *
     * Entities are of three types:  polymer, non-polymer and water.
     * Note that the water category includes only water;  ordered
     * solvent such as sulfate ion or acetone would be described as
     * individual non-polymer entities.
     *
     * The ENTITY category is specific to macromolecular CIF
     * applications and replaces the function of the CHEMICAL category
     * in the CIF core.
     *
     * It is important to remember that the ENTITY data are not the
     * result of the crystallographic experiment;  those results are
     * represented by the ATOM_SITE data items. ENTITY data items
     * describe the chemistry of the molecules under investigation
     * and can most usefully be thought of as the ideal groups to which
     * the structure is restrained or constrained during refinement.
     *
     * It is also important to remember that entities do not correspond
     * directly to the enumeration of the contents of the asymmetric
     * unit. Entities are described only once, even in those structures
     * that contain multiple observations of an entity. The
     * STRUCT_ASYM data items, which reference the entity list,
     * describe and label the contents of the asymmetric unit.
     */
    entity: {
        /**
         * A description of special aspects of the entity.
         */
        details: str,
        /**
         * Formula mass in daltons of the entity.
         */
        formula_weight: float,
        /**
         * The value of _entity.id must uniquely identify a record in the
         * ENTITY list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * The method by which the sample for the entity was produced.
         * Entities isolated directly from natural sources (tissues, soil
         * samples etc.) are expected to have further information in the
         * ENTITY_SRC_NAT category. Entities isolated from genetically
         * manipulated sources are expected to have further information in
         * the ENTITY_SRC_GEN category.
         */
        src_method: Aliased(str),
        /**
         * Defines the type of the entity.
         *
         * Polymer entities are expected to have corresponding
         * ENTITY_POLY and associated entries.
         *
         * Non-polymer entities are expected to have corresponding
         * CHEM_COMP and associated entries.
         *
         * Water entities are not expected to have corresponding
         * entries in the ENTITY category.
         */
        type: Aliased(str),
        /**
         * A description of the entity.
         *
         * Corresponds to the compound name in the PDB format.
         */
        pdbx_description: List(',', function (x) { return x; }),
        /**
         * A place holder for the number of molecules of the entity in
         * the entry.
         */
        pdbx_number_of_molecules: int,
        /**
         * Details about any entity mutation(s).
         */
        pdbx_mutation: str,
        /**
         * Entity fragment description(s).
         */
        pdbx_fragment: str,
        /**
         * Enzyme Commission (EC) number(s)
         */
        pdbx_ec: List(',', function (x) { return x; }),
    },
    /**
     * Data items in the ENTITY_POLY category record details about the
     * polymer, such as the type of the polymer, the number of
     * monomers and whether it has nonstandard features.
     */
    entity_poly: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * A flag to indicate whether the polymer contains at least
         * one monomer-to-monomer link different from that implied by
         * _entity_poly.type.
         */
        nstd_linkage: Aliased(str),
        /**
         * A flag to indicate whether the polymer contains at least
         * one monomer that is not considered standard.
         */
        nstd_monomer: Aliased(str),
        /**
         * The type of the polymer.
         */
        type: Aliased(str),
        /**
         * The PDB strand/chain id(s) corresponding to this polymer entity.
         */
        pdbx_strand_id: List(',', function (x) { return x; }),
        /**
         * Chemical sequence expressed as string of one-letter
         * amino acid codes. Modifications and non-standard
         * amino acids are coded as X.
         */
        pdbx_seq_one_letter_code: str,
        /**
         * Cannonical chemical sequence expressed as string of
         * one-letter amino acid codes. Modifications are coded
         * as the parent amino acid where possible.
         *
         * A  for alanine or adenine
         * B  for ambiguous asparagine/aspartic-acid
         * R  for arginine
         * N  for asparagine
         * D  for aspartic-acid
         * C  for cysteine or cystine or cytosine
         * Q  for glutamine
         * E  for glutamic-acid
         * Z  for ambiguous glutamine/glutamic acid
         * G  for glycine or guanine
         * H  for histidine
         * I  for isoleucine
         * L  for leucine
         * K  for lysine
         * M  for methionine
         * F  for phenylalanine
         * P  for proline
         * S  for serine
         * T  for threonine or thymine
         * W  for tryptophan
         * Y  for tyrosine
         * V  for valine
         * U  for uracil
         */
        pdbx_seq_one_letter_code_can: str,
        /**
         * For Structural Genomics entries, the sequence's target identifier registered at the TargetTrack database.
         */
        pdbx_target_identifier: str,
    },
    /**
     * Data items in the ENTITY_POLY_SEQ category specify the sequence
     * of monomers in a polymer. Allowance is made for the possibility
     * of microheterogeneity in a sample by allowing a given sequence
     * number to be correlated with more than one monomer ID. The
     * corresponding ATOM_SITE entries should reflect this
     * heterogeneity.
     */
    entity_poly_seq: {
        /**
         * This data item is a pointer to _entity_poly.entity_id in the
         * ENTITY_POLY category.
         */
        entity_id: str,
        /**
         * A flag to indicate whether this monomer in the polymer is
         * heterogeneous in sequence.
         */
        hetero: Aliased(str),
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        mon_id: str,
        /**
         * The value of _entity_poly_seq.num must uniquely and sequentially
         * identify a record in the ENTITY_POLY_SEQ list.
         *
         * Note that this item must be a number and that the sequence
         * numbers must progress in increasing numerical order.
         */
        num: int,
    },
    /**
     * There is only one item in the ENTRY category, _entry.id. This
     * data item gives a name to this entry and is indirectly a key to
     * the categories (such as CELL, GEOM, EXPTL) that describe
     * information pertinent to the entire data block.
     */
    entry: {
        /**
         * The value of _entry.id identifies the data block.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
    },
    /**
     * Data items in the EXPTL category record details about the
     * experimental work prior to the intensity measurements and
     * details about the absorption-correction technique employed.
     */
    exptl: {
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * The method used in the experiment.
         */
        method: Aliased(str),
    },
    /**
     * Data items in the STRUCT category record details about the
     * description of the crystallographic structure.
     */
    struct: {
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * A title for the data block. The author should attempt to convey
         * the essence of the structure archived in the CIF in the title,
         * and to distinguish this structural result from others.
         */
        title: str,
        /**
         * An automatically generated descriptor for an NDB structure or
         * the unstructured content of the PDB COMPND record.
         */
        pdbx_descriptor: str,
    },
    /**
     * Data items in the STRUCT_ASYM category record details about the
     * structural elements in the asymmetric unit.
     */
    struct_asym: {
        /**
         * A description of special aspects of this portion of the contents
         * of the asymmetric unit.
         */
        details: str,
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The value of _struct_asym.id must uniquely identify a record in
         * the STRUCT_ASYM list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * This data item indicates whether the structural elements are modified.
         */
        pdbx_modified: str,
        /**
         * A flag indicating that this entity was originally labeled
         * with a blank PDB chain id.
         */
        pdbx_blank_PDB_chainid_flag: Aliased(str),
    },
    /**
     * Data items in the STRUCT_CONF category record details about
     * the backbone conformation of a segment of polymer.
     *
     * Data items in the STRUCT_CONF_TYPE category define the
     * criteria used to identify the backbone conformations.
     */
    struct_conf: {
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        beg_label_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.label_comp_id in
         * the ATOM_SITE category.
         */
        beg_label_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        beg_label_seq_id: int,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        beg_auth_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in
         * the ATOM_SITE category.
         */
        beg_auth_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment begins.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        beg_auth_seq_id: int,
        /**
         * This data item is a pointer to _struct_conf_type.id in the
         * STRUCT_CONF_TYPE category.
         */
        conf_type_id: Aliased(str),
        /**
         * A description of special aspects of the conformation assignment.
         */
        details: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        end_label_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        end_label_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        end_label_seq_id: int,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        end_auth_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        end_auth_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        end_auth_seq_id: int,
        /**
         * The value of _struct_conf.id must uniquely identify a record in
         * the STRUCT_CONF list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment starts.
         */
        pdbx_beg_PDB_ins_code: str,
        /**
         * A component of the identifier for the residue at which the
         * conformation segment ends.
         */
        pdbx_end_PDB_ins_code: str,
        /**
         * This item is a place holder for the helix class used in the PDB
         * HELIX record.
         */
        pdbx_PDB_helix_class: str,
        /**
         * A placeholder for the lengths of the helix of the PDB
         * HELIX record.
         */
        pdbx_PDB_helix_length: int,
        /**
         * A placeholder for the helix identifier of the PDB
         * HELIX record.
         */
        pdbx_PDB_helix_id: str,
    },
    /**
     * Data items in the STRUCT_CONN category record details about
     * the connections between portions of the structure. These can be
     * hydrogen bonds, salt bridges, disulfide bridges and so on.
     *
     * The STRUCT_CONN_TYPE records define the criteria used to
     * identify these connections.
     */
    struct_conn: {
        /**
         * This data item is a pointer to _struct_conn_type.id in the
         * STRUCT_CONN_TYPE category.
         */
        conn_type_id: Aliased(str),
        /**
         * A description of special aspects of the connection.
         */
        details: str,
        /**
         * The value of _struct_conn.id must uniquely identify a record in
         * the STRUCT_CONN list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        ptnr1_label_asym_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        ptnr1_label_atom_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        ptnr1_label_comp_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        ptnr1_label_seq_id: int,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        ptnr1_auth_asym_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        ptnr1_auth_comp_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        ptnr1_auth_seq_id: int,
        /**
         * Describes the symmetry operation that should be applied to the
         * atom set specified by _struct_conn.ptnr1_label* to generate the
         * first partner in the structure connection.
         */
        ptnr1_symmetry: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        ptnr2_label_asym_id: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        ptnr2_label_atom_id: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        ptnr2_label_comp_id: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        ptnr2_label_seq_id: int,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        ptnr2_auth_asym_id: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        ptnr2_auth_comp_id: str,
        /**
         * A component of the identifier for partner 2 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        ptnr2_auth_seq_id: int,
        /**
         * Describes the symmetry operation that should be applied to the
         * atom set specified by _struct_conn.ptnr2_label* to generate the
         * second partner in the structure connection.
         */
        ptnr2_symmetry: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.pdbx_PDB_ins_code in the
         * ATOM_SITE category.
         */
        pdbx_ptnr1_PDB_ins_code: str,
        /**
         * A component of the identifier for partner 1 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_alt_id in the ATOM_SITE category.
         */
        pdbx_ptnr1_label_alt_id: str,
        /**
         * A placeholder for the standard residue name found in
         * the MODRES record of a PDB file.
         */
        pdbx_ptnr1_standard_comp_id: str,
        /**
         * A component of the identifier for partner 1 of the structure
         * connection.
         *
         * This data item is a pointer to _atom_site.pdbx_PDB_ins_code in the
         * ATOM_SITE category.
         */
        pdbx_ptnr2_PDB_ins_code: str,
        /**
         * A component of the identifier for partner 2 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_alt_id in the ATOM_SITE category.
         */
        pdbx_ptnr2_label_alt_id: str,
        /**
         * A component of the identifier for partner 3 of the
         * structure connection. This data item is a pointer to
         * _atom_site.pdbx_PDB_ins_code in the ATOM_SITE category.
         */
        pdbx_ptnr3_PDB_ins_code: str,
        /**
         * A component of the identifier for partner 3 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_alt_id in the ATOM_SITE category.
         */
        pdbx_ptnr3_label_alt_id: str,
        /**
         * A component of the identifier for partner 3 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_asym_id in the ATOM_SITE category.
         */
        pdbx_ptnr3_label_asym_id: str,
        /**
         * A component of the identifier for partner 3 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_atom_id in the ATOM_SITE category.
         */
        pdbx_ptnr3_label_atom_id: str,
        /**
         * A component of the identifier for partner 3 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_comp_id in the ATOM_SITE category.
         */
        pdbx_ptnr3_label_comp_id: str,
        /**
         * A component of the identifier for partner 1 of the
         * structure connection. This data item is a pointer to
         * _atom_site.label_seq_id in the ATOM_SITE category.
         */
        pdbx_ptnr3_label_seq_id: int,
        /**
         * A placeholder for the PDB id in the case the category
         * is used to hold the information of the MODRES record of
         * a PDB file.
         */
        pdbx_PDB_id: str,
        /**
         * Distance value for this contact.
         */
        pdbx_dist_value: float,
        /**
         * The chemical bond order associated with the specified atoms in
         * this contact.
         */
        pdbx_value_order: Aliased(str),
    },
    /**
     * Data items in the STRUCT_CONN_TYPE category record details
     * about the criteria used to identify interactions between
     * portions of the structure.
     */
    struct_conn_type: {
        /**
         * The criteria used to define the interaction.
         */
        criteria: str,
        /**
         * The chemical or structural type of the interaction.
         */
        id: Aliased(str),
        /**
         * A reference that specifies the criteria used to define the
         * interaction.
         */
        reference: str,
    },
    /**
     * Data items in the STRUCT_KEYWORDS category specify keywords
     * that describe the chemical structure in this entry.
     */
    struct_keywords: {
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * Keywords describing this structure.
         */
        text: List(',', function (x) { return x; }),
        /**
         * Terms characterizing the macromolecular structure.
         */
        pdbx_keywords: str,
    },
    /**
     * Data items in the STRUCT_NCS_OPER category describe the
     * noncrystallographic symmetry operations.
     *
     * Each operator is specified as a matrix and a subsequent
     * translation vector. Operators need not represent proper
     * rotations.
     */
    struct_ncs_oper: {
        /**
         * A code to indicate whether this operator describes a
         * relationship between coordinates all of which are given in the
         * data block (in which case the value of code is 'given'), or
         * whether the operator is used to generate new coordinates from
         * those that are given in the data block (in which case the value
         * of code is 'generate').
         */
        code: Aliased(str),
        /**
         * A description of special aspects of the noncrystallographic
         * symmetry operator.
         */
        details: str,
        /**
         * The value of _struct_ncs_oper.id must uniquely identify a
         * record in the STRUCT_NCS_OPER list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * The elements of the 3x3 matrix component of a
         * noncrystallographic symmetry operation.
         */
        matrix: Matrix(3, 3),
        /**
         * The elements of the three-element vector component of a
         * noncrystallographic symmetry operation.
         */
        vector: Vector(3),
    },
    /**
     * Data items in the STRUCT_SHEET_RANGE category record details
     * about the residue ranges that form a beta-sheet. Residues are
     * included in a range if they made beta-sheet-type hydrogen-bonding
     * interactions with at least one adjacent strand and if there are
     * at least two residues in the range.
     */
    struct_sheet_range: {
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        beg_label_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        beg_label_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        beg_label_seq_id: int,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        end_label_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        end_label_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        end_label_seq_id: int,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        beg_auth_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in
         * the ATOM_SITE category.
         */
        beg_auth_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range begins.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        beg_auth_seq_id: int,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        end_auth_asym_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        end_auth_comp_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta-sheet range ends.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        end_auth_seq_id: int,
        /**
         * The value of _struct_sheet_range.id must uniquely identify a
         * range in a given sheet in the STRUCT_SHEET_RANGE list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * This data item is a pointer to _struct_sheet.id in the
         * STRUCT_SHEET category.
         */
        sheet_id: str,
        /**
         * A component of the identifier for the residue at which the
         * beta sheet range begins.  Insertion code.
         */
        pdbx_beg_PDB_ins_code: str,
        /**
         * A component of the identifier for the residue at which the
         * beta sheet range ends. Insertion code.
         */
        pdbx_end_PDB_ins_code: str,
    },
    /**
     * Data items in the STRUCT_SITE category record details about
     * portions of the structure that contribute to structurally
     * relevant sites (e.g. active sites, substrate-binding subsites,
     * metal-coordination sites).
     */
    struct_site: {
        /**
         * A description of special aspects of the site.
         */
        details: str,
        /**
         * The value of _struct_site.id must uniquely identify a record in
         * the STRUCT_SITE list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * Number of residues in the site.
         */
        pdbx_num_residues: int,
        /**
         * Source of evidence supporting the assignment of this site.
         */
        pdbx_evidence_code: str,
        /**
         * A component of the identifier for the ligand in the site.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        pdbx_auth_asym_id: str,
        /**
         * A component of the identifier for the ligand in the site.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        pdbx_auth_comp_id: str,
        /**
         * A component of the identifier for the ligand in the site.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        pdbx_auth_seq_id: str,
        /**
         * PDB insertion code for the ligand in the site.
         */
        pdbx_auth_ins_code: str,
    },
    /**
     * Data items in the STRUCT_SITE_GEN category record details about
     * the generation of portions of the structure that contribute to
     * structurally relevant sites.
     */
    struct_site_gen: {
        /**
         * A description of special aspects of the symmetry generation of
         * this portion of the structural site.
         */
        details: str,
        /**
         * The value of _struct_site_gen.id must uniquely identify a record
         * in the STRUCT_SITE_GEN list.
         *
         * Note that this item need not be a number; it can be any unique
         * identifier.
         */
        id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_sites_alt.id in the
         * ATOM_SITES_ALT category.
         */
        label_alt_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        label_asym_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        label_atom_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        label_comp_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        label_seq_id: int,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        auth_asym_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        auth_comp_id: str,
        /**
         * A component of the identifier for participants in the site.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        auth_seq_id: str,
        /**
         * This data item is a pointer to _struct_site.id in the STRUCT_SITE
         * category.
         */
        site_id: str,
        /**
         * Describes the symmetry operation that should be applied to the
         * atom set specified by _struct_site_gen.label* to generate a
         * portion of the site.
         */
        symmetry: str,
        /**
         * PDB insertion code.
         */
        pdbx_auth_ins_code: str,
        /**
         * Number of residues in the site.
         */
        pdbx_num_res: int,
    },
    /**
     * Data items in the SYMMETRY category record details about the
     * space-group symmetry.
     */
    symmetry: {
        /**
         * This data item is a pointer to _entry.id in the ENTRY category.
         */
        entry_id: str,
        /**
         * The cell settings for this space-group symmetry.
         */
        cell_setting: Aliased(str),
        /**
         * Space-group number from International Tables for Crystallography
         * Vol. A (2002).
         */
        Int_Tables_number: int,
        /**
         * Space-group symbol as described by Hall (1981). This symbol
         * gives the space-group setting explicitly. Leave spaces between
         * the separate components of the symbol.
         *
         * Ref: Hall, S. R. (1981). Acta Cryst. A37, 517-525; erratum
         * (1981) A37, 921.
         */
        space_group_name_Hall: str,
        /**
         * Hermann-Mauguin space-group symbol. Note that the
         * Hermann-Mauguin symbol does not necessarily contain complete
         * information about the symmetry and the space-group origin. If
         * used, always supply the FULL symbol from International Tables
         * for Crystallography Vol. A (2002) and indicate the origin and
         * the setting if it is not implicit. If there is any doubt that
         * the equivalent positions can be uniquely deduced from this
         * symbol, specify the  _symmetry_equiv.pos_as_xyz or
         * _symmetry.space_group_name_Hall  data items as well. Leave
         * spaces between symbols referring to
         * different axes.
         */
        'space_group_name_H-M': str,
    },
    /**
     * These are internal RCSB records to keep track of data processing
     * and status of the entry.
     */
    pdbx_database_status: {
        /**
         * Code for status of file.
         */
        status_code: Aliased(str),
        /**
         * Code for status of structure factor file.
         */
        status_code_sf: Aliased(str),
        /**
         * Code for status of NMR constraints file.
         */
        status_code_mr: Aliased(str),
        /**
         * The value of _pdbx_database_status.entry_id identifies the data block.
         */
        entry_id: str,
        /**
         * The date of initial deposition.  (The first message for
         * deposition has been received.)
         */
        recvd_initial_deposition_date: str,
        /**
         * This code indicates whether the entry belongs to
         * Structural Genomics Project.
         */
        SG_entry: Aliased(str),
        /**
         * The site where the file was deposited.
         */
        deposit_site: Aliased(str),
        /**
         * The site where the file was deposited.
         */
        process_site: Aliased(str),
        /**
         * Code for status of chemical shift data file.
         */
        status_code_cs: Aliased(str),
        /**
         * The methods development category in which this
         * entry has been placed.
         */
        methods_development_category: Aliased(str),
        /**
         * A flag indicating that the entry is compatible with the PDB format.
         *
         * A value of 'N' indicates that the no PDB format data file is
         * corresponding to this entry is available in the PDB archive.
         */
        pdb_format_compatible: Aliased(str),
    },
    /**
     * The PDBX_NONPOLY_SCHEME category provides residue level nomenclature
     * mapping for non-polymer entities.
     */
    pdbx_nonpoly_scheme: {
        /**
         * Pointer to _atom_site.label_asym_id.
         */
        asym_id: str,
        /**
         * Pointer to _atom_site.label_entity_id.
         */
        entity_id: str,
        /**
         * Pointer to _atom_site.label_comp_id.
         */
        mon_id: str,
        /**
         * PDB strand/chain id.
         */
        pdb_strand_id: str,
        /**
         * NDB/RCSB residue number.
         */
        ndb_seq_num: str,
        /**
         * PDB residue number.
         */
        pdb_seq_num: str,
        /**
         * Author provided residue numbering.   This value may differ from the PDB residue
         * number and may not correspond to residue numbering within the coordinate records.
         */
        auth_seq_num: str,
        /**
         * PDB residue identifier.
         */
        pdb_mon_id: str,
        /**
         * Author provided residue identifier.   This value may differ from the PDB residue
         * identifier and may not correspond to residue identification within the coordinate records.
         */
        auth_mon_id: str,
        /**
         * PDB insertion code.
         */
        pdb_ins_code: str,
    },
    /**
     * Data items in PDBX_DATABASE_RELATED contain references to entries
     * that are related to the this entry.
     */
    pdbx_database_related: {
        /**
         * The name of the database containing the related entry.
         */
        db_name: str,
        /**
         * A description of the related entry.
         */
        details: str,
        /**
         * The identifying code in the related database.
         */
        db_id: str,
        /**
         * The identifying content type of the related entry.
         */
        content_type: Aliased(str),
    },
    pdbx_entity_nonpoly: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP category.
         */
        comp_id: str,
        /**
         * A name for the non-polymer entity
         */
        name: str,
    },
    /**
     * PDBX_CHEM_COMP_SYNONYMS holds chemical name and synonym correspondences.
     */
    pdbx_chem_comp_synonyms: {
        /**
         * The synonym of this particular chemical component.
         */
        name: str,
        /**
         * The chemical component for which this synonym applies.
         */
        comp_id: str,
        /**
         * The provenance of this synonym.
         */
        provenance: Aliased(str),
    },
    /**
     * Data items in the CHEM_COMP_IDENTIFIER category provide
     * identifiers for chemical components.
     */
    pdbx_chem_comp_identifier: {
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: str,
        /**
         * This data item contains the identifier value for this
         * component.
         */
        identifier: str,
        /**
         * This data item contains the identifier type.
         */
        type: Aliased(str),
        /**
         * This data item contains the name of the program
         * or library used to compute the identifier.
         */
        program: str,
        /**
         * This data item contains the version of the program
         * or library used to compute the identifier.
         */
        program_version: str,
    },
    /**
     * Data items in the PDBX_UNOBS_OR_ZERO_OCC_RESIDUES category list the
     * residues within the entry that are not observed or have zero occupancy.
     */
    pdbx_unobs_or_zero_occ_residues: {
        /**
         * The value of _pdbx_unobs_or_zero_occ_residues.id must uniquely identify
         * each item in the PDBX_UNOBS_OR_ZERO_OCC_RESIDUES list.
         *
         * This is an integer serial number.
         */
        id: int,
        /**
         * The value of polymer flag indicates whether the unobserved or
         * zero occupancy residue is part of a polymer chain or not
         */
        polymer_flag: Aliased(str),
        /**
         * The value of occupancy flag indicates whether the residue
         * is unobserved (= 1) or the coordinates have an occupancy of zero (=0)
         */
        occupancy_flag: Aliased(int),
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.pdbx_PDB_model_num in the
         * ATOM_SITE category.
         */
        PDB_model_num: int,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        auth_asym_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        auth_comp_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        auth_seq_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.pdbx_PDB_ins_code in the
         * ATOM_SITE category.
         */
        PDB_ins_code: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        label_asym_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        label_comp_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        label_seq_id: int,
    },
    /**
     * Data items in the PDBX_STRUCT_MOD_RESIDUE category list the
     * modified polymer components in the entry and provide some
     * details describing the nature of the modification.
     */
    pdbx_struct_mod_residue: {
        /**
         * The value of _pdbx_struct_mod_residue.id must uniquely identify
         * each item in the PDBX_STRUCT_MOD_RESIDUE list.
         *
         * This is an integer serial number.
         */
        id: int,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        auth_asym_id: str,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        auth_comp_id: str,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        auth_seq_id: int,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.pdbx_PDB_ins_code in the
         * ATOM_SITE category.
         */
        PDB_ins_code: str,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.label_asym_id in the
         * ATOM_SITE category.
         */
        label_asym_id: str,
        /**
         * Part of the identifier for the modified polymer component.
         *
         * This data item is a pointer to _atom_site.label_comp_id in the
         * ATOM_SITE category.
         */
        label_comp_id: str,
        /**
         * Part of the identifier for the unobserved or zero occupancy residue.
         *
         * This data item is a pointer to _atom_site.label_seq_id in the
         * ATOM_SITE category.
         */
        label_seq_id: int,
        /**
         * The parent component identifier for this modified polymer component.
         */
        parent_comp_id: str,
        /**
         * Details of the modification for this polymer component.
         */
        details: str,
    },
    /**
     * Data items in the PDBX_STRUCT_OPER_LIST category describe
     * Cartesian rotation and translation operations required to
     * generate or transform the coordinates deposited with this entry.
     */
    pdbx_struct_oper_list: {
        /**
         * This identifier code must uniquely identify a
         * record in the PDBX_STRUCT_OPER_LIST list.
         */
        id: str,
        /**
         * A code to indicate the type of operator.
         */
        type: Aliased(str),
        /**
         * A descriptive name for the transformation operation.
         */
        name: str,
        /**
         * The symmetry operation corresponding to the transformation operation.
         */
        symmetry_operation: str,
        /**
         * The elements of the 3x3 matrix component of the
         * transformation operation.
         */
        matrix: Matrix(3, 3),
        /**
         * The elements of the three-element vector component of the
         * transformation operation.
         */
        vector: Vector(3),
    },
    /**
     * Data items in the PDBX_STRUCT_ASSEMBLY category record details about
     * the structural elements that form macromolecular assemblies.
     */
    pdbx_struct_assembly: {
        /**
         * Provides details of the method used to determine or
         * compute the assembly.
         */
        method_details: str,
        /**
         * Provides the details of the oligomeric state of the assembly.
         */
        oligomeric_details: str,
        /**
         * The number of polymer molecules in the assembly.
         */
        oligomeric_count: int,
        /**
         * A description of special aspects of the macromolecular assembly.
         */
        details: str,
        /**
         * The value of _pdbx_struct_assembly.id must uniquely identify a record in
         * the PDBX_STRUCT_ASSEMBLY list.
         */
        id: str,
    },
    /**
     * Data items in the PDBX_STRUCT_ASSEMBLY_GEN category record details about
     * the generation of each macromolecular assemblies. The PDBX_STRUCT_ASSEMBLY_GEN
     * data items provide the specifications of the components that
     * constitute that assembly in terms of cartesian transformations.
     */
    pdbx_struct_assembly_gen: {
        /**
         * This data item is a pointer to _struct_asym.id in
         * the STRUCT_ASYM category.
         *
         * This item may be expressed as a comma separated list of identifiers.
         */
        asym_id_list: List(',', function (x) { return x; }),
        /**
         * This data item is a pointer to _pdbx_struct_assembly.id in the
         * PDBX_STRUCT_ASSEMBLY category.
         */
        assembly_id: str,
        /**
         * Identifies the operation of collection of operations
         * from category PDBX_STRUCT_OPER_LIST.
         *
         * Operation expressions may have the forms:
         *
         * (1)        the single operation 1
         * (1,2,5)    the operations 1, 2, 5
         * (1-4)      the operations 1,2,3 and 4
         * (1,2)(3,4) the combinations of operations
         * 3 and 4 followed by 1 and 2 (i.e.
         * the cartesian product of parenthetical
         * groups applied from right to left)
         */
        oper_expression: str,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_LIST category record
     * the list of entities within each reference molecule.
     */
    pdbx_reference_entity_list: {
        /**
         * The value of _pdbx_reference_entity_list.prd_id is a reference
         * _pdbx_reference_molecule.prd_id in the PDBX_REFERENCE_MOLECULE category.
         */
        prd_id: str,
        /**
         * The value of _pdbx_reference_entity_list.ref_entity_id is a unique identifier
         * the a constituent entity within this reference molecule.
         */
        ref_entity_id: str,
        /**
         * Defines the polymer characteristic of the entity.
         */
        type: Aliased(str),
        /**
         * Additional details about this entity.
         */
        details: str,
        /**
         * The component number of this entity within the molecule.
         */
        component_id: int,
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_LINK category give details about
     * the linkages between entities within reference molecules.
     */
    pdbx_reference_entity_link: {
        /**
         * The value of _pdbx_reference_entity_link.link_id uniquely identifies
         * linkages between entities with a molecule.
         */
        link_id: int,
        /**
         * The value of _pdbx_reference_entity_link.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        prd_id: str,
        /**
         * A description of special aspects of a linkage between
         * chemical components in the structure.
         */
        details: str,
        /**
         * The reference entity id of the first of the two entities joined by the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_list.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id_1: str,
        /**
         * The reference entity id of the second of the two entities joined by the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_list.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_LIST category.
         */
        ref_entity_id_2: str,
        /**
         * For a polymer entity, the sequence number in the first of
         * the two entities containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_1: int,
        /**
         * For a polymer entity, the sequence number in the second of
         * the two entities containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_2: int,
        /**
         * The component identifier in the first of the two entities containing the linkage.
         *
         * For polymer entities, this data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         *
         * For non-polymer entities, this data item is a pointer to
         * _pdbx_reference_entity_nonpoly.chem_comp_id in the
         * PDBX_REFERENCE_ENTITY_NONPOLY category.
         */
        comp_id_1: str,
        /**
         * The component identifier in the second of the two entities containing the linkage.
         *
         * For polymer entities, this data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         *
         * For non-polymer entities, this data item is a pointer to
         * _pdbx_reference_entity_nonpoly.chem_comp_id in the
         * PDBX_REFERENCE_ENTITY_NONPOLY category.
         */
        comp_id_2: str,
        /**
         * The atom identifier/name in the first of the two entities containing the linkage.
         */
        atom_id_1: str,
        /**
         * The atom identifier/name in the second of the two entities containing the linkage.
         */
        atom_id_2: str,
        /**
         * The bond order target for the chemical linkage.
         */
        value_order: Aliased(str),
        /**
         * The entity component identifier for the first of two entities containing the linkage.
         */
        component_1: int,
        /**
         * The entity component identifier for the second of two entities containing the linkage.
         */
        component_2: int,
        /**
         * A code indicating the entity types involved in the linkage.
         */
        link_class: Aliased(str),
    },
    /**
     * Data items in the PDBX_REFERENCE_ENTITY_POLY_LINK category give details about
     * polymer linkages including both standard and non-standard linkages between
     * polymer componnents.
     */
    pdbx_reference_entity_poly_link: {
        /**
         * The value of _pdbx_reference_entity_poly_link.link_id uniquely identifies
         * a linkage within a polymer entity.
         */
        link_id: int,
        /**
         * The value of _pdbx_reference_entity_poly_link.prd_id is a reference
         * _pdbx_reference_entity_list.prd_id in the PDBX_REFERENCE_ENTITY_POLY category.
         */
        prd_id: str,
        /**
         * The reference entity id of the polymer entity containing the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly.ref_entity_id
         * in the PDBX_REFERENCE_ENTITY_POLY category.
         */
        ref_entity_id: str,
        /**
         * The entity component identifier entity containing the linkage.
         */
        component_id: int,
        /**
         * For a polymer entity, the sequence number in the first of
         * the two components making the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_1: int,
        /**
         * For a polymer entity, the sequence number in the second of
         * the two components making the linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.num
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        entity_seq_num_2: int,
        /**
         * The component identifier in the first of the two components making the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        comp_id_1: str,
        /**
         * The component identifier in the second of the two components making the
         * linkage.
         *
         * This data item is a pointer to _pdbx_reference_entity_poly_seq.mon_id
         * in the PDBX_REFERENCE_ENTITY_POLY_SEQ category.
         */
        comp_id_2: str,
        /**
         * The atom identifier/name in the first of the two components making
         * the linkage.
         */
        atom_id_1: str,
        /**
         * The atom identifier/name in the second of the two components making
         * the linkage.
         */
        atom_id_2: str,
        /**
         * The bond order target for the non-standard linkage.
         */
        value_order: Aliased(str),
    },
    /**
     * Data items in the PDBX_MOLECULE category identify reference molecules
     * within a PDB entry.
     */
    pdbx_molecule: {
        /**
         * The value of _pdbx_molecule.prd_id is the PDB accession code for this
         * reference molecule.
         */
        prd_id: str,
        /**
         * The value of _pdbx_molecule.instance_id is identifies a particular molecule
         * in the molecule list.
         */
        instance_id: int,
        /**
         * A reference to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
    },
    /**
     * Data items in the PDBX_MOLECULE_FEATURES category record features of molecules
     * within a PDB entry.
     */
    pdbx_molecule_features: {
        /**
         * The value of _pdbx_molecule_features.prd_id is the PDB accession code for this
         * reference molecule.
         */
        prd_id: str,
        /**
         * Broadly defines the function of the molecule.
         */
        class: Aliased(str),
        /**
         * Defines the structural classification of the molecule.
         */
        type: Aliased(str),
        /**
         * A name of the molecule.
         */
        name: str,
        /**
         * Additional details describing the molecule.
         */
        details: str,
    },
    /**
     * Data items in the ENTITY_SRC_NAT category record details of
     * the source from which the entity was obtained in cases
     * where the entity was isolated directly from a natural tissue.
     */
    entity_src_nat: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * Scientific name of the organism of the natural source.
         */
        pdbx_organism_scientific: str,
        /**
         * The plasmid containing the gene.
         */
        pdbx_plasmid_name: str,
        /**
         * This data item is an ordinal identifier for entity_src_nat data records.
         */
        pdbx_src_id: int,
        /**
         * The beginning polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_beg_seq_num: int,
        /**
         * The ending polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_end_seq_num: int,
    },
    /**
     * Data items in the ENTITY_SRC_GEN category record details of
     * the source from which the entity was obtained in cases
     * where the source was genetically manipulated.  The
     * following are treated separately:  items pertaining to the tissue
     * from which the gene was obtained, items pertaining to the host
     * organism for gene expression and items pertaining to the actual
     * producing organism (plasmid).
     */
    entity_src_gen: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * Identifies the gene.
         */
        pdbx_gene_src_gene: List(',', function (x) { return x; }),
        /**
         * Scientific name of the organism.
         */
        pdbx_gene_src_scientific_name: str,
        /**
         * The name of the plasmid that produced the entity in the host
         * organism. Where full details of the protein production are available
         * it would be expected that this item would be derived from
         * _pdbx_construct.name of the construct pointed to from
         * _entity_src_gen_express.plasmid_id.
         */
        plasmid_name: str,
        /**
         * This data item is an ordinal identifier for entity_src_gen data records.
         */
        pdbx_src_id: int,
        /**
         * The beginning polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_beg_seq_num: int,
        /**
         * The ending polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_end_seq_num: int,
    },
    /**
     * The data items in category PDBX_ENTITY_SRC_SYN record the source details
     * about chemically synthesized molecules.
     */
    pdbx_entity_src_syn: {
        /**
         * The scientific name of the organism from which the sequence of
         * the synthetic entity was derived.
         */
        organism_scientific: str,
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * This data item is an ordinal identifier for pdbx_entity_src_syn data records.
         */
        pdbx_src_id: int,
        /**
         * The beginning polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_beg_seq_num: int,
        /**
         * The ending polymer sequence position for the polymer section corresponding
         * to this source.
         *
         * A reference to the sequence position in the entity_poly category.
         */
        pdbx_end_seq_num: int,
    },
    /**
     * Data items in the PDBX_ENTITY_BRANCH_DESCRIPTOR category provide
     * string descriptors of entity chemical structure.
     */
    pdbx_entity_branch_descriptor: {
        /**
         * This data item is a pointer to _entity_poly.entity_id in the ENTITY
         * category.
         */
        entity_id: str,
        /**
         * This data item contains the descriptor value for this
         * entity.
         */
        descriptor: str,
        /**
         * This data item contains the descriptor type.
         */
        type: Aliased(str),
        /**
         * This data item contains the name of the program
         * or library used to compute the descriptor.
         */
        program: str,
        /**
         * This data item contains the version of the program
         * or library used to compute the descriptor.
         */
        program_version: str,
        /**
         * Ordinal index for this category.
         */
        ordinal: int,
    },
    /**
     * Data items in the pdbx_entity_instance_feature category records
     * special features of selected entity instances.
     */
    pdbx_entity_instance_feature: {
        /**
         * Special structural details about this entity instance.
         */
        details: str,
        /**
         * A feature type associated with entity instance.
         */
        feature_type: Aliased(str),
        /**
         * Author instance identifier (formerly PDB Chain ID)
         */
        auth_asym_id: str,
        /**
         * Instance identifier for this entity.
         */
        asym_id: str,
        /**
         * Author provided residue number.
         */
        auth_seq_num: str,
        /**
         * Position in the sequence.
         */
        seq_num: int,
        /**
         * Chemical component identifier
         */
        comp_id: str,
        /**
         * The author provided chemical component identifier
         */
        auth_comp_id: str,
        /**
         * An ordinal index for this category
         */
        ordinal: int,
    },
    /**
     * Data items in the PDBX_ENTITY_BRANCH_LIST category specify the list
     * of monomers in a branched entity.  Allowance is made for the possibility
     * of microheterogeneity in a sample by allowing a given sequence
     * number to be correlated with more than one monomer ID. The
     * corresponding ATOM_SITE entries should reflect this
     * heterogeneity.
     */
    pdbx_entity_branch_list: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * A flag to indicate whether this monomer in the entity is
         * heterogeneous in sequence.
         */
        hetero: Aliased(str),
        /**
         * This data item is a pointer to _chem_comp.id in the CHEM_COMP
         * category.
         */
        comp_id: str,
        /**
         * The value pair  _pdbx_entity_branch_list.num and _pdbx_entity_branch_list.comp_id
         * must uniquely identify a record in the PDBX_ENTITY_BRANCH_LIST list.
         */
        num: int,
    },
    /**
     * Data items in the PDBX_ENTITY_BRANCH_LINK category give details about
     * the linkages between components within a branched entity.
     */
    pdbx_entity_branch_link: {
        /**
         * The value of _pdbx_entity_branch_link.link_id uniquely identifies
         * linkages within the branched entity.
         */
        link_id: int,
        /**
         * A description of special aspects of this linkage.
         */
        details: str,
        /**
         * The entity id for this branched entity.
         *
         * This data item is a pointer to _pdbx_entity_branch_list.entity_id
         * in the PDBX_ENTITY_BRANCH_LIST category.
         */
        entity_id: str,
        /**
         * The component number for the first component making the linkage.
         *
         * This data item is a pointer to _pdbx_entity_branch_list.num
         * in the PDBX_ENTITY_BRANCH_LIST category.
         */
        entity_branch_list_num_1: int,
        /**
         * The component number for the second component making the linkage.
         *
         * This data item is a pointer to _pdbx_entity_branch_list.num
         * in the PDBX_ENTITY_BRANCH_LIST category.
         */
        entity_branch_list_num_2: int,
        /**
         * The component identifier for the first component making the linkage.
         *
         * This data item is a pointer to _pdbx_entity_branch_list.comp_id
         * in the PDBX_ENTITY_BRANCH_LIST category.
         */
        comp_id_1: str,
        /**
         * The component identifier for the second component making the linkage.
         *
         * This data item is a pointer to _pdbx_entity_branch_list.comp_id
         * in the PDBX_ENTITY_BRANCH_LIST category.
         */
        comp_id_2: str,
        /**
         * The atom identifier/name for the first atom making the linkage.
         */
        atom_id_1: str,
        /**
         * The leaving atom identifier/name bonded to the first atom making the linkage.
         */
        leaving_atom_id_1: str,
        /**
         * The chiral configuration of the first atom making the linkage.
         */
        atom_stereo_config_1: Aliased(str),
        /**
         * The atom identifier/name for the second atom making the linkage.
         */
        atom_id_2: str,
        /**
         * The leaving atom identifier/name bonded to the second atom making the linkage.
         */
        leaving_atom_id_2: str,
        /**
         * The chiral configuration of the second atom making the linkage.
         */
        atom_stereo_config_2: Aliased(str),
        /**
         * The bond order target for the chemical linkage.
         */
        value_order: Aliased(str),
    },
    /**
     * Data items in the PDBX_ENTITY_BRANCH category specify the list
     * of branched entities and the type.
     */
    pdbx_entity_branch: {
        /**
         * The entity id for this branched entity.
         *
         * This data item is a pointer to _entity.id
         */
        entity_id: str,
        /**
         * The type of this branched oligosaccharide.
         */
        type: Aliased(str),
    },
    /**
     * The PDBX_BRANCH_SCHEME category provides residue level nomenclature
     * mapping for branch chain entities.
     */
    pdbx_branch_scheme: {
        /**
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * A flag to indicate whether this monomer in the entity is
         * heterogeneous in sequence.
         */
        hetero: Aliased(str),
        /**
         * Pointer to _atom_site.label_asym_id.
         */
        asym_id: str,
        /**
         * This data item is a pointer to _atom_site.label_comp_id in the
         * PDBX_ENTITY_BRANCH_LIST category.
         */
        mon_id: str,
        /**
         * This data item is a pointer to _pdbx_entity_branch_list.num in the
         * PDBX_ENTITY_BRANCH_LIST category.
         */
        num: int,
        /**
         * This data item is a pointer to _atom_site.auth_asym_id in the
         * ATOM_SITE category.
         */
        pdb_asym_id: str,
        /**
         * This data item is a pointer to _atom_site.auth_seq_id in the
         * ATOM_SITE category.
         */
        pdb_seq_num: str,
        /**
         * This data item is a pointer to _atom_site.auth_comp_id in the
         * ATOM_SITE category.
         */
        pdb_mon_id: str,
        /**
         * This data item is a pointer to _atom_site.pdbx_auth_asym_id in the
         * ATOM_SITE category.
         */
        auth_asym_id: str,
        /**
         * This data item is a pointer to _atom_site.pdbx_auth_seq_id in the
         * ATOM_SITE category.
         */
        auth_seq_num: str,
        /**
         * This data item is a pointer to _atom_site.pdbx_auth_comp_id in the
         * ATOM_SITE category.
         */
        auth_mon_id: str,
    },
    /**
     * Data items in the IHM_STARTING_MODEL_DETAILS category records the
     * details about structural models used as starting inputs in
     * the integrative model building process.
     */
    ihm_starting_model_details: {
        /**
         * A unique identifier for the starting structural model.
         */
        starting_model_id: str,
        /**
         * A unique identifier for the distinct molecular entities.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * A text description of the molecular entity
         */
        entity_description: str,
        /**
         * An asym/strand identifier for the entity molecule.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The identifier for the polymeric segment modeled using this starting model.
         * This data item is a pointer to _ihm_entity_poly_segment.id in the
         * IHM_ENTITY_POLY_SEGMENT category.
         */
        entity_poly_segment_id: int,
        /**
         * The source of the starting model.
         */
        starting_model_source: Aliased(str),
        /**
         * The author assigned chainId/auth_asym_id corresponding to this starting model.
         * This corresponds to the chainId/auth_asym_id of the experimental models in the
         * PDB or comparative models in the Model Archive or the starting models referenced
         * via a DOI. If starting models are included in IHM_STARTING_MODEL_COORD, then
         * this will be the same as _ihm_starting_model_details.asym_id.
         */
        starting_model_auth_asym_id: str,
        /**
         * The offset in residue numbering between the starting model and the deposited I/H model, if applicable.
         * I/H model residue number = Starting model residue number + offset
         */
        starting_model_sequence_offset: int,
        /**
         * Identifier to the starting model (comparative, experimental or integrative)
         * used as input in the integrative modeling.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
    },
    /**
     * Data items in the IHM_STARTING_COMPARATIVE_MODELS category records
     * additional details about comparative models used as starting inputs in
     * the integrative model building process.
     */
    ihm_starting_comparative_models: {
        /**
         * A unique identifier for the starting comparative model.
         */
        id: int,
        /**
         * The identifier for the starting structural model.
         * This data item is a pointer to _ihm_starting_model_details.starting_model_id
         * in the IHM_STARTING_MODEL_DETAILS category.
         */
        starting_model_id: str,
        /**
         * The chainId/auth_asym_id corresponding to the starting model.
         */
        starting_model_auth_asym_id: str,
        /**
         * The starting residue index of the starting model.
         */
        starting_model_seq_id_begin: int,
        /**
         * The ending residue index of the starting model.
         */
        starting_model_seq_id_end: int,
        /**
         * The chainId/auth_asym_id corresponding to the template.
         */
        template_auth_asym_id: str,
        /**
         * The starting residue index of the template.
         */
        template_seq_id_begin: int,
        /**
         * The ending residue index of the template.
         */
        template_seq_id_end: int,
        /**
         * The percentage sequence identity between the template sequence and the comparative model sequence.
         */
        template_sequence_identity: float,
        /**
         * The denominator used while calculating the sequence identity provided in
         * _ihm_starting_comparative_models.template_sequence_identity.
         */
        template_sequence_identity_denominator: Aliased(int),
        /**
         * The dataset list id corresponding to the template used to obtain the comparative model.
         * This data item is a pointer to _ihm_dataset_list.id in the IHM_DATASET_LIST category.
         */
        template_dataset_list_id: int,
        /**
         * The file id corresponding to the sequence alignment of the template sequence and the comparative model sequence.
         * This data item is a pointer to _ihm_external_files.id in the IHM_EXTERNAL_FILES category.
         */
        alignment_file_id: int,
    },
    /**
     * Data items in the IHM_STARTING_MODEL_SEQ_DIF category provide a
     * mechanism for indicating and annotating point differences
     * between the sequence of the entity or biological unit described
     * in the data block and the sequence of the starting model used in
     * the integrative modeling referenced from a database. The point
     * differences may be due to point mutations introduced in the
     * starting model or the presence of modified amino acid residues.
     */
    ihm_starting_model_seq_dif: {
        /**
         * A unique identifier for the entry.
         */
        id: int,
        /**
         * A unique identifier for the distinct molecular entities.
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY category.
         */
        entity_id: str,
        /**
         * An asym/strand identifier for the entity molecule.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The residue index.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id: int,
        /**
         * The component identifier for the residue.
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id: str,
        /**
         * Unique identifier for the starting model record.
         * This data item is a pointer to _ihm_starting_model_details.starting_model_id in the
         * IHM_STARTING_MODEL_DETAILS category.
         */
        starting_model_id: str,
        /**
         * The asym/strand identifier for the entity molecule of the database starting model.
         */
        db_asym_id: str,
        /**
         * The corresponding residue index of the database starting model.
         */
        db_seq_id: int,
        /**
         * The correspinding component identifier for the residue in the database starting model.
         */
        db_comp_id: str,
        /**
         * A description of special aspects of the point differences
         * between the sequence of the entity or biological unit described
         * in the data block and that in the starting model referenced
         * from a database.
         */
        details: str,
    },
    /**
     * Data items in the IHM_MODEL_REPRESENTATION category lists the
     * various mono or multi-scale model representations used in the
     * integrative modeling study.
     */
    ihm_model_representation: {
        /**
         * A unique identifier for the model representation.
         */
        id: int,
        /**
         * Name/brief description for the model representation.
         */
        name: str,
        /**
         * Additional details about the model representation.
         */
        details: str,
    },
    /**
     * Data items in the IHM_MODEL_REPRESENTATION_DETAILS category records the
     * details about the architecture and representation of structural
     * models involved in the integrative modeling study.
     */
    ihm_model_representation_details: {
        /**
         * A unique identifier for the category.
         */
        id: int,
        /**
         * An identifier that collects or groups together a set of representations.
         * This data item is a pointer to _ihm_model_representation.id in the
         * IHM_MODEL_REPRESENTATION category.
         */
        representation_id: int,
        /**
         * The identifier for the polymeric segment in the representation.
         * This data item is a pointer to _ihm_entity_poly_segment.id in the
         * IHM_ENTITY_POLY_SEGMENT category.
         */
        entity_poly_segment_id: int,
        /**
         * A unique identifier distinct molecular entities.
         * This data item is a pointer to _entity.id in the
         * ENTITY category.
         */
        entity_id: str,
        /**
         * A text description of the molecular entity
         */
        entity_description: str,
        /**
         * An asym/strand identifier for the entity molecule.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        entity_asym_id: str,
        /**
         * The primitive object used to model this segment.
         */
        model_object_primitive: Aliased(str),
        /**
         * The identifier for the starting structural model.
         * This data item is a pointer to _ihm_starting_model_details.starting_model_id
         * in the IHM_STARTING_MODEL_DETAILS category.
         */
        starting_model_id: str,
        /**
         * The manner in which the segment is modeled.
         */
        model_mode: Aliased(str),
        /**
         * The level of detail at which model primitive objects are applied to the structure.
         */
        model_granularity: Aliased(str),
        /**
         * The number of primitive objects used to model a feature in the case of 'by-feature' granularity.
         */
        model_object_count: int,
    },
    /**
     * Data items in the IHM_STRUCT_ASSEMBLY_DETAILS category records
     * the details of the structural assemblies and used in the
     * integrative modeling.
     */
    ihm_struct_assembly_details: {
        /**
         * A unique identifier for the structural assembly description.
         */
        id: int,
        /**
         * An identifier for the structural assembly.
         * This data item will remain the same for all components
         * of an assembly.
         * This data item is a pointer to _ihm_struct_assembly.id
         * in the IHM_STRUCT_ASSEMBLY category.
         */
        assembly_id: int,
        /**
         * The parent of this assembly in a hierarchy.
         * This data item is a pointer to _ihm_struct_assembly.id in the
         * IHM_STRUCT_ASSEMBLY category.
         * This data item should point to the assembly id of the immediate
         * parent in a hierarchy.
         * By convention, the full assembly (top of hierarchy) is assigned parent id 0 (zero).
         * In case of assemblies that do not conform to a hierarchy,
         * _ihm_struct_assembly_details.parent_assembly_id is the same as
         * _ihm_struct_assembly_details.assembly_id indicating a self-parent.
         */
        parent_assembly_id: int,
        /**
         * A text description of the molecular entity
         */
        entity_description: str,
        /**
         * A unique identifier for distinct molecular entities.
         * This data item is a pointer to _entity.id in the
         * ENTITY category.
         */
        entity_id: str,
        /**
         * An asym/strand identifier for the component in the assembly.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The identifier for the polymeric segment in the assembly.
         * This data item is a pointer to _ihm_entity_poly_segment.id in the
         * IHM_ENTITY_POLY_SEGMENT category.
         */
        entity_poly_segment_id: int,
    },
    /**
     * Data items in the IHM_STRUCT_ASSEMBLY category lists
     * all the structural assemblies used in the integrative
     * modeling study.
     */
    ihm_struct_assembly: {
        /**
         * A unique identifier for the structural assembly.
         */
        id: int,
        /**
         * A name for the structural assembly.
         */
        name: str,
        /**
         * Description of the structural assembly.
         */
        description: str,
    },
    /**
     * Data items in the IHM_MODELING_PROTOCOL category lists all
     * modeling protocols used in the integrative modeling study.
     */
    ihm_modeling_protocol: {
        /**
         * A unique identifier for the modeling protocol.
         */
        id: int,
        /**
         * Number of independent steps in the modeling protocol.
         */
        num_steps: int,
        /**
         * The name for the modeling protocol.
         */
        protocol_name: str,
    },
    /**
     * Data items in the IHM_MODELING_PROTOCOL_DETAILS category records the
     * step-wise details of the integrative modeling workflow.
     */
    ihm_modeling_protocol_details: {
        /**
         * A unique identifier for the modeling protocol/step combination.
         */
        id: int,
        /**
         * An index for the modeling protocol carried out.
         * This data item is a pointer to _ihm_modeling_protocol.id in the
         * IHM_MODELING_PROTOCOL category.
         */
        protocol_id: int,
        /**
         * An index for a particular step within the modeling protocol.
         */
        step_id: int,
        /**
         * An index for the structural assembly being modeled.
         * This is an indicator to whether the whole assembly is modeled
         * or if only a subset of the structural assembly is modeled.
         * This data item is a pointer to _ihm_struct_assembly.id in the
         * IHM_STRUCT_ASSEMBLY category. The IHM_STRUCT_ASSEMBLY category provides the
         * details regarding the different structural assemblies used in the modeling.
         * The default value for this data item is "1", indicating that the entire
         * assembly is being modeled.
         */
        struct_assembly_id: int,
        /**
         * An index for the dataset group being used in the modeling protocol.
         * This data item is a pointer to the _ihm_dataset_group.id in the
         * IHM_DATASET_GROUP category.
         */
        dataset_group_id: int,
        /**
         * A textual description of the structural assembly being modeled.
         */
        struct_assembly_description: str,
        /**
         * The name or type of the modeling step.
         */
        step_name: str,
        /**
         * Description of the method involved in the modeling step.
         */
        step_method: str,
        /**
         * The number of models in the beginning of the step.
         */
        num_models_begin: int,
        /**
         * The number of models at the end of the step.
         */
        num_models_end: int,
        /**
         * A flag to indicate if the modeling is multi scale.
         */
        multi_scale_flag: Aliased(str),
        /**
         * A flag to indicate if the modeling is multi state.
         */
        multi_state_flag: Aliased(str),
        /**
         * A flag to indicate if the modeling involves an ensemble ordered by time or other order.
         */
        ordered_flag: Aliased(str),
        /**
         * The file id corresponding to the script used in the modeling protocol step.
         * This data item is a pointer to _ihm_external_files.id in the IHM_EXTERNAL_FILES category.
         */
        script_file_id: int,
        /**
         * Identifier to the software used in the modeling protocol step.
         * This data item is a pointer to the _software.pdbx_ordinal in the
         * SOFTWARE category.
         */
        software_id: int,
    },
    /**
     * Data items in the IHM_MULTI_STATE_MODELING category records the
     * details of the multi-state modeling protocol, if applicable.
     */
    ihm_multi_state_modeling: {
        /**
         * A unique identifier for a particular state in the multi-state modeling.
         */
        state_id: int,
        /**
         * An identifier for a collections of states in the multi-state modeling.
         * This data item can be used when structural models belong to diffent
         * multi-state modeling types.
         */
        state_group_id: int,
        /**
         * A fraction representing the population of the particular state.
         */
        population_fraction: float,
        /**
         * The standard deviation of the population fraction.
         */
        population_fraction_sd: float,
        /**
         * The type that the multiple states being modeled belong to.
         */
        state_type: str,
        /**
         * A descriptive name for the state.
         */
        state_name: str,
        /**
         * The type of multi-state modeling experiment carried out.
         */
        experiment_type: Aliased(str),
        /**
         * Additional textual details of the multi-state modeling, if required.
         */
        details: str,
    },
    /**
     * Data items in the IHM_MODELING_POST_PROCESS category records
     * the details of the post processing of the models/results of
     * the modeling protocol.
     */
    ihm_modeling_post_process: {
        /**
         * A unique identifier for the post modeling analysis/step combination.
         */
        id: int,
        /**
         * An identifier for the modeling protocol, whose post modeling analysis
         * is being carried out.
         * This data item is a pointer to the _ihm_modeling_protocol.id
         * in the IHM_MODELING_PROTOCOL category.
         */
        protocol_id: int,
        /**
         * An identifier for the post modeling analysis. This data item accounts for
         * multiple post-modeling analyses that can be carried out.
         */
        analysis_id: int,
        /**
         * In a multi-step process, this identifier denotes the particular
         * step in the post modeling analysis.
         */
        step_id: int,
        /**
         * The type of post modeling analysis being carried out.
         */
        type: Aliased(str),
        /**
         * The parameter/feature used in the post modeling analysis.
         */
        feature: Aliased(str),
        /**
         * The number of models at the beginning of the post processing step.
         */
        num_models_begin: int,
        /**
         * The number of models the the end of the post processing step.
         */
        num_models_end: int,
    },
    /**
     * Data items in the IHM_ENSEMBLE_INFO category records the
     * details of the model clusters or ensembles obtained after
     * sampling.
     */
    ihm_ensemble_info: {
        /**
         * A unique id for the ensemble.
         */
        ensemble_id: int,
        /**
         * An optional name for the cluster or ensemble for better description.
         */
        ensemble_name: str,
        /**
         * An identifier for the post modeling analyses carried out.
         * This data item is a pointer to _ihm_modeling_post_process.id in
         * the IHM_MODELING_POST_PROCESS category.
         */
        post_process_id: int,
        /**
         * An identifier for the cluster or group of models being deposited.
         * This data item is a pointer to the _ihm_model_group.id
         * in the IHM_MODEL_GROUP category.
         */
        model_group_id: int,
        /**
         * The clustering method used to obtain the ensemble, if applicable.
         */
        ensemble_clustering_method: Aliased(str),
        /**
         * The parameter/feature used for clustering the models, if applicable.
         */
        ensemble_clustering_feature: Aliased(str),
        /**
         * The number of models in the current ensemble being described.
         */
        num_ensemble_models: int,
        /**
         * The number of models from the current ensemble that is deposited.
         */
        num_ensemble_models_deposited: int,
        /**
         * The precision of each cluster or ensemble is calculated as dRMSD, which
         * is the average C-alpha distance root mean square deviation (dRMSD)
         * between the individual models in the cluster and the cluster centroid.
         * The cluster centroid is defined as the model with the minimal sum of
         * dRMSDs to the other models in the cluster or ensemble.
         */
        ensemble_precision_value: float,
        /**
         * A reference to the external file containing the structural models
         * in the ensemble. The number of models in the external file should
         * correspond to the number of models in the ensemble. This data item
         * is a pointer to _ihm_external_files.id in the IHM_EXTERNAL_FILES
         * category.
         * It is recommended that the large ensemble files be stored as separate
         * zip files within the same DOI. It is also recommended that large sphere
         * model ensembles be in binary format, which facilitates faster access.
         * Currently, a binary dump of co-ordinates in dcd format is suggested.
         * The topology can be inferred from the IHM_SPHERE_OBJ_SITE and the
         * ATOM_SITE categories in the corresponding mmCIF file.
         */
        ensemble_file_id: int,
    },
    /**
     * Data items in the IHM_MODEL_LIST category record the
     * details of the models being deposited.
     */
    ihm_model_list: {
        /**
         * A unique identifier for the structural model being deposited.
         */
        model_id: int,
        /**
         * A decsriptive name for the model.
         */
        model_name: str,
        /**
         * An identifier to the structure assembly corresponding to the model.
         * This data item is a pointer to the _ihm_struct_assembly.id
         * in the IHM_STRUCT_ASSEMBLY category.
         */
        assembly_id: int,
        /**
         * An identifier to the modeling protocol that produced the model.
         * This data item is a pointer to the _ihm_modeling_protocol.id
         * in the IHM_MODELING_PROTOCOL category.
         */
        protocol_id: int,
        /**
         * An identifier to the multi-scale model representation id of the model.
         * This data item is a pointer to the _ihm_model_representation.id
         * in the IHM_MODEL_REPRESENTATION category.
         */
        representation_id: int,
    },
    /**
     * IHM_MODEL_GROUP category defines collections or groups of integrative
     * structural models.
     */
    ihm_model_group: {
        /**
         * A unique identifier for a collection or group of structural models.
         * This data item can be used to group models into structural clusters
         * or using other criteria based on experimental data or other
         * relationships such as those belonging to the same state or time stamp.
         * An ensemble of models and its representative can either be grouped together
         * or can be separate groups in the ihm_model_group table. The choice between
         * the two options should be decided based on how the modeling was carried out
         * and how the representative was chosen. If the representative is a member of
         * the ensemble (i.e., best scoring model), then it is recommended that the
         * representative and the ensemble belong to the same model group. If the
         * representative is calculated from the ensemble (i.e., centroid), then it is
         * recommended that the representative be separated into a different group.
         */
        id: int,
        /**
         * A name for the collection of models.
         */
        name: str,
        /**
         * Additional details about the collection of models.
         */
        details: str,
    },
    /**
     * IHM_MODEL_GROUP_LINK category provides the list of models present in
     * a particular model group.
     */
    ihm_model_group_link: {
        /**
         * An identifier for the structural model.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * An identifier for the structural model group.
         * This data item is a pointer to _ihm_model_group.id in the
         * IHM_MODEL_GROUP category.
         */
        group_id: int,
    },
    /**
     * Data items in the IHM_MODEL_REPRESENTATIVE category record the
     * details of the representative model in an ensemble or cluster.
     */
    ihm_model_representative: {
        /**
         * A unique identifier for the representative of the model group.
         */
        id: int,
        /**
         * The model group identifier corresponding to the representative model.
         * This data item is a pointer to _ihm_model_group.id in the
         * IHM_MODEL_GROUP category.
         */
        model_group_id: int,
        /**
         * The model identifier corresponding to the representative model.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * The selection criteria based on which the representative is chosen.
         */
        selection_criteria: Aliased(str),
    },
    /**
     * Category holds the list of all datasets used in the IHM modeling.
     * These can be datasets archived in other related databases such as
     * BMRB, EMDB, EMPIAR, SASBDB, PRIDE etc., or can be hosted in other
     * places such as the authors website, github etc. These datasets are
     * elaborated in detail in the IHM_DATASET_RELATED_DB_REFERENCE and/or
     * the IHM_DATASET_EXTERNAL_REFERENCE categories. This category
     * holds the list of all datasets used.
     */
    ihm_dataset_list: {
        /**
         * A unique identifier for the dataset.
         */
        id: int,
        /**
         * The type of data held in the dataset.
         */
        data_type: Aliased(str),
        /**
         * A flag that indicates whether the dataset is archived in
         * an IHM related database or elsewhere.
         */
        database_hosted: Aliased(str),
    },
    /**
     * Category to define groups or collections of input datasets.
     */
    ihm_dataset_group: {
        /**
         * A unique identifier for the dataset group.
         */
        id: int,
        /**
         * A name for the dataset group.
         */
        name: str,
        /**
         * The application / utilization of the dataset group in modeling.
         */
        application: Aliased(str),
        /**
         * Additional details regarding the dataset group.
         */
        details: str,
    },
    /**
     * IHM_DATASET_GROUP_LINK category provides the list of datasets present in
     * a particular group.
     */
    ihm_dataset_group_link: {
        /**
         * An identifier for the dataset.
         * This data item is a pointer to _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * An identifier for the dataset group.
         * This data item is a pointer to _ihm_dataset_group.id in the
         * IHM_DATASET_GROUP category.
         */
        group_id: int,
    },
    /**
     * Category holds information about related datasets, where one is derived from the other.
     */
    ihm_related_datasets: {
        /**
         * The dataset list id corresponding to the derived dataset.
         * This data item is a pointer to _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id_derived: int,
        /**
         * The primary dataset list id from which the corresponding derived dataset is obtained.
         * This data item is a pointer to _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id_primary: int,
    },
    /**
     * Category holds information related to data sources for the entry.
     * These can be datasets archived in other related databases such as
     * BMRB, EMDB, EMPIAR, SASBDB, PRIDE etc.
     */
    ihm_dataset_related_db_reference: {
        /**
         * A unique identifier for the related database entry.
         */
        id: int,
        /**
         * Identifier to the dataset list used in the IHM modeling.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * The name of the database containing the dataset entry.
         */
        db_name: Aliased(str),
        /**
         * The accession code for the database entry.
         */
        accession_code: str,
        /**
         * Version of the database entry, if the database allows versioning.
         */
        version: str,
        /**
         * Details regarding the dataset entry.
         */
        details: str,
    },
    /**
     * Category holds links to other external data sources for the I/H model entry.
     * Input datasets held in other databases such as EMDB, BMRB, SASBDB etc.
     * are referenced in the IHM_DATASET_RELATED_DB_REFERENCE category.
     * This data category, along with IHM_EXTERNAL_FILES category, holds information
     * regarding other non-database external data sources, such as  DOIs (digital
     * object identifiers) or supplementary files stored locally. The DOIs can either
     * lead to the external data file(s) directly (as in case of DOIs provided by the PDB)
     * or might lead to an HTML landing page (as provided by Zenodo). In the latter case,
     * additional URL (Uniform Resource Locator) information is required to retrieve
     * the external data file(s).
     */
    ihm_external_reference_info: {
        /**
         * A unique identifier for the external reference.
         */
        reference_id: int,
        /**
         * The name of the reference provider.
         */
        reference_provider: str,
        /**
         * The type of external reference.
         * Currently, only Digital Object Identifiers (DOIs) and supplementary files
         * stored locally are supported.
         */
        reference_type: Aliased(str),
        /**
         * The external reference or the Digital Object Identifier (DOI).
         * This field is not relevant for local files.
         */
        reference: str,
        /**
         * The type of object that the external reference points to, usually
         * a single file or an archive.
         */
        refers_to: Aliased(str),
        /**
         * The Uniform Resource Locator (URL) corresponding to the external reference (DOI).
         * This URL should link to the corresponding downloadable file or archive and is provided
         * to enable automated software to download the referenced file or archive.
         */
        associated_url: str,
    },
    /**
     * Category provides details regarding external files. The IHM_EXTERNAL_REFERENCE_INFO
     * category captures the top-level details regarding external data sources.
     * This category captures the specific details regarding externally stored files
     * related to the particular I/H model entry.
     */
    ihm_external_files: {
        /**
         * A unique identifier for each external file.
         */
        id: int,
        /**
         * A pointer to the source of the external file - either DOI or locally stored.
         * This data item is a pointer to _ihm_external_reference_info.reference_id in the
         * IHM_EXTERNAL_REFERENCE_INFO category.
         */
        reference_id: int,
        /**
         * The relative path (including filename) for each external file.
         * Absolute paths (starting with "/") are not permitted.
         * This is required for identifying individual files from within
         * a tar-zipped archive file or for identifying supplementary local
         * files organized within a directory structure.
         * This data item assumes a POSIX-like directory structure or file path.
         */
        file_path: str,
        /**
         * The type of content in the file.
         */
        content_type: Aliased(str),
        /**
         * Storage size of the external file in bytes.
         */
        file_size_bytes: float,
        /**
         * Additional textual details regarding the external file.
         */
        details: str,
    },
    /**
     * Category provides additional details regarding input data hosted externally
     * at other resources.
     */
    ihm_dataset_external_reference: {
        /**
         * A unique identifier for the external data.
         */
        id: int,
        /**
         * Identifier to the dataset list used in the I/H modeling.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * The file id corresponding to this external data file.
         * This data item is a pointer to _ihm_external_files.id
         * in the IHM_EXTERNAL_FILES category.
         */
        file_id: int,
    },
    /**
     * Data items in the IHM_LOCALIZATION_DENSITY_FILES category records the
     * details of files that provide information regarding localization densities
     * of ensembles. These may be stored externally as local files or linked via
     * DOI and can be in any accepted format that provides volume information
     * (CCP4, MRC, etc.).
     */
    ihm_localization_density_files: {
        /**
         * A unique identifier.
         */
        id: int,
        /**
         * The file id for the externally stored localization density file.
         * This data item is a pointer to _ihm_external_files.id
         * in the IHM_EXTERNAL_FILES category.
         */
        file_id: int,
        /**
         * The ensemble identifier for the ensemble, for which the localization density is provided.
         * This data item is a pointer to _ihm_ensemble_info.ensemble_id in the IHM_ENSEMBLE_INFO category.
         */
        ensemble_id: int,
        /**
         * The entity identifier corresponding to this localization density.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The identifier for the polymeric segment corresponding to this
         * localization density.
         * This data item is a pointer to _ihm_entity_poly_segment.id in the
         * IHM_ENTITY_POLY_SEGMENT category.
         */
        entity_poly_segment_id: int,
        /**
         * An asym/strand identifier corresponding to this localization density.
         * This data item is a pointer to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
    },
    /**
     * Data items in the IHM_PREDICTED_CONTACT_RESTRAINT category records the
     * list of predicted contacts used in the integrative modeling experiment.
     * This has been adapted from the widely used CASP RR format
     * (http://www.predictioncenter.org/casp8/index.cgi?page=format#RR).
     * These contacts may be derived from various computational tools.
     * The software information can be provided in the SOFTWARE category.
     */
    ihm_predicted_contact_restraint: {
        /**
         * A unique identifier for the predicted contact restraint.
         */
        id: int,
        /**
         * An identifier to group the predicted contacts.
         */
        group_id: int,
        /**
         * The entity identifier for the first monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category.
         */
        entity_id_1: str,
        /**
         * The entity identifier for the second monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category.
         */
        entity_id_2: str,
        /**
         * An asym/strand identifier for the first monomer partner in the predicted contact.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id_1: str,
        /**
         * An asym/strand identifier for the second monomer partner in the predicted contact.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id_2: str,
        /**
         * The component identifier for the first monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_1: str,
        /**
         * The component identifier for the second monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_2: str,
        /**
         * The sequence index for the first monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_1: int,
        /**
         * The sequence index for the second monomer partner in the predicted contact.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_2: int,
        /**
         * If _ihm_predicted_contact_restraint.model_granularity is by-residue, then indicate the atom
         * used to represent the first monomer partner in three-dimension. Default is the C-alpha atom.
         */
        rep_atom_1: Aliased(str),
        /**
         * If _ihm_predicted_contact_restraint.model_granularity is by-residue, then indicate the atom
         * used to represent the second monomer partner in three-dimension. Default is the C-alpha atom.
         */
        rep_atom_2: Aliased(str),
        /**
         * The lower limit to the distance threshold applied to this predicted contact restraint
         * in the integrative modeling task.
         */
        distance_lower_limit: float,
        /**
         * The upper limit to the distance threshold applied to this predicted contact restraint
         * in the integrative modeling task.
         */
        distance_upper_limit: float,
        /**
         * The real number that indicates the probability that the predicted distance restraint
         * is correct. This number should fall between 0.0 and 1.0.
         */
        probability: float,
        /**
         * The type of distance restraint applied.
         */
        restraint_type: Aliased(str),
        /**
         * The granularity of the predicted contact as applied to the multi-scale model.
         */
        model_granularity: Aliased(str),
        /**
         * Identifier to the predicted contacts dataset.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * Identifier to the software used to obtain the predicted contacts dataset.
         * This data item is a pointer to the _software.pdbx_ordinal in the
         * SOFTWARE category.
         */
        software_id: int,
    },
    /**
     * Data items in the IHM_CROSS_LINK_LIST category records the
     * list of spatial restraints derived from chemical crosslinking
     * experiment.
     */
    ihm_cross_link_list: {
        /**
         * A unique identifier for the cross link restraint.
         */
        id: int,
        /**
         * An identifier for a set of ambiguous crosslink restraints.
         * Handles experimental uncertainties in the identities of
         * crosslinked residues.
         */
        group_id: int,
        /**
         * A text description of molecular entity 1.
         */
        entity_description_1: str,
        /**
         * A text description of molecular entity 2.
         */
        entity_description_2: str,
        /**
         * The entity identifier for the first monomer partner in the cross link
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category.
         */
        entity_id_1: str,
        /**
         * The entity identifier for the second monomer partner in the cross link
         *
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category.
         */
        entity_id_2: str,
        /**
         * The component identifier for the first monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_1: str,
        /**
         * The component identifier for the second monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_2: str,
        /**
         * The sequence index for the first monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_1: int,
        /**
         * The sequence index for the second monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_2: int,
        /**
         * The type of crosslinker used.
         */
        linker_type: Aliased(str),
        /**
         * Identifier to the crosslinking dataset.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
    },
    /**
     * Data items in the IHM_CROSS_LINK_RESTRAINT category enumerates the
     * implementation details of the chemical crosslinking restraints in
     * the integrative modeling. This category holds the details of how
     * the experimentally derived crosslinks are applied in the modeling.
     */
    ihm_cross_link_restraint: {
        /**
         * A unique identifier for the cross link record.
         */
        id: int,
        /**
         * An identifier for a set of ambiguous cross-links.
         * Handles implementation uncertainties related to multiple copies of subunit.
         * This data item is a pointer to _ihm_cross_link_list.id in the
         * IHM_CROSS_LINK_LIST category.
         */
        group_id: int,
        /**
         * The entity identifier for the first monomer partner in the cross link
         *
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.entity_id_1 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        entity_id_1: str,
        /**
         * The entity identifier for the second monomer partner in the cross link
         *
         * This data item is a pointer to _entity_poly_seq.entity_id in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.entity_id_2 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        entity_id_2: str,
        /**
         * An asym/strand identifier for the first monomer partner in the cross-link.
         *
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id_1: str,
        /**
         * An asym/strand identifier for the second monomer partner in the cross-link.
         *
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id_2: str,
        /**
         * The component identifier for the first monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.comp_id_1 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        comp_id_1: str,
        /**
         * The component identifier for the second monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.comp_id_2 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        comp_id_2: str,
        /**
         * The sequence index for the first monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.seq_id_1 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        seq_id_1: int,
        /**
         * The sequence index for the second monomer partner in the cross link.
         *
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category
         * and the _ihm_cross_link_restraint.seq_id_2 in the IHM_CROSS_LINK_RESTRAINT category.
         */
        seq_id_2: int,
        /**
         * The atom identifier for the first monomer partner in the cross link.
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_1: str,
        /**
         * The atom identifier for the second monomer partner in the cross link.
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id_2: str,
        /**
         * The type of the cross link restraint applied.
         */
        restraint_type: Aliased(str),
        /**
         * The cross link conditionality.
         */
        conditional_crosslink_flag: Aliased(str),
        /**
         * The coarse-graining information for the crosslink implementation.
         */
        model_granularity: Aliased(str),
        /**
         * The distance threshold applied to this crosslink in the integrative modeling task.
         */
        distance_threshold: float,
        /**
         * The uncertainty in the crosslinking experimental data;
         * may be approximated to the false positive rate.
         */
        psi: float,
        /**
         * The uncertainty in the position of residue 1 in the crosslink
         * arising due to the multi-scale nature of the model represention.
         */
        sigma_1: float,
        /**
         * The uncertainty in the position of residue 2 in the crosslink
         * arising due to the multi-scale nature of the model represention.
         */
        sigma_2: float,
    },
    /**
     * Data items in the IHM_CROSS_LINK_RESULT_PARAMETERS category records the
     * results of the crosslinking restraint parameters in the IHM modeling.
     */
    ihm_cross_link_result_parameters: {
        /**
         * A unique identifier for the restraint/model combination.
         */
        id: int,
        /**
         * An identifier for the crosslink restraint between a pair of residues.
         * This data item is a pointer to _ihm_cross_link_restraint.id in the
         * IHM_CROSS_LINK_RESTRAINT category.
         */
        restraint_id: int,
        /**
         * The model number corresponding to the cross link result presented.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * The uncertainty in the crosslinking experimental data;
         * May be approximated to the false positive rate.
         */
        psi: float,
        /**
         * The uncertainty in the position of residue 1 in the crosslink
         * arising due to the multi-scale nature of the model represention.
         */
        sigma_1: float,
        /**
         * The uncertainty in the position of residue 2 in the crosslink
         * arising due to the multi-scale nature of the model represention.
         */
        sigma_2: float,
    },
    /**
     * Data items in the IHM_2DEM_CLASS_AVERAGE_RESTRAINT category records the
     * details of the 2DEM class averages used in the IHM modeling.
     */
    ihm_2dem_class_average_restraint: {
        /**
         * A unique identifier for the 2dem class average.
         */
        id: int,
        /**
         * Identifier to the 2dem class average dataset.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * The number of raw micrographs used to obtain the class average.
         */
        number_raw_micrographs: int,
        /**
         * Pixel size width of the 2dem class average image.
         * While fitting the model to the image, _ihm_2dem_class_average_restraint.pixel_size_width
         * is used along with _ihm_2dem_class_average_restraint.pixel_size_height to scale the image.
         */
        pixel_size_width: float,
        /**
         * Pixel size height of the 2dem class average image.
         * While fitting the model to the image, _ihm_2dem_class_average_restraint.pixel_size_height
         * is used along with _ihm_2dem_class_average_restraint.pixel_size_width to scale the image.
         */
        pixel_size_height: float,
        /**
         * Resolution of the 2dem class average.
         */
        image_resolution: float,
        /**
         * A flag that indicates whether or not the 2DEM class average image is segmented i.e.,
         * whether the whole image is used or only a portion of it is used (by masking
         * or by other means) as restraint in the modeling.
         */
        image_segment_flag: Aliased(str),
        /**
         * Number of 2D projections of the model used in the fitting.
         */
        number_of_projections: int,
        /**
         * An indicator to whether the whole assembly that is modeled is fit into the image
         * or if only a subset of the structural assembly is fit into the image.
         * This data item is a pointer to _ihm_struct_assembly.id in the
         * IHM_STRUCT_ASSEMBLY category. The IHM_STRUCT_ASSEMBLY category provides the
         * details regarding the different structural assemblies used in the modeling.
         * The default value for this data item is "1" indicating that the entire assembly
         * being modeled is fit into the EM data.
         */
        struct_assembly_id: int,
        /**
         * Details of how the 2DEM restraint is applied in the modeling algorithm.
         */
        details: str,
    },
    /**
     * Data items in the IHM_2DEM_CLASS_AVERAGE_FITTING category records the
     * details of the fitting of the model to the 2DEM class averages
     * used in the IHM modeling. The following conventions are recommended
     * while generating the rotation matrix and translation vector for
     * transformation.
     *
     * - The model is rotated and translated to fit to the 2DEM image.
     * - The 2DEM image should be in the XY plane.
     * - The lower left image corner (image pixel index 0,0) should be at x,y,z = (0,0,0).
     * - The 2D image is scaled by the _ihm_2dem_class_average_restraint.pixel_size_width
     * and _ihm_2dem_class_average_restraint.pixel_size_height from the
     * IHM_2DEM_CLASS_AVERAGE_RESTRAINT table.
     * - The transformation is applied after the scaling and hence the translation vector
     * should account for the scaling.
     * - There are no specifications for Z translations i.e., how far the image should be
     * from the model while projecting. It may be set to zero.
     */
    ihm_2dem_class_average_fitting: {
        /**
         * A unique identifier for the 2dem class average fitting data.
         */
        id: int,
        /**
         * Identifier to the 2dem class average restraint.
         * This data item is a pointer to the _ihm_2dem_class_average_restraint.id in the
         * IHM_2DEM_CLASS_AVERAGE_RESTRAINT category.
         */
        restraint_id: int,
        /**
         * The model number corresponding to the 2DEM fitting result presented.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * The cross correlation coefficient corresponding to the model to image fitting.
         */
        cross_correlation_coefficient: float,
        /**
         * Data item  of the rotation matrix used in the fitting of the model to the image.
         */
        rot_matrix: Matrix(3, 3),
        /**
         * Data item  of the tranlation vector used in the fitting of the model to the image.
         */
        tr_vector: Vector(3),
    },
    /**
     * Data items in the IHM_3DEM_RESTRAINT category records the
     * details of the 3DEM maps used as restraints in the
     * IHM modeling.
     */
    ihm_3dem_restraint: {
        /**
         * A unique identifier for the 3DEM restraint description.
         */
        id: int,
        /**
         * Identifier to the 3DEM map used.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * The model number corresponding to the 3DEM fitting result presented.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * An indicator to whether the whole assembly that is modeled is fit into the 3DEM map
         * or if only a subset of the structural assembly is fit into the map.
         * This data item is a pointer to _ihm_struct_assembly.id in the
         * IHM_STRUCT_ASSEMBLY category. The IHM_STRUCT_ASSEMBLY category provides the
         * details regarding the different structural assemblies used in the modeling.
         * The default value for this data item is "1" indicating that the entire assembly
         * being modeled is fit into the EM map.
         */
        struct_assembly_id: int,
        /**
         * Method used to fit the model to the 3DEM map.
         */
        fitting_method: str,
        /**
         * In case of Gaussian mixture models, the number of gaussians
         * is a parameter used to covert the 3DEM maps and models into
         * GMMs. This captures the level of granularity used in
         * representing the maps and/or models as 3D Gaussians.
         */
        number_of_gaussians: int,
        /**
         * The cross correlation coefficient corresponding to the model to map fitting.
         */
        cross_correlation_coefficient: float,
    },
    /**
     * Data items in the IHM_SAS_RESTRAINT category records the
     * details of the SAS data used as restraints in the
     * IHM modeling.
     */
    ihm_sas_restraint: {
        /**
         * A unique identifier for the SAS restraint description.
         */
        id: int,
        /**
         * Identifier to the SAS data used.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         */
        dataset_list_id: int,
        /**
         * The model number corresponding to the SAS fitting result presented.
         * This data item is a pointer to _ihm_model_list.model_id in the
         * IHM_MODEL_LIST category.
         */
        model_id: int,
        /**
         * An indicator to whether the whole assembly that is modeled is fit into the SAS data
         * or if only a subset of the structural assembly is fit into the data.
         * This data item is a pointer to _ihm_struct_assembly.id in the
         * IHM_STRUCT_ASSEMBLY category. The IHM_STRUCT_ASSEMBLY category provides the
         * details regarding the different structural assemblies used in the modeling.
         * The default value for this data item is "1" indicating that the entire assembly
         * being modeled is fit into the SAS data.
         */
        struct_assembly_id: int,
        /**
         * A flag that indicates whether or not the SAS profile is segmented i.e.,
         * whether the whole SAS profile is used or only a portion of it is used
         * (by masking or by other means) as restraint in the modeling.
         */
        profile_segment_flag: Aliased(str),
        /**
         * The type of atoms in the model fit to the SAS data.
         */
        fitting_atom_type: str,
        /**
         * The method used for fitting the model to the SAS data.
         */
        fitting_method: str,
        /**
         * An indicator to single or multiple state fitting.
         */
        fitting_state: Aliased(str),
        /**
         * Radius of gyration obtained from the SAS profile, if used as input restraint.
         */
        radius_of_gyration: float,
        /**
         * The chi value resulting from fitting the model to the SAS data.
         */
        chi_value: float,
        /**
         * Additional details regarding the SAS restraint used.
         */
        details: str,
    },
    /**
     * Data items in the IHM_STARTING_MODEL_COORD category records the coordinates
     * for structural templates used as starting inputs in the integrative model
     * building tasks.
     */
    ihm_starting_model_coord: {
        /**
         * A unique identifier for this coordinate position.
         */
        ordinal_id: int,
        /**
         * The identifier for the starting structural model.
         * This data item is a pointer to _ihm_starting_model_details.starting_model_id
         * in the IHM_STARTING_MODEL_DETAILS category.
         */
        starting_model_id: str,
        /**
         * The group of atoms to which the atom site in the starting model belongs. This data
         * item is provided for compatibility with the original Protein Data Bank format,
         * and only for that purpose.
         */
        group_PDB: Aliased(str),
        /**
         * The serial number for this coordinate position.
         */
        id: int,
        /**
         * The atom type symbol(element symbol) corresponding to this coordinate position.
         */
        type_symbol: str,
        /**
         * The entity identifier corresponding to this coordinate position.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The atom identifier/name corresponding to this coordinate position.
         * This data item is a pointer to _chem_comp_atom.atom_id in the
         * CHEM_COMP_ATOM category.
         */
        atom_id: str,
        /**
         * The component identifier corresponding to this coordinate position.
         * This data item is a pointer to _chem_comp.id in the
         * CHEM_COMP category.
         */
        comp_id: str,
        /**
         * The sequence index corresponding this to coordinate position.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id: int,
        /**
         * The asym/strand id corresponding to this coordinate position.
         *
         * This data item is a pointer to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The Cartesian X component corresponding to this coordinate position.
         */
        Cartn_x: float,
        /**
         * The Cartesian Y component corresponding to this coordinate position.
         */
        Cartn_y: float,
        /**
         * The Cartesian Z component corresponding to this coordinate position.
         */
        Cartn_z: float,
        /**
         * The isotropic temperature factor corresponding to this coordinate position.
         */
        B_iso_or_equiv: float,
    },
    /**
     * Data items in the IHM_SPHERE_OBJ_SITE category records the details
     * of the spherical objects modeled in the integrative structural model.
     */
    ihm_sphere_obj_site: {
        /**
         * A unique identifier for this pseudo atom / sphere object.
         */
        id: int,
        /**
         * The entity identifier corresponding to this sphere object.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The leading sequence index corresponding to this sphere object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_begin: int,
        /**
         * The trailing sequence index corresponding to this sphere object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_end: int,
        /**
         * An asym/strand identifier corresponding to this sphere object.
         * This data item is a pointer to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The Cartesian X component corresponding to this sphere object.
         */
        Cartn_x: float,
        /**
         * The Cartesian Y component corresponding to this sphere object.
         */
        Cartn_y: float,
        /**
         * The Cartesian Z component corresponding to this sphere object.
         */
        Cartn_z: float,
        /**
         * The radius associated with the primitive sphere object at this position.
         */
        object_radius: float,
        /**
         * The Root Mean Square Fluctuation (RMSF) observed in the primitive
         * sphere object at this position.
         */
        rmsf: float,
        /**
         * The model id corresponding to the sphere object.
         * This data item is a pointer to _ihm_model_list.model_id
         * in the IHM_MODEL_LIST category.
         */
        model_id: int,
    },
    /**
     * Data items in the IHM_GAUSSIAN_OBJ_SITE category records the details
     * of the gaussian objects modeled in the integrative structural model.
     */
    ihm_gaussian_obj_site: {
        /**
         * A unique identifier for this gaussian object in the model.
         */
        id: int,
        /**
         * The entity identifier corresponding to this gaussian object.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The leading sequence index corresponding to this gaussian object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_begin: int,
        /**
         * The trailing sequence index corresponding to this gaussian object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_end: int,
        /**
         * An asym/strand identifier corresponding to this gaussian object.
         * This data item is a pointer to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The mean Cartesian X component corresponding to this gaussian object.
         */
        mean_Cartn_x: float,
        /**
         * The mean Cartesian Y component corresponding to this gaussian object.
         */
        mean_Cartn_y: float,
        /**
         * The mean Cartesian Z component corresponding to this gaussian object.
         */
        mean_Cartn_z: float,
        /**
         * The weight of the gaussian object.
         */
        weight: float,
        /**
         * Data item  of the covariance matrix representing the Gaussian object.
         */
        covariance_matrix: Matrix(3, 3),
        /**
         * The model id corresponding to the gaussian object.
         * This data item is a pointer to _ihm_model_list.model_id
         * in the IHM_MODEL_LIST category.
         */
        model_id: int,
    },
    /**
     * Data items in the IHM_GAUSSIAN_OBJ_ENSEMBLE category records the details
     * of the gaussian objects representing an ensemble or cluster of models.
     */
    ihm_gaussian_obj_ensemble: {
        /**
         * A unique identifier for this gaussian object.
         */
        id: int,
        /**
         * The entity identifier corresponding to this gaussian object.
         * This data item is a pointer to _entity.id in the ENTITY category.
         */
        entity_id: str,
        /**
         * The leading sequence index corresponding to this gaussian object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_begin: int,
        /**
         * The trailing sequence index corresponding to this gaussian object.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_end: int,
        /**
         * An asym/strand identifier corresponding to this gaussian object.
         * This data item is a pointer to _struct_asym.id in the STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The mean Cartesian X component corresponding to this gaussian object.
         */
        mean_Cartn_x: float,
        /**
         * The mean Cartesian Y component corresponding to this gaussian object.
         */
        mean_Cartn_y: float,
        /**
         * The mean Cartesian Z component corresponding to this gaussian object.
         */
        mean_Cartn_z: float,
        /**
         * The weight of the gaussian object.
         */
        weight: float,
        /**
         * Data item  of the covariance matrix representing the Gaussian object.
         */
        covariance_matrix: Matrix(3, 3),
        /**
         * The ensemble id corresponding to the gaussian object.
         * This data item is a pointer to _ihm_ensemble_info.ensemble_id
         * in the IHM_ENSEMBLE_INFO category.
         */
        ensemble_id: int,
    },
    /**
     * IHM_FEATURE_LIST is the high level category that provides defintions
     * to select atoms/residues from polymeric and non-polymeric entities.
     */
    ihm_feature_list: {
        /**
         * A unique identifier for the feature.
         */
        feature_id: int,
        /**
         * The type of feature.
         */
        feature_type: Aliased(str),
        /**
         * The type of entity.
         */
        entity_type: Aliased(str),
    },
    /**
     * Data items in the IHM_POLY_RESIDUE_FEATURE category provides the defintions
     * required to select a specific residue or a set of residues that may or may not be
     * in a contiguous range.
     */
    ihm_poly_residue_feature: {
        /**
         * A unique identifier for the category.
         */
        ordinal_id: int,
        /**
         * An identifier for the selected residue / residue range feature.
         * This data item is a pointer to _ihm_feature_list.feature_id in the
         * IHM_FEATURE_LIST category.
         */
        feature_id: int,
        /**
         * The entity identifier for residue / residue range.
         * This data item is a pointer to _entity_poly_seq.entity_id in the
         * ENTITY_POLY_SEQ category.
         */
        entity_id: str,
        /**
         * An asym/strand identifier for the residue / residue range, if applicable.
         * This data item is a pointer to _struct_asym.id in the
         * STRUCT_ASYM category.
         */
        asym_id: str,
        /**
         * The component identifier of the beginning residue / residue range.
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_begin: str,
        /**
         * The component identifier of the ending residue / residue range.
         * This data item is a pointer to _entity_poly_seq.mon_id in the ENTITY_POLY_SEQ category.
         */
        comp_id_end: str,
        /**
         * The sequence index of the beginning residue / residue range.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_begin: int,
        /**
         * The sequence index of the ending residue / residue range.
         * This data item is a pointer to _entity_poly_seq.num in the ENTITY_POLY_SEQ category.
         */
        seq_id_end: int,
    },
    /**
     * Data items in the IHM_DERIVED_DISTANCE_RESTRAINT category records the
     * list of distance restraints used in the integrative modeling experiment.
     * These distance redistance restraints may be derived from various kinds of experiments.
     */
    ihm_derived_distance_restraint: {
        /**
         * A unique identifier for the derived distance restraint.
         */
        id: int,
        /**
         * An identifier to group the distance restraints.
         * This can be the same as the _ihm_derived_distance_restraint.id in case
         * the some of the restraints are not grouped.
         */
        group_id: int,
        /**
         * The feature identifier for the first partner in the distance restraint.
         * This data item is a pointer to _ihm_feature_list.feature_id in the
         * IHM_FEATURE_LIST category.
         */
        feature_id_1: int,
        /**
         * The feature identifier for the second partner in the distance restraint.
         * This data item is a pointer to _ihm_feature_list.feature_id in the
         * IHM_FEATURE_LIST category.
         */
        feature_id_2: int,
        /**
         * If a group of atoms or residues are restrained, this data item defines
         * the conditionality based on which the restraint is applied in the modeling.
         */
        group_conditionality: Aliased(str),
        /**
         * The fraction of randomly excluded distance restraints during modeling.
         * In HADDOCK, this is used along with ambiguous interface restraints (AIRs)
         * to account for uncertainties in AIRs.
         */
        random_exclusion_fraction: float,
        /**
         * The upper limit to the distance threshold applied to this distance restraint
         * in the integrative modeling task.
         */
        distance_upper_limit: float,
        /**
         * The type of distance restraint applied.
         */
        restraint_type: Aliased(str),
        /**
         * Identifier to the input data from which the distance restraint is derived.
         * This data item is a pointer to the _ihm_dataset_list.id in the
         * IHM_DATASET_LIST category.
         * This data item may not be applicable for all cases. For example, in case of
         * ambiguous interface restraints where the interface residues are identified
         * from multiple experiments, the reference to the _ihm_dataset_list.id is
         * handled in the IHM_INTERFACE_RESIDUE_FEATURE category rather than here.
         */
        dataset_list_id: int,
    },
    /**
     * PDBX_CHEM_COMP_RELATED describes the relationship between two chemical components.
     */
    pdbx_chem_comp_related: {
        /**
         * The chemical component for which this relationship applies.
         */
        comp_id: str,
        /**
         * The related chemical component for which this chemical component is based.
         */
        related_comp_id: str,
        /**
         * Describes the type of relationship
         */
        relationship_type: Aliased(str),
        /**
         * Describes the type of relationship
         */
        details: str,
    },
};
;
//# sourceMappingURL=mmcif.js.map

/***/ }),
/* 58 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ValueRef; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ValueBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ValueCell; });
/* harmony import */ var _id_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var ValueRef;
(function (ValueRef) {
    function create(ref) { return { ref: ref }; }
    ValueRef.create = create;
    function set(ref, value) { ref.ref = value; return ref; }
    ValueRef.set = set;
})(ValueRef || (ValueRef = {}));
var getNextId = Object(_id_factory__WEBPACK_IMPORTED_MODULE_0__[/* idFactory */ "a"])(0, 0x7FFFFFFF);
var ValueBox;
(function (ValueBox) {
    function create(value, metadata) {
        return { id: getNextId(), version: 0, value: value, metadata: metadata };
    }
    ValueBox.create = create;
    /** The box.metadata is carried over from the old box */
    function withValue(box, value) {
        return { id: box.id, version: box.version + 1, value: value, metadata: box.metadata };
    }
    ValueBox.withValue = withValue;
})(ValueBox || (ValueBox = {}));
var ValueCell;
(function (ValueCell) {
    function create(value, metadata) {
        return ValueRef.create(ValueBox.create(value, metadata));
    }
    ValueCell.create = create;
    /** The box.metadata is carried over from the old box */
    function update(cell, value) {
        return ValueRef.set(cell, ValueBox.withValue(cell.ref, value));
    }
    ValueCell.update = update;
    function set(cell, box) {
        return ValueRef.set(cell, box);
    }
    ValueCell.set = set;
    /** Updates the cell if the value is has changed, comparing by reference */
    function updateIfChanged(cell, value) {
        return cell.ref.value !== value ? update(cell, value) : cell;
    }
    ValueCell.updateIfChanged = updateIfChanged;
})(ValueCell || (ValueCell = {}));

//# sourceMappingURL=value-cell.js.map

/***/ }),
/* 59 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Binding; });
/* harmony import */ var _input_input_observer__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(84);
/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(41);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function Binding(triggers, action, description) {
    if (action === void 0) { action = ''; }
    if (description === void 0) { description = ''; }
    return Binding.create(triggers, action, description);
}
(function (Binding) {
    function create(triggers, action, description) {
        if (action === void 0) { action = ''; }
        if (description === void 0) { description = ''; }
        return { triggers: triggers, action: action, description: description };
    }
    Binding.create = create;
    Binding.Empty = { triggers: [], action: '', description: '' };
    function isEmpty(binding) {
        return binding.triggers.length === 0 ||
            binding.triggers.every(function (t) { return t.buttons === undefined && t.modifiers === undefined; });
    }
    Binding.isEmpty = isEmpty;
    function match(binding, buttons, modifiers) {
        return binding.triggers.some(function (t) { return Trigger.match(t, buttons, modifiers); });
    }
    Binding.match = match;
    function formatTriggers(binding) {
        return binding.triggers.map(Trigger.format).join(' or ');
    }
    Binding.formatTriggers = formatTriggers;
    function format(binding, name) {
        if (name === void 0) { name = ''; }
        var help = binding.description || Object(_string__WEBPACK_IMPORTED_MODULE_1__[/* stringToWords */ "d"])(name);
        return Object(_string__WEBPACK_IMPORTED_MODULE_1__[/* interpolate */ "c"])(help, { triggers: '<i>' + formatTriggers(binding) + '</i>' });
    }
    Binding.format = format;
    function Trigger(buttons, modifiers) {
        return Trigger.create(buttons, modifiers);
    }
    Binding.Trigger = Trigger;
    (function (Trigger) {
        function create(buttons, modifiers) {
            return { buttons: buttons, modifiers: modifiers };
        }
        Trigger.create = create;
        Trigger.Empty = {};
        function match(trigger, buttons, modifiers) {
            var b = trigger.buttons, m = trigger.modifiers;
            return b !== undefined &&
                (b === buttons || _input_input_observer__WEBPACK_IMPORTED_MODULE_0__[/* ButtonsType */ "a"].has(b, buttons)) &&
                (!m || _input_input_observer__WEBPACK_IMPORTED_MODULE_0__[/* ModifiersKeys */ "b"].areEqual(m, modifiers));
        }
        Trigger.match = match;
        function format(trigger) {
            var s = [];
            var b = formatButtons(trigger.buttons);
            if (b)
                s.push(b);
            var m = formatModifiers(trigger.modifiers);
            if (m)
                s.push(m);
            return s.join(' + ');
        }
        Trigger.format = format;
    })(Trigger = Binding.Trigger || (Binding.Trigger = {}));
})(Binding || (Binding = {}));
var B = _input_input_observer__WEBPACK_IMPORTED_MODULE_0__[/* ButtonsType */ "a"];
function formatButtons(buttons) {
    var s = [];
    if (buttons === undefined) {
        s.push('any mouse button');
    }
    else if (buttons === 0) {
        s.push('mouse hover');
    }
    else {
        if (B.has(buttons, 1 /* Primary */))
            s.push('left mouse button');
        if (B.has(buttons, 2 /* Secondary */))
            s.push('right mouse button');
        if (B.has(buttons, 4 /* Auxilary */))
            s.push('wheel/middle mouse button');
        if (B.has(buttons, 8 /* Forth */))
            s.push('three fingers');
    }
    return s.join(' + ');
}
function formatModifiers(modifiers, verbose) {
    var s = [];
    if (modifiers) {
        if (modifiers.alt)
            s.push('alt key');
        if (modifiers.control)
            s.push('control key');
        if (modifiers.meta)
            s.push('meta/command key');
        if (modifiers.shift)
            s.push('shift key');
        if (verbose && s.length === 0)
            s.push('no key');
    }
    else {
        if (verbose)
            s.push('any key');
    }
    return s.join(' + ');
}
//# sourceMappingURL=binding.js.map

/***/ }),
/* 60 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SubjectSubscriber; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subject; });
/* unused harmony export AnonymousSubject */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(44);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(35);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(208);
/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(353);
/* harmony import */ var _internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(277);
/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */







var SubjectSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](SubjectSubscriber, _super);
    function SubjectSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        return _this;
    }
    return SubjectSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_2__[/* Subscriber */ "a"]));

var Subject = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](Subject, _super);
    function Subject() {
        var _this = _super.call(this) || this;
        _this.observers = [];
        _this.closed = false;
        _this.isStopped = false;
        _this.hasError = false;
        _this.thrownError = null;
        return _this;
    }
    Subject.prototype[_internal_symbol_rxSubscriber__WEBPACK_IMPORTED_MODULE_6__[/* rxSubscriber */ "a"]] = function () {
        return new SubjectSubscriber(this);
    };
    Subject.prototype.lift = function (operator) {
        var subject = new AnonymousSubject(this, this);
        subject.operator = operator;
        return subject;
    };
    Subject.prototype.next = function (value) {
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__[/* ObjectUnsubscribedError */ "a"]();
        }
        if (!this.isStopped) {
            var observers = this.observers;
            var len = observers.length;
            var copy = observers.slice();
            for (var i = 0; i < len; i++) {
                copy[i].next(value);
            }
        }
    };
    Subject.prototype.error = function (err) {
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__[/* ObjectUnsubscribedError */ "a"]();
        }
        this.hasError = true;
        this.thrownError = err;
        this.isStopped = true;
        var observers = this.observers;
        var len = observers.length;
        var copy = observers.slice();
        for (var i = 0; i < len; i++) {
            copy[i].error(err);
        }
        this.observers.length = 0;
    };
    Subject.prototype.complete = function () {
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__[/* ObjectUnsubscribedError */ "a"]();
        }
        this.isStopped = true;
        var observers = this.observers;
        var len = observers.length;
        var copy = observers.slice();
        for (var i = 0; i < len; i++) {
            copy[i].complete();
        }
        this.observers.length = 0;
    };
    Subject.prototype.unsubscribe = function () {
        this.isStopped = true;
        this.closed = true;
        this.observers = null;
    };
    Subject.prototype._trySubscribe = function (subscriber) {
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__[/* ObjectUnsubscribedError */ "a"]();
        }
        else {
            return _super.prototype._trySubscribe.call(this, subscriber);
        }
    };
    Subject.prototype._subscribe = function (subscriber) {
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_4__[/* ObjectUnsubscribedError */ "a"]();
        }
        else if (this.hasError) {
            subscriber.error(this.thrownError);
            return _Subscription__WEBPACK_IMPORTED_MODULE_3__[/* Subscription */ "a"].EMPTY;
        }
        else if (this.isStopped) {
            subscriber.complete();
            return _Subscription__WEBPACK_IMPORTED_MODULE_3__[/* Subscription */ "a"].EMPTY;
        }
        else {
            this.observers.push(subscriber);
            return new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_5__[/* SubjectSubscription */ "a"](this, subscriber);
        }
    };
    Subject.prototype.asObservable = function () {
        var observable = new _Observable__WEBPACK_IMPORTED_MODULE_1__[/* Observable */ "a"]();
        observable.source = this;
        return observable;
    };
    Subject.create = function (destination, source) {
        return new AnonymousSubject(destination, source);
    };
    return Subject;
}(_Observable__WEBPACK_IMPORTED_MODULE_1__[/* Observable */ "a"]));

var AnonymousSubject = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](AnonymousSubject, _super);
    function AnonymousSubject(destination, source) {
        var _this = _super.call(this) || this;
        _this.destination = destination;
        _this.source = source;
        return _this;
    }
    AnonymousSubject.prototype.next = function (value) {
        var destination = this.destination;
        if (destination && destination.next) {
            destination.next(value);
        }
    };
    AnonymousSubject.prototype.error = function (err) {
        var destination = this.destination;
        if (destination && destination.error) {
            this.destination.error(err);
        }
    };
    AnonymousSubject.prototype.complete = function () {
        var destination = this.destination;
        if (destination && destination.complete) {
            this.destination.complete();
        }
    };
    AnonymousSubject.prototype._subscribe = function (subscriber) {
        var source = this.source;
        if (source) {
            return this.source.subscribe(subscriber);
        }
        else {
            return _Subscription__WEBPACK_IMPORTED_MODULE_3__[/* Subscription */ "a"].EMPTY;
        }
    };
    return AnonymousSubject;
}(Subject));

//# sourceMappingURL=Subject.js.map


/***/ }),
/* 61 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isProductionMode; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isDebugMode; });
/* unused harmony export setProductionMode */
/* unused harmony export setDebugMode */
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * on node `process.env.NODE_ENV` is available, in webpack build it is automatically set
 * by the DefinePlugin to the webpack `mode` value
 */
var isProductionMode = "production" === 'production';
/**
 * set to true to enable more comprehensive checks and assertions,
 * mostly used in `mol-gl` and in valence-model calculation
 */
var isDebugMode = undefined === '*' || undefined === 'molstar';

function setProductionMode(value) {
    if (typeof value !== 'undefined')
        isProductionMode = value;
}
function setDebugMode(value) {
    if (typeof value !== 'undefined')
        isDebugMode = value;
}
//# sourceMappingURL=debug.js.map

/***/ }),
/* 62 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ cif_CifWriter; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string-builder.js
var string_builder = __webpack_require__(106);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/iterator.js
var iterator = __webpack_require__(290);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif.js + 1 modules
var binary_cif = __webpack_require__(121);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/writer/cif/encoder.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var encoder_Field;
(function (Field) {
    function str(name, value, params) {
        return { name: name, type: 0 /* Str */, value: value, valueKind: params && params.valueKind, defaultFormat: params && params.encoder ? { encoder: params.encoder } : void 0, shouldInclude: params && params.shouldInclude };
    }
    Field.str = str;
    function int(name, value, params) {
        return {
            name: name,
            type: 1 /* Int */,
            value: value,
            valueKind: params && params.valueKind,
            defaultFormat: params ? { encoder: params.encoder, typedArray: params.typedArray } : void 0,
            shouldInclude: params && params.shouldInclude
        };
    }
    Field.int = int;
    function float(name, value, params) {
        return {
            name: name,
            type: 2 /* Float */,
            value: value,
            valueKind: params && params.valueKind,
            defaultFormat: params ? { encoder: params.encoder, typedArray: params.typedArray, digitCount: typeof params.digitCount !== 'undefined' ? params.digitCount : void 0 } : void 0,
            shouldInclude: params && params.shouldInclude
        };
    }
    Field.float = float;
    function index(name) {
        return int(name, function (e, d, i) { return i + 1; }, { typedArray: Int32Array, encoder: binary_cif["b" /* ArrayEncoding */].by(binary_cif["b" /* ArrayEncoding */].delta).and(binary_cif["b" /* ArrayEncoding */].runLength).and(binary_cif["b" /* ArrayEncoding */].integerPacking) });
    }
    Field.index = index;
    var Builder = /** @class */ (function () {
        function Builder() {
            this.fields = [];
        }
        Builder.prototype.index = function (name) {
            this.fields.push(Field.index(name));
            return this;
        };
        Builder.prototype.str = function (name, value, params) {
            this.fields.push(Field.str(name, value, params));
            return this;
        };
        Builder.prototype.int = function (name, value, params) {
            this.fields.push(Field.int(name, value, params));
            return this;
        };
        Builder.prototype.vec = function (name, values, params) {
            for (var i = 0; i < values.length; i++) {
                this.fields.push(Field.int(name + "[" + (i + 1) + "]", values[i], params));
            }
            return this;
        };
        Builder.prototype.float = function (name, value, params) {
            this.fields.push(Field.float(name, value, params));
            return this;
        };
        Builder.prototype.many = function (fields) {
            for (var i = 0; i < fields.length; i++)
                this.fields.push(fields[i]);
            return this;
        };
        Builder.prototype.add = function (field) {
            this.fields.push(field);
            return this;
        };
        Builder.prototype.getFields = function () { return this.fields; };
        return Builder;
    }());
    Field.Builder = Builder;
    function build() {
        return new Builder();
    }
    Field.build = build;
})(encoder_Field || (encoder_Field = {}));
var encoder_Category;
(function (Category) {
    Category.Empty = { fields: [], source: [] };
    function filterOf(directives) {
        var cat_whitelist = [];
        var cat_blacklist = [];
        var field_whitelist = [];
        var field_blacklist = [];
        for (var _i = 0, _a = directives.split(/[\r\n]+/); _i < _a.length; _i++) {
            var d = _a[_i];
            d = d.trim();
            // allow for empty lines in config
            if (d.length === 0)
                continue;
            // let ! denote blacklisted entries
            var blacklist = /^!/.test(d);
            if (blacklist)
                d = d.substr(1);
            var split = d.split(/\./);
            var field = split[1];
            var list = blacklist ? (field ? field_blacklist : cat_blacklist) : (field ? field_whitelist : cat_whitelist);
            list[list.length] = d;
            // ensure categories are aware about whitelisted columns
            if (field && !cat_whitelist.includes(split[0])) {
                cat_whitelist[cat_whitelist.length] = split[0];
            }
        }
        var wlcatcol = field_whitelist.map(function (it) { return it.split('.')[0]; });
        // blacklist has higher priority
        return {
            includeCategory: function (cat) {
                // block if category in black
                if (cat_blacklist.includes(cat)) {
                    return false;
                }
                else {
                    // if there is a whitelist, the category has to be explicitly allowed
                    return cat_whitelist.length <= 0 ||
                        // otherwise include if whitelist contains category
                        cat_whitelist.indexOf(cat) !== -1;
                }
            },
            includeField: function (cat, field) {
                // column names are assumed to follow the pattern 'category_name.column_name'
                var full = cat + '.' + field;
                if (field_blacklist.includes(full)) {
                    return false;
                }
                else {
                    // if for this category no whitelist entries exist
                    return !wlcatcol.includes(cat) ||
                        // otherwise must be specifically allowed
                        field_whitelist.includes(full);
                }
            }
        };
    }
    Category.filterOf = filterOf;
    Category.DefaultFilter = {
        includeCategory: function (cat) { return true; },
        includeField: function (cat, field) { return true; }
    };
    Category.DefaultFormatter = {
        getFormat: function (cat, field) { return void 0; }
    };
    function ofTable(table, indices) {
        if (indices) {
            return {
                fields: cifFieldsFromTableSchema(table._schema),
                source: [{ data: table, rowCount: indices.length, keys: function () { return iterator["a" /* default */].Array(indices); } }]
            };
        }
        return {
            fields: cifFieldsFromTableSchema(table._schema),
            source: [{ data: table, rowCount: table._rowCount }]
        };
    }
    Category.ofTable = ofTable;
})(encoder_Category || (encoder_Category = {}));
var Encoder;
(function (Encoder) {
    function writeDatabase(encoder, name, database) {
        encoder.startDataBlock(name);
        var _loop_1 = function (table) {
            encoder.writeCategory({ name: table, instance: function () { return encoder_Category.ofTable(database[table]); } });
        };
        for (var _i = 0, _a = database._tableNames; _i < _a.length; _i++) {
            var table = _a[_i];
            _loop_1(table);
        }
    }
    Encoder.writeDatabase = writeDatabase;
    function writeDatabaseCollection(encoder, collection) {
        for (var _i = 0, _a = Object.keys(collection); _i < _a.length; _i++) {
            var name_1 = _a[_i];
            writeDatabase(encoder, name_1, collection[name_1]);
        }
    }
    Encoder.writeDatabaseCollection = writeDatabaseCollection;
})(Encoder || (Encoder = {}));
function columnValue(k) {
    return function (i, d) { return d[k].value(i); };
}
function columnListValue(k) {
    return function (i, d) { return d[k].value(i).join(d[k].schema.separator); };
}
function columnTensorValue(k) {
    var coords = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        coords[_i - 1] = arguments[_i];
    }
    return function (i, d) {
        var _a;
        return (_a = d[k].schema.space).get.apply(_a, Object(tslib_es6["__spreadArrays"])([d[k].value(i)], coords));
    };
}
function columnValueKind(k) {
    return function (i, d) { return d[k].valueKind(i); };
}
function getTensorDefinitions(field, space) {
    var fieldDefinitions = [];
    var type = 2 /* Float */;
    var valueKind = columnValueKind(field);
    if (space.rank === 1) {
        var rows = space.dimensions[0];
        for (var i = 0; i < rows; i++) {
            var name_2 = field + "[" + (i + 1) + "]";
            fieldDefinitions.push({ name: name_2, type: type, value: columnTensorValue(field, i), valueKind: valueKind });
        }
    }
    else if (space.rank === 2) {
        var rows = space.dimensions[0], cols = space.dimensions[1];
        for (var i = 0; i < rows; i++) {
            for (var j = 0; j < cols; j++) {
                var name_3 = field + "[" + (i + 1) + "][" + (j + 1) + "]";
                fieldDefinitions.push({ name: name_3, type: type, value: columnTensorValue(field, i, j), valueKind: valueKind });
            }
        }
    }
    else if (space.rank === 3) {
        var d0 = space.dimensions[0], d1 = space.dimensions[1], d2 = space.dimensions[2];
        for (var i = 0; i < d0; i++) {
            for (var j = 0; j < d1; j++) {
                for (var k = 0; k < d2; k++) {
                    var name_4 = field + "[" + (i + 1) + "][" + (j + 1) + "][" + (k + 1) + "]";
                    fieldDefinitions.push({ name: name_4, type: type, value: columnTensorValue(field, i, j, k), valueKind: valueKind });
                }
            }
        }
    }
    else {
        throw new Error('Tensors with rank > 3 or rank 0 are currently not supported.');
    }
    return fieldDefinitions;
}
function cifFieldsFromTableSchema(schema) {
    var fields = [];
    for (var _i = 0, _a = Object.keys(schema); _i < _a.length; _i++) {
        var k = _a[_i];
        var t = schema[k];
        if (t.valueType === 'int') {
            fields.push({ name: k, type: 1 /* Int */, value: columnValue(k), valueKind: columnValueKind(k) });
        }
        else if (t.valueType === 'float') {
            fields.push({ name: k, type: 2 /* Float */, value: columnValue(k), valueKind: columnValueKind(k) });
        }
        else if (t.valueType === 'str') {
            fields.push({ name: k, type: 0 /* Str */, value: columnValue(k), valueKind: columnValueKind(k) });
        }
        else if (t.valueType === 'list') {
            fields.push({ name: k, type: 0 /* Str */, value: columnListValue(k), valueKind: columnValueKind(k) });
        }
        else if (t.valueType === 'tensor') {
            fields.push.apply(fields, getTensorDefinitions(k, t.space));
        }
        else {
            throw new Error("Unknown valueType " + t.valueType);
        }
    }
    return fields;
}
//# sourceMappingURL=encoder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/index.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/writer/cif/encoder/util.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function getFieldDigitCount(field) {
    if (field.defaultFormat && typeof field.defaultFormat.digitCount !== 'undefined')
        return Math.max(0, Math.min(field.defaultFormat.digitCount, 16));
    return 6;
}
function getIncludedFields(category) {
    return category.fields.some(function (f) { return !!f.shouldInclude; })
        ? category.fields.filter(function (f) { return !f.shouldInclude || category.source.some(function (src) { return f.shouldInclude(src.data); }); })
        : category.fields;
}
function getCategoryInstanceData(category, ctx) {
    var instance = category.instance(ctx);
    var sources = instance.source.filter(function (s) { return s.rowCount > 0; });
    if (!sources.length)
        return { instance: instance, rowCount: 0, source: [] };
    var rowCount = sources.reduce(function (a, c) { return a + c.rowCount; }, 0);
    var source = sources.map(function (c) { return ({
        data: c.data,
        keys: function () { return c.keys ? c.keys() : iterator["a" /* default */].Range(0, c.rowCount - 1); },
        rowCount: c.rowCount
    }); });
    return { instance: instance, rowCount: rowCount, source: source };
}
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/writer/cif/encoder/text.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from CIFTools.js (https://github.com/dsehnal/CIFTools.js)
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var text_TextEncoder = /** @class */ (function () {
    function TextEncoder() {
        this.builder = string_builder["a" /* default */].create();
        this.encoded = false;
        this.dataBlockCreated = false;
        this.filter = encoder_Category.DefaultFilter;
        this.formatter = encoder_Category.DefaultFormatter;
        this.isBinary = false;
        this.binaryEncodingProvider = void 0;
    }
    TextEncoder.prototype.setFilter = function (filter) {
        this.filter = filter || encoder_Category.DefaultFilter;
    };
    TextEncoder.prototype.isCategoryIncluded = function (name) {
        return this.filter.includeCategory(name);
    };
    TextEncoder.prototype.setFormatter = function (formatter) {
        this.formatter = formatter || encoder_Category.DefaultFormatter;
    };
    TextEncoder.prototype.startDataBlock = function (header) {
        this.dataBlockCreated = true;
        string_builder["a" /* default */].write(this.builder, "data_" + (header || '').replace(/[ \n\t]/g, '').toUpperCase() + "\n#\n");
    };
    TextEncoder.prototype.writeCategory = function (category, context, options) {
        if (this.encoded) {
            throw new Error('The writer contents have already been encoded, no more writing.');
        }
        if (!this.dataBlockCreated) {
            throw new Error('No data block created.');
        }
        if (!(options === null || options === void 0 ? void 0 : options.ignoreFilter) && !this.filter.includeCategory(category.name))
            return;
        var _a = getCategoryInstanceData(category, context), instance = _a.instance, rowCount = _a.rowCount, source = _a.source;
        if (!rowCount)
            return;
        if (rowCount === 1) {
            writeCifSingleRecord(category, instance, source, this.builder, this.filter, this.formatter);
        }
        else {
            writeCifLoop(category, instance, source, this.builder, this.filter, this.formatter);
        }
    };
    TextEncoder.prototype.encode = function () {
        this.encoded = true;
    };
    TextEncoder.prototype.writeTo = function (stream) {
        var chunks = string_builder["a" /* default */].getChunks(this.builder);
        for (var i = 0, _i = chunks.length; i < _i; i++) {
            stream.writeString(chunks[i]);
        }
    };
    TextEncoder.prototype.getSize = function () {
        return string_builder["a" /* default */].getSize(this.builder);
    };
    TextEncoder.prototype.getData = function () {
        return string_builder["a" /* default */].getString(this.builder);
    };
    return TextEncoder;
}());
/* harmony default export */ var encoder_text = (text_TextEncoder);
function writeValue(builder, data, key, f, floatPrecision, index) {
    var kind = f.valueKind;
    var p = kind ? kind(key, data) : 0 /* Present */;
    if (p !== 0 /* Present */) {
        if (p === 1 /* NotPresent */)
            writeNotPresent(builder);
        else
            writeUnknown(builder);
    }
    else {
        var val = f.value(key, data, index);
        var t = f.type;
        if (t === 0 /* Str */) {
            if (isMultiline(val)) {
                writeMultiline(builder, val);
                return true;
            }
            else {
                return writeChecked(builder, val);
            }
        }
        else if (t === 1 /* Int */) {
            writeInteger(builder, val);
        }
        else {
            writeFloat(builder, val, floatPrecision);
        }
    }
    return false;
}
function getFloatPrecisions(categoryName, fields, formatter) {
    var ret = [];
    for (var _a = 0, fields_1 = fields; _a < fields_1.length; _a++) {
        var f = fields_1[_a];
        var format = formatter.getFormat(categoryName, f.name);
        if (format && typeof format.digitCount !== 'undefined')
            ret[ret.length] = f.type === 2 /* Float */ ? Math.pow(10, Math.max(0, Math.min(format.digitCount, 15))) : 0;
        else
            ret[ret.length] = f.type === 2 /* Float */ ? Math.pow(10, getFieldDigitCount(f)) : 0;
    }
    return ret;
}
function writeCifSingleRecord(category, instance, source, builder, filter, formatter) {
    var fields = getIncludedFields(instance);
    var src = source[0];
    var data = src.data;
    var width = fields.reduce(function (w, f) { return filter.includeField(category.name, f.name) ? Math.max(w, f.name.length) : 0; }, 0);
    // this means no field from this category is included.
    if (width === 0)
        return;
    width += category.name.length + 6;
    var it = src.keys();
    var key = it.move();
    var precisions = getFloatPrecisions(category.name, instance.fields, formatter);
    for (var _f = 0; _f < fields.length; _f++) {
        var f = fields[_f];
        if (!filter.includeField(category.name, f.name))
            continue;
        string_builder["a" /* default */].writePadRight(builder, "_" + category.name + "." + f.name, width);
        var multiline = writeValue(builder, data, key, f, precisions[_f], 0);
        if (!multiline)
            string_builder["a" /* default */].newline(builder);
    }
    string_builder["a" /* default */].write(builder, '#\n');
}
function writeCifLoop(category, instance, source, builder, filter, formatter) {
    var fieldSource = getIncludedFields(instance);
    var fields = filter === encoder_Category.DefaultFilter ? fieldSource : fieldSource.filter(function (f) { return filter.includeField(category.name, f.name); });
    var fieldCount = fields.length;
    if (fieldCount === 0)
        return;
    var precisions = getFloatPrecisions(category.name, fields, formatter);
    writeLine(builder, 'loop_');
    for (var i = 0; i < fieldCount; i++) {
        writeLine(builder, "_" + category.name + "." + fields[i].name);
    }
    var index = 0;
    for (var _c = 0; _c < source.length; _c++) {
        var src = source[_c];
        var data = src.data;
        if (src.rowCount === 0)
            continue;
        var it_1 = src.keys();
        while (it_1.hasNext) {
            var key = it_1.move();
            var multiline = false;
            for (var _f = 0; _f < fieldCount; _f++) {
                multiline = writeValue(builder, data, key, fields[_f], precisions[_f], index);
            }
            if (!multiline)
                string_builder["a" /* default */].newline(builder);
            index++;
        }
    }
    string_builder["a" /* default */].write(builder, '#\n');
}
function isMultiline(value) {
    return typeof value === 'string' && value.indexOf('\n') >= 0;
}
function writeLine(builder, val) {
    string_builder["a" /* default */].write(builder, val);
    string_builder["a" /* default */].newline(builder);
}
function writeInteger(builder, val) {
    string_builder["a" /* default */].writeInteger(builder, val);
    string_builder["a" /* default */].whitespace1(builder);
}
function writeFloat(builder, val, precisionMultiplier) {
    string_builder["a" /* default */].writeFloat(builder, val, precisionMultiplier);
    string_builder["a" /* default */].whitespace1(builder);
}
function writeNotPresent(builder) {
    string_builder["a" /* default */].writeSafe(builder, '. ');
}
function writeUnknown(builder) {
    string_builder["a" /* default */].writeSafe(builder, '? ');
}
function writeChecked(builder, val) {
    if (!val) {
        string_builder["a" /* default */].writeSafe(builder, '. ');
        return false;
    }
    var escape = val.charCodeAt(0) === 95 /* _ */, escapeCharStart = '\'', escapeCharEnd = '\' ';
    var hasWhitespace = false;
    var hasSingle = false;
    var hasDouble = false;
    for (var i = 0, _l = val.length - 1; i < _l; i++) {
        var c = val.charCodeAt(i);
        switch (c) {
            case 9:
                hasWhitespace = true;
                break; // \t
            case 10: // \n
                writeMultiline(builder, val);
                return true;
            case 32:
                hasWhitespace = true;
                break; // ' '
            case 34: // "
                if (hasSingle) {
                    writeMultiline(builder, val);
                    return true;
                }
                hasDouble = true;
                escape = true;
                escapeCharStart = '\'';
                escapeCharEnd = '\' ';
                break;
            case 39: // '
                if (hasDouble) {
                    writeMultiline(builder, val);
                    return true;
                }
                escape = true;
                hasSingle = true;
                escapeCharStart = '"';
                escapeCharEnd = '" ';
                break;
        }
    }
    var fst = val.charCodeAt(0);
    if (!escape && (fst === 35 /* # */ || fst === 36 /* $ */ || fst === 59 /* ; */ || fst === 91 /* [ */ || fst === 93 /* ] */ || hasWhitespace)) {
        escapeCharStart = '\'';
        escapeCharEnd = '\' ';
        escape = true;
    }
    if (escape) {
        string_builder["a" /* default */].writeSafe(builder, escapeCharStart);
        string_builder["a" /* default */].writeSafe(builder, val);
        string_builder["a" /* default */].writeSafe(builder, escapeCharEnd);
    }
    else {
        string_builder["a" /* default */].writeSafe(builder, val);
        string_builder["a" /* default */].writeSafe(builder, ' ');
    }
    return false;
}
function writeMultiline(builder, val) {
    string_builder["a" /* default */].writeSafe(builder, '\n;' + val);
    string_builder["a" /* default */].writeSafe(builder, '\n;\n');
}
//# sourceMappingURL=text.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/utf8.js
var utf8 = __webpack_require__(157);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/common/msgpack/encode.js
/*
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from https://github.com/rcsb/mmtf-javascript
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function encode(value) {
    var buffer = new ArrayBuffer(encodedSize(value));
    var view = new DataView(buffer);
    var bytes = new Uint8Array(buffer);
    encodeInternal(value, view, bytes, 0);
    return bytes;
}
function encodedSize(value) {
    var type = typeof value;
    // Raw Bytes
    if (type === 'string') {
        var length_1 = Object(utf8["a" /* utf8ByteCount */])(value);
        if (length_1 < 0x20) {
            return 1 + length_1;
        }
        if (length_1 < 0x100) {
            return 2 + length_1;
        }
        if (length_1 < 0x10000) {
            return 3 + length_1;
        }
        if (length_1 < 0x100000000) {
            return 5 + length_1;
        }
    }
    if (value instanceof Uint8Array) {
        var length_2 = value.byteLength;
        if (length_2 < 0x100) {
            return 2 + length_2;
        }
        if (length_2 < 0x10000) {
            return 3 + length_2;
        }
        if (length_2 < 0x100000000) {
            return 5 + length_2;
        }
    }
    if (type === 'number') {
        // Floating Point
        // double
        if (Math.floor(value) !== value)
            return 9;
        // Integers
        if (value >= 0) {
            // positive fixnum
            if (value < 0x80)
                return 1;
            // uint 8
            if (value < 0x100)
                return 2;
            // uint 16
            if (value < 0x10000)
                return 3;
            // uint 32
            if (value < 0x100000000)
                return 5;
            throw new Error('Number too big 0x' + value.toString(16));
        }
        // negative fixnum
        if (value >= -0x20)
            return 1;
        // int 8
        if (value >= -0x80)
            return 2;
        // int 16
        if (value >= -0x8000)
            return 3;
        // int 32
        if (value >= -0x80000000)
            return 5;
        throw new Error('Number too small -0x' + value.toString(16).substr(1));
    }
    // Boolean, null
    if (type === 'boolean' || value === null || value === void 0)
        return 1;
    // Container Types
    if (type === 'object') {
        var length_3, size = 0;
        if (Array.isArray(value)) {
            length_3 = value.length;
            for (var i = 0; i < length_3; i++) {
                size += encodedSize(value[i]);
            }
        }
        else {
            var keys = Object.keys(value);
            length_3 = keys.length;
            for (var i = 0; i < length_3; i++) {
                var key = keys[i];
                size += encodedSize(key) + encodedSize(value[key]);
            }
        }
        if (length_3 < 0x10) {
            return 1 + size;
        }
        if (length_3 < 0x10000) {
            return 3 + size;
        }
        if (length_3 < 0x100000000) {
            return 5 + size;
        }
        throw new Error('Array or object too long 0x' + length_3.toString(16));
    }
    throw new Error('Unknown type ' + type);
}
function encodeInternal(value, view, bytes, offset) {
    var type = typeof value;
    // Strings Bytes
    if (type === 'string') {
        var length_4 = Object(utf8["a" /* utf8ByteCount */])(value);
        // fix str
        if (length_4 < 0x20) {
            view.setUint8(offset, length_4 | 0xa0);
            Object(utf8["c" /* utf8Write */])(bytes, offset + 1, value);
            return 1 + length_4;
        }
        // str 8
        if (length_4 < 0x100) {
            view.setUint8(offset, 0xd9);
            view.setUint8(offset + 1, length_4);
            Object(utf8["c" /* utf8Write */])(bytes, offset + 2, value);
            return 2 + length_4;
        }
        // str 16
        if (length_4 < 0x10000) {
            view.setUint8(offset, 0xda);
            view.setUint16(offset + 1, length_4);
            Object(utf8["c" /* utf8Write */])(bytes, offset + 3, value);
            return 3 + length_4;
        }
        // str 32
        if (length_4 < 0x100000000) {
            view.setUint8(offset, 0xdb);
            view.setUint32(offset + 1, length_4);
            Object(utf8["c" /* utf8Write */])(bytes, offset + 5, value);
            return 5 + length_4;
        }
    }
    if (value instanceof Uint8Array) {
        var length_5 = value.byteLength;
        var bytes_1 = new Uint8Array(view.buffer);
        // bin 8
        if (length_5 < 0x100) {
            view.setUint8(offset, 0xc4);
            view.setUint8(offset + 1, length_5);
            bytes_1.set(value, offset + 2);
            return 2 + length_5;
        }
        // bin 16
        if (length_5 < 0x10000) {
            view.setUint8(offset, 0xc5);
            view.setUint16(offset + 1, length_5);
            bytes_1.set(value, offset + 3);
            return 3 + length_5;
        }
        // bin 32
        if (length_5 < 0x100000000) {
            view.setUint8(offset, 0xc6);
            view.setUint32(offset + 1, length_5);
            bytes_1.set(value, offset + 5);
            return 5 + length_5;
        }
    }
    if (type === 'number') {
        if (!isFinite(value)) {
            throw new Error('Number not finite: ' + value);
        }
        // Floating point
        if (Math.floor(value) !== value) {
            view.setUint8(offset, 0xcb);
            view.setFloat64(offset + 1, value);
            return 9;
        }
        // Integers
        if (value >= 0) {
            // positive fixnum
            if (value < 0x80) {
                view.setUint8(offset, value);
                return 1;
            }
            // uint 8
            if (value < 0x100) {
                view.setUint8(offset, 0xcc);
                view.setUint8(offset + 1, value);
                return 2;
            }
            // uint 16
            if (value < 0x10000) {
                view.setUint8(offset, 0xcd);
                view.setUint16(offset + 1, value);
                return 3;
            }
            // uint 32
            if (value < 0x100000000) {
                view.setUint8(offset, 0xce);
                view.setUint32(offset + 1, value);
                return 5;
            }
            throw new Error('Number too big 0x' + value.toString(16));
        }
        // negative fixnum
        if (value >= -0x20) {
            view.setInt8(offset, value);
            return 1;
        }
        // int 8
        if (value >= -0x80) {
            view.setUint8(offset, 0xd0);
            view.setInt8(offset + 1, value);
            return 2;
        }
        // int 16
        if (value >= -0x8000) {
            view.setUint8(offset, 0xd1);
            view.setInt16(offset + 1, value);
            return 3;
        }
        // int 32
        if (value >= -0x80000000) {
            view.setUint8(offset, 0xd2);
            view.setInt32(offset + 1, value);
            return 5;
        }
        throw new Error('Number too small -0x' + (-value).toString(16).substr(1));
    }
    // null
    if (value === null || value === undefined) {
        view.setUint8(offset, 0xc0);
        return 1;
    }
    // Boolean
    if (type === 'boolean') {
        view.setUint8(offset, value ? 0xc3 : 0xc2);
        return 1;
    }
    // Container Types
    if (type === 'object') {
        var length_6, size = 0;
        var isArray = Array.isArray(value);
        var keys = void 0;
        if (isArray) {
            length_6 = value.length;
        }
        else {
            keys = Object.keys(value);
            length_6 = keys.length;
        }
        if (length_6 < 0x10) {
            view.setUint8(offset, length_6 | (isArray ? 0x90 : 0x80));
            size = 1;
        }
        else if (length_6 < 0x10000) {
            view.setUint8(offset, isArray ? 0xdc : 0xde);
            view.setUint16(offset + 1, length_6);
            size = 3;
        }
        else if (length_6 < 0x100000000) {
            view.setUint8(offset, isArray ? 0xdd : 0xdf);
            view.setUint32(offset + 1, length_6);
            size = 5;
        }
        if (isArray) {
            for (var i = 0; i < length_6; i++) {
                size += encodeInternal(value[i], view, bytes, offset + size);
            }
        }
        else {
            for (var i = 0, _i = keys.length; i < _i; i++) {
                var key = keys[i];
                size += encodeInternal(key, view, bytes, offset + size);
                size += encodeInternal(value[key], view, bytes, offset + size);
            }
        }
        return size;
    }
    throw new Error('Unknown type ' + type);
}
//# sourceMappingURL=encode.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif/classifier.js
var classifier = __webpack_require__(260);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/writer/cif/encoder/binary.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from CIFTools.js (https://github.com/dsehnal/CIFTools.js)
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var binary_BinaryEncoder = /** @class */ (function () {
    function BinaryEncoder(encoder, encodingProvider, autoClassify) {
        this.autoClassify = autoClassify;
        this.dataBlocks = [];
        this.filter = encoder_Category.DefaultFilter;
        this.formatter = encoder_Category.DefaultFormatter;
        this.isBinary = true;
        this.binaryEncodingProvider = void 0;
        this.binaryEncodingProvider = encodingProvider;
        this.data = {
            encoder: encoder,
            version: binary_cif["c" /* VERSION */],
            dataBlocks: this.dataBlocks
        };
    }
    BinaryEncoder.prototype.setFilter = function (filter) {
        this.filter = filter || encoder_Category.DefaultFilter;
    };
    BinaryEncoder.prototype.isCategoryIncluded = function (name) {
        return this.filter.includeCategory(name);
    };
    BinaryEncoder.prototype.setFormatter = function (formatter) {
        this.formatter = formatter || encoder_Category.DefaultFormatter;
    };
    BinaryEncoder.prototype.startDataBlock = function (header) {
        this.dataBlocks.push({
            header: (header || '').replace(/[ \n\t]/g, '').toUpperCase(),
            categories: []
        });
    };
    BinaryEncoder.prototype.writeCategory = function (category, context, options) {
        if (!this.data) {
            throw new Error('The writer contents have already been encoded, no more writing.');
        }
        if (!this.dataBlocks.length) {
            throw new Error('No data block created.');
        }
        if (!(options === null || options === void 0 ? void 0 : options.ignoreFilter) && !this.filter.includeCategory(category.name))
            return;
        var _a = getCategoryInstanceData(category, context), instance = _a.instance, rowCount = _a.rowCount, source = _a.source;
        if (!rowCount)
            return;
        var cat = { name: '_' + category.name, columns: [], rowCount: rowCount };
        var fields = getIncludedFields(instance);
        for (var _i = 0, fields_1 = fields; _i < fields_1.length; _i++) {
            var f = fields_1[_i];
            if (!this.filter.includeField(category.name, f.name))
                continue;
            var format = this.formatter.getFormat(category.name, f.name);
            cat.columns.push(encodeField(category.name, f, source, rowCount, format, this.binaryEncodingProvider, this.autoClassify));
        }
        // no columns included.
        if (!cat.columns.length)
            return;
        this.dataBlocks[this.dataBlocks.length - 1].categories.push(cat);
    };
    BinaryEncoder.prototype.encode = function () {
        if (this.encodedData)
            return;
        this.encodedData = encode(this.data);
        this.data = null;
        this.dataBlocks = null;
    };
    BinaryEncoder.prototype.writeTo = function (writer) {
        writer.writeBinary(this.encodedData);
    };
    BinaryEncoder.prototype.getData = function () {
        this.encode();
        return this.encodedData;
    };
    BinaryEncoder.prototype.getSize = function () {
        return this.encodedData.length;
    };
    return BinaryEncoder;
}());
/* harmony default export */ var encoder_binary = (binary_BinaryEncoder);
function getArrayCtor(field, format) {
    if (format && format.typedArray)
        return format.typedArray;
    if (field.defaultFormat && field.defaultFormat.typedArray)
        return field.defaultFormat.typedArray;
    if (field.type === 0 /* Str */)
        return Array;
    if (field.type === 1 /* Int */)
        return Int32Array;
    return Float64Array;
}
function getDefaultEncoder(type) {
    if (type === 0 /* Str */)
        return binary_cif["a" /* ArrayEncoder */].by(binary_cif["b" /* ArrayEncoding */].stringArray);
    return binary_cif["a" /* ArrayEncoder */].by(binary_cif["b" /* ArrayEncoding */].byteArray);
}
function tryGetEncoder(categoryName, field, format, provider) {
    if (format && format.encoder) {
        return format.encoder;
    }
    else if (field.defaultFormat && field.defaultFormat.encoder) {
        return field.defaultFormat.encoder;
    }
    else if (provider) {
        return provider.get(categoryName, field.name);
    }
    else {
        return void 0;
    }
}
function classify(type, data) {
    if (type === 0 /* Str */)
        return binary_cif["a" /* ArrayEncoder */].by(binary_cif["b" /* ArrayEncoding */].stringArray);
    if (type === 1 /* Int */)
        return Object(classifier["b" /* classifyIntArray */])(data);
    return Object(classifier["a" /* classifyFloatArray */])(data);
}
function encodeField(categoryName, field, data, totalCount, format, encoderProvider, autoClassify) {
    var _a = getFieldData(field, getArrayCtor(field, format), totalCount, data), array = _a.array, allPresent = _a.allPresent, mask = _a.mask;
    var encoder = tryGetEncoder(categoryName, field, format, encoderProvider);
    if (!encoder) {
        if (autoClassify)
            encoder = classify(field.type, array);
        else
            encoder = getDefaultEncoder(field.type);
    }
    var encoded = encoder.encode(array);
    var maskData = void 0;
    if (!allPresent) {
        var maskRLE = binary_cif["a" /* ArrayEncoder */].by(binary_cif["b" /* ArrayEncoding */].runLength).and(binary_cif["b" /* ArrayEncoding */].byteArray).encode(mask);
        if (maskRLE.data.length < mask.length) {
            maskData = maskRLE;
        }
        else {
            maskData = binary_cif["a" /* ArrayEncoder */].by(binary_cif["b" /* ArrayEncoding */].byteArray).encode(mask);
        }
    }
    return {
        name: field.name,
        data: encoded,
        mask: maskData
    };
}
function getFieldData(field, arrayCtor, totalCount, data) {
    var isStr = field.type === 0 /* Str */;
    var array = new arrayCtor(totalCount);
    var mask = new Uint8Array(totalCount);
    var valueKind = field.valueKind;
    var getter = field.value;
    var allPresent = true;
    var offset = 0;
    for (var _d = 0; _d < data.length; _d++) {
        var d = data[_d].data;
        var keys = data[_d].keys();
        while (keys.hasNext) {
            var key = keys.move();
            var p = valueKind ? valueKind(key, d) : 0 /* Present */;
            if (p !== 0 /* Present */) {
                mask[offset] = p;
                if (isStr)
                    array[offset] = '';
                allPresent = false;
            }
            else {
                mask[offset] = 0 /* Present */;
                array[offset] = getter(key, d, offset);
            }
            offset++;
        }
    }
    return { array: array, allPresent: allPresent, mask: mask };
}
//# sourceMappingURL=binary.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/writer/cif.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var cif_CifWriter;
(function (CifWriter) {
    CifWriter.Encoder = Encoder;
    CifWriter.Category = encoder_Category;
    CifWriter.Field = encoder_Field;
    CifWriter.Encoding = binary_cif["b" /* ArrayEncoding */];
    function createEncoder(params) {
        var _a = params || {}, _b = _a.binary, binary = _b === void 0 ? false : _b, _c = _a.encoderName, encoderName = _c === void 0 ? 'mol*' : _c;
        return binary ? new encoder_binary(encoderName, params ? params.binaryEncodingPovider : void 0, params ? !!params.binaryAutoClassifyEncoding : false) : new encoder_text();
    }
    CifWriter.createEncoder = createEncoder;
    function fields() {
        return CifWriter.Field.build();
    }
    CifWriter.fields = fields;
    var E = CifWriter.Encoding;
    CifWriter.Encodings = {
        deltaRLE: E.by(E.delta).and(E.runLength).and(E.integerPacking),
        fixedPoint2: E.by(E.fixedPoint(100)).and(E.delta).and(E.integerPacking),
        fixedPoint3: E.by(E.fixedPoint(1000)).and(E.delta).and(E.integerPacking),
    };
    function categoryInstance(fields, source) {
        return { fields: fields, source: [source] };
    }
    CifWriter.categoryInstance = categoryInstance;
    function createEncodingProviderFromCifFrame(frame) {
        return {
            get: function (c, f) {
                var cat = frame.categories[c];
                if (!cat)
                    return void 0;
                var ff = cat.getField(f);
                return ff && ff.binaryEncoding ? binary_cif["a" /* ArrayEncoder */].fromEncoding(ff.binaryEncoding) : void 0;
            }
        };
    }
    CifWriter.createEncodingProviderFromCifFrame = createEncodingProviderFromCifFrame;
    ;
    function createEncodingProviderFromJsonConfig(hints) {
        return {
            get: function (c, f) {
                for (var i = 0; i < hints.length; i++) {
                    var hint = hints[i];
                    if (hint.categoryName === c && hint.columnName === f) {
                        return resolveEncoding(hint);
                    }
                }
            }
        };
    }
    CifWriter.createEncodingProviderFromJsonConfig = createEncodingProviderFromJsonConfig;
    function resolveEncoding(hint) {
        var precision = hint.precision;
        if (precision !== void 0) {
            var multiplier = Math.pow(10, precision);
            var fixedPoint = E.by(E.fixedPoint(multiplier));
            switch (hint.encoding) {
                case 'pack':
                    return fixedPoint.and(E.integerPacking);
                case 'rle':
                    return fixedPoint.and(E.runLength).and(E.integerPacking);
                case 'delta':
                    return fixedPoint.and(E.delta).and(E.integerPacking);
                case 'delta-rle':
                    return fixedPoint.and(E.delta).and(E.runLength).and(E.integerPacking);
            }
            ;
        }
        else {
            switch (hint.encoding) {
                case 'pack':
                    return E.by(E.integerPacking);
                case 'rle':
                    return E.by(E.runLength).and(E.integerPacking);
                case 'delta':
                    return E.by(E.delta).and(E.integerPacking);
                case 'delta-rle':
                    return E.by(E.delta).and(E.runLength).and(E.integerPacking);
            }
        }
        throw new Error('cannot be reached');
    }
})(cif_CifWriter || (cif_CifWriter = {}));
//# sourceMappingURL=cif.js.map

/***/ }),
/* 63 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LinkCylinderParams; });
/* unused harmony export DefaultLinkCylinderProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return LinkLineParams; });
/* unused harmony export DefaultLinkLineProps */
/* unused harmony export calculateShiftDir */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return LinkStyle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return createLinkCylinderMesh; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return createLinkLines; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(39);
/* harmony import */ var _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34);
/* harmony import */ var _mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(81);
/* harmony import */ var _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(33);
/* harmony import */ var _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(74);
/* harmony import */ var _mol_geo_geometry_lines_lines_builder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(172);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var LinkCylinderParams = {
    linkScale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0.4, { min: 0, max: 1, step: 0.1 }),
    linkSpacing: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(1, { min: 0, max: 2, step: 0.01 }),
    linkCap: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false),
    radialSegments: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_5__[/* BaseGeometry */ "a"].CustomQualityParamInfo),
};
var DefaultLinkCylinderProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(LinkCylinderParams);
var LinkLineParams = {
    linkScale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.1 }),
    linkSpacing: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0.1, { min: 0, max: 2, step: 0.01 }),
};
var DefaultLinkLineProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(LinkLineParams);
var tmpV12 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var tmpShiftV12 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var tmpShiftV13 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var up = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].create(0, 1, 0);
/** Calculate 'shift' direction that is perpendiculat to v1 - v2 and goes through v3 */
function calculateShiftDir(out, v1, v2, v3) {
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].normalize(tmpShiftV12, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(tmpShiftV12, v1, v2));
    if (v3 !== null) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(tmpShiftV13, v1, v3);
    }
    else {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].copy(tmpShiftV13, v1); // no reference point, use v1
    }
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].normalize(tmpShiftV13, tmpShiftV13);
    // ensure v13 and v12 are not colinear
    var dp = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].dot(tmpShiftV12, tmpShiftV13);
    if (1 - Math.abs(dp) < 1e-5) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpShiftV13, 1, 0, 0);
        dp = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].dot(tmpShiftV12, tmpShiftV13);
        if (1 - Math.abs(dp) < 1e-5) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpShiftV13, 0, 1, 0);
            dp = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].dot(tmpShiftV12, tmpShiftV13);
        }
    }
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].setMagnitude(tmpShiftV12, tmpShiftV12, dp);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(tmpShiftV13, tmpShiftV13, tmpShiftV12);
    return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].normalize(out, tmpShiftV13);
}
var LinkStyle;
(function (LinkStyle) {
    LinkStyle[LinkStyle["Solid"] = 0] = "Solid";
    LinkStyle[LinkStyle["Dashed"] = 1] = "Dashed";
    LinkStyle[LinkStyle["Double"] = 2] = "Double";
    LinkStyle[LinkStyle["Triple"] = 3] = "Triple";
    LinkStyle[LinkStyle["Disk"] = 4] = "Disk";
})(LinkStyle || (LinkStyle = {}));
/**
 * Each edge is included twice to allow for coloring/picking
 * the half closer to the first vertex, i.e. vertex a.
 */
function createLinkCylinderMesh(ctx, linkBuilder, props, mesh) {
    var linkCount = linkBuilder.linkCount, referencePosition = linkBuilder.referencePosition, position = linkBuilder.position, style = linkBuilder.style, radius = linkBuilder.radius, ignore = linkBuilder.ignore;
    if (!linkCount)
        return _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_2__[/* Mesh */ "a"].createEmpty(mesh);
    var linkScale = props.linkScale, linkSpacing = props.linkSpacing, radialSegments = props.radialSegments, linkCap = props.linkCap;
    var vertexCountEstimate = radialSegments * 2 * linkCount * 2;
    var builderState = _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__[/* MeshBuilder */ "a"].createState(vertexCountEstimate, vertexCountEstimate / 4, mesh);
    var va = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var vb = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var vShift = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var cylinderProps = {
        radiusTop: 1,
        radiusBottom: 1,
        radialSegments: radialSegments,
        topCap: linkCap,
        bottomCap: linkCap
    };
    for (var edgeIndex = 0, _eI = linkCount; edgeIndex < _eI; ++edgeIndex) {
        if (ignore && ignore(edgeIndex))
            continue;
        position(va, vb, edgeIndex);
        var linkRadius = radius(edgeIndex);
        var linkStyle = style ? style(edgeIndex) : LinkStyle.Solid;
        builderState.currentGroup = edgeIndex;
        if (linkStyle === LinkStyle.Dashed) {
            cylinderProps.radiusTop = cylinderProps.radiusBottom = linkRadius / 3;
            cylinderProps.topCap = cylinderProps.bottomCap = true;
            Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addFixedCountDashedCylinder */ "c"])(builderState, va, vb, 0.5, 7, cylinderProps);
        }
        else if (linkStyle === LinkStyle.Double || linkStyle === LinkStyle.Triple) {
            var order = LinkStyle.Double ? 2 : 3;
            var multiRadius = linkRadius * (linkScale / (0.5 * order));
            var absOffset = (linkRadius - multiRadius) * linkSpacing;
            calculateShiftDir(vShift, va, vb, referencePosition ? referencePosition(edgeIndex) : null);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].setMagnitude(vShift, vShift, absOffset);
            cylinderProps.radiusTop = cylinderProps.radiusBottom = multiRadius;
            cylinderProps.topCap = cylinderProps.bottomCap = linkCap;
            if (order === 3)
                Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addCylinder */ "a"])(builderState, va, vb, 0.5, cylinderProps);
            Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addDoubleCylinder */ "b"])(builderState, va, vb, 0.5, vShift, cylinderProps);
        }
        else if (linkStyle === LinkStyle.Disk) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(tmpV12, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(tmpV12, vb, va), 0.475);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(va, va, tmpV12);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(vb, vb, tmpV12);
            cylinderProps.radiusTop = cylinderProps.radiusBottom = linkRadius;
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].dot(tmpV12, up) > 0) {
                cylinderProps.topCap = false;
                cylinderProps.bottomCap = linkCap;
            }
            else {
                cylinderProps.topCap = linkCap;
                cylinderProps.bottomCap = false;
            }
            Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addCylinder */ "a"])(builderState, va, vb, 0.5, cylinderProps);
        }
        else {
            cylinderProps.radiusTop = cylinderProps.radiusBottom = linkRadius;
            cylinderProps.topCap = cylinderProps.bottomCap = linkCap;
            Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_4__[/* addCylinder */ "a"])(builderState, va, vb, 0.5, cylinderProps);
        }
    }
    return _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__[/* MeshBuilder */ "a"].getMesh(builderState);
}
/**
 * Each edge is included twice to allow for coloring/picking
 * the half closer to the first vertex, i.e. vertex a.
 */
function createLinkLines(ctx, linkBuilder, props, lines) {
    var linkCount = linkBuilder.linkCount, referencePosition = linkBuilder.referencePosition, position = linkBuilder.position, style = linkBuilder.style, ignore = linkBuilder.ignore;
    if (!linkCount)
        return _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_6__[/* Lines */ "a"].createEmpty(lines);
    var linkScale = props.linkScale, linkSpacing = props.linkSpacing;
    var linesCountEstimate = linkCount * 2;
    var builder = _mol_geo_geometry_lines_lines_builder__WEBPACK_IMPORTED_MODULE_7__[/* LinesBuilder */ "a"].create(linesCountEstimate, linesCountEstimate / 4, lines);
    var va = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var vb = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var vShift = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    for (var edgeIndex = 0, _eI = linkCount; edgeIndex < _eI; ++edgeIndex) {
        if (ignore && ignore(edgeIndex))
            continue;
        position(va, vb, edgeIndex);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(vb, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(vb, va, vb), 0.5);
        // TODO use line width?
        var linkStyle = style ? style(edgeIndex) : LinkStyle.Solid;
        if (linkStyle === LinkStyle.Dashed) {
            builder.addFixedCountDashes(va, vb, 7, edgeIndex);
        }
        else if (linkStyle === LinkStyle.Double || linkStyle === LinkStyle.Triple) {
            var order = LinkStyle.Double ? 2 : 3;
            var multiRadius = 1 * (linkScale / (0.5 * order));
            var absOffset = (1 - multiRadius) * linkSpacing;
            calculateShiftDir(vShift, va, vb, referencePosition ? referencePosition(edgeIndex) : null);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].setMagnitude(vShift, vShift, absOffset);
            if (order === 3)
                builder.add(va[0], va[1], va[2], vb[0], vb[1], vb[2], edgeIndex);
            builder.add(va[0] + vShift[0], va[1] + vShift[1], va[2] + vShift[2], vb[0] + vShift[0], vb[1] + vShift[1], vb[2] + vShift[2], edgeIndex);
            builder.add(va[0] - vShift[0], va[1] - vShift[1], va[2] - vShift[2], vb[0] - vShift[0], vb[1] - vShift[1], vb[2] - vShift[2], edgeIndex);
        }
        else if (linkStyle === LinkStyle.Disk) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(tmpV12, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(tmpV12, vb, va), 0.475);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(va, va, tmpV12);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(vb, vb, tmpV12);
            // TODO what to do here?
            builder.add(va[0], va[1], va[2], vb[0], vb[1], vb[2], edgeIndex);
        }
        else {
            builder.add(va[0], va[1], va[2], vb[0], vb[1], vb[2], edgeIndex);
        }
    }
    return builder.getLines();
}
//# sourceMappingURL=link.js.map

/***/ }),
/* 64 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var Matrix;
(function (Matrix) {
    function create(cols, rows, ctor) {
        if (ctor === void 0) { ctor = Float32Array; }
        var size = cols * rows;
        return { data: new ctor(size), size: size, cols: cols, rows: rows };
    }
    Matrix.create = create;
    /** Get element assuming data are stored in column-major order */
    function get(m, i, j) {
        return m.data[m.rows * j + i];
    }
    Matrix.get = get;
    /** Set element assuming data are stored in column-major order */
    function set(m, i, j, value) {
        m.data[m.rows * j + i] = value;
        return m;
    }
    Matrix.set = set;
    /** Add to element assuming data are stored in column-major order */
    function add(m, i, j, value) {
        m.data[m.rows * j + i] += value;
        return m;
    }
    Matrix.add = add;
    /** Zero out the matrix */
    function makeZero(m) {
        m.data.fill(0.0);
        return m;
    }
    Matrix.makeZero = makeZero;
    function clone(m) {
        return { data: m.data.slice(), size: m.size, cols: m.cols, rows: m.rows };
    }
    Matrix.clone = clone;
    function fromArray(data, cols, rows) {
        return { data: data, size: cols * rows, cols: cols, rows: rows };
    }
    Matrix.fromArray = fromArray;
    function transpose(out, mat) {
        if (out.cols !== mat.rows || out.rows !== mat.cols) {
            throw new Error('transpose: matrix dimensions incompatible');
        }
        if (out.data === mat.data) {
            throw new Error('transpose: matrices share memory');
        }
        var nrows = mat.rows, ncols = mat.cols;
        var md = mat.data, mtd = out.data;
        for (var i = 0, mi = 0, mti = 0; i < nrows; mti += 1, mi += ncols, ++i) {
            var ri = mti;
            for (var j = 0; j < ncols; ri += nrows, j++)
                mtd[ri] = md[mi + j];
        }
        return out;
    }
    Matrix.transpose = transpose;
    /** out = matA * matB' */
    function multiplyABt(out, matA, matB) {
        var ncols = matA.cols, nrows = matA.rows, mrows = matB.rows;
        var ad = matA.data, bd = matB.data, cd = out.data;
        for (var i = 0, matAp = 0, outP = 0; i < nrows; matAp += ncols, i++) {
            for (var pB = 0, j = 0; j < mrows; outP++, j++) {
                var sum = 0.0;
                var pMatA = matAp;
                for (var k = 0; k < ncols; pMatA++, pB++, k++) {
                    sum += ad[pMatA] * bd[pB];
                }
                cd[outP] = sum;
            }
        }
        return out;
    }
    Matrix.multiplyABt = multiplyABt;
    /** Get the mean of rows in `mat` */
    function meanRows(mat) {
        var nrows = mat.rows, ncols = mat.cols;
        var md = mat.data;
        var mean = new Array(ncols);
        for (var j = 0; j < ncols; ++j)
            mean[j] = 0.0;
        for (var i = 0, p = 0; i < nrows; ++i) {
            for (var j = 0; j < ncols; ++j, ++p)
                mean[j] += md[p];
        }
        for (var j = 0; j < ncols; ++j)
            mean[j] /= nrows;
        return mean;
    }
    Matrix.meanRows = meanRows;
    /** Subtract `row` from all rows in `mat` */
    function subRows(mat, row) {
        var nrows = mat.rows, ncols = mat.cols;
        var md = mat.data;
        for (var i = 0, p = 0; i < nrows; ++i) {
            for (var j = 0; j < ncols; ++j, ++p)
                md[p] -= row[j];
        }
        return mat;
    }
    Matrix.subRows = subRows;
})(Matrix || (Matrix = {}));
/* harmony default export */ __webpack_exports__["a"] = (Matrix);
//# sourceMappingURL=matrix.js.map

/***/ }),
/* 65 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomPropertyDescriptor", function() { return CustomPropertyDescriptor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomProperties", function() { return CustomProperties; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function CustomPropertyDescriptor(desc) {
    return desc;
}
(function (CustomPropertyDescriptor) {
    function getUUID(prop) {
        if (!prop.__key) {
            prop.__key = _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* UUID */ "c"].create22();
        }
        return prop.__key;
    }
    CustomPropertyDescriptor.getUUID = getUUID;
})(CustomPropertyDescriptor || (CustomPropertyDescriptor = {}));
var CustomProperties = /** @class */ (function () {
    function CustomProperties() {
        this._list = [];
        this._set = new Set();
        this._refs = new Map();
        this._assets = new Map();
    }
    Object.defineProperty(CustomProperties.prototype, "all", {
        get: function () {
            return this._list;
        },
        enumerable: false,
        configurable: true
    });
    CustomProperties.prototype.add = function (desc) {
        if (this._set.has(desc))
            return;
        this._list.push(desc);
        this._set.add(desc);
    };
    CustomProperties.prototype.reference = function (desc, add) {
        var refs = this._refs.get(desc) || 0;
        refs += add ? 1 : -1;
        this._refs.set(desc, Math.max(refs, 0));
    };
    CustomProperties.prototype.hasReference = function (desc) {
        return (this._refs.get(desc) || 0) > 0;
    };
    CustomProperties.prototype.has = function (desc) {
        return this._set.has(desc);
    };
    /** Sets assets for a prop, disposes of existing assets for that prop */
    CustomProperties.prototype.assets = function (desc, assets) {
        var prevAssets = this._assets.get(desc);
        if (prevAssets) {
            for (var _i = 0, prevAssets_1 = prevAssets; _i < prevAssets_1.length; _i++) {
                var a = prevAssets_1[_i];
                a.dispose();
            }
        }
        if (assets)
            this._assets.set(desc, assets);
        else
            this._assets.delete(desc);
    };
    /** Disposes of all assets of all props */
    CustomProperties.prototype.dispose = function () {
        this._assets.forEach(function (assets) {
            for (var _i = 0, assets_1 = assets; _i < assets_1.length; _i++) {
                var a = assets_1[_i];
                a.dispose();
            }
        });
    };
    return CustomProperties;
}());
//# sourceMappingURL=custom-property.js.map

/***/ }),
/* 66 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "ParameterControls", function() { return /* binding */ parameters_ParameterControls; });
__webpack_require__.d(__webpack_exports__, "ParameterMappingControl", function() { return /* binding */ parameters_ParameterMappingControl; });
__webpack_require__.d(__webpack_exports__, "ParamHelp", function() { return /* binding */ parameters_ParamHelp; });
__webpack_require__.d(__webpack_exports__, "SimpleParam", function() { return /* binding */ parameters_SimpleParam; });
__webpack_require__.d(__webpack_exports__, "BoolControl", function() { return /* binding */ parameters_BoolControl; });
__webpack_require__.d(__webpack_exports__, "LineGraphControl", function() { return /* binding */ parameters_LineGraphControl; });
__webpack_require__.d(__webpack_exports__, "NumberInputControl", function() { return /* binding */ parameters_NumberInputControl; });
__webpack_require__.d(__webpack_exports__, "NumberRangeControl", function() { return /* binding */ parameters_NumberRangeControl; });
__webpack_require__.d(__webpack_exports__, "TextControl", function() { return /* binding */ parameters_TextControl; });
__webpack_require__.d(__webpack_exports__, "PureSelectControl", function() { return /* binding */ parameters_PureSelectControl; });
__webpack_require__.d(__webpack_exports__, "SelectControl", function() { return /* binding */ parameters_SelectControl; });
__webpack_require__.d(__webpack_exports__, "IntervalControl", function() { return /* binding */ parameters_IntervalControl; });
__webpack_require__.d(__webpack_exports__, "BoundedIntervalControl", function() { return /* binding */ parameters_BoundedIntervalControl; });
__webpack_require__.d(__webpack_exports__, "ColorControl", function() { return /* binding */ parameters_ColorControl; });
__webpack_require__.d(__webpack_exports__, "ColorListControl", function() { return /* binding */ parameters_ColorListControl; });
__webpack_require__.d(__webpack_exports__, "Vec3Control", function() { return /* binding */ parameters_Vec3Control; });
__webpack_require__.d(__webpack_exports__, "Mat4Control", function() { return /* binding */ parameters_Mat4Control; });
__webpack_require__.d(__webpack_exports__, "UrlControl", function() { return /* binding */ parameters_UrlControl; });
__webpack_require__.d(__webpack_exports__, "FileControl", function() { return /* binding */ parameters_FileControl; });
__webpack_require__.d(__webpack_exports__, "FileListControl", function() { return /* binding */ parameters_FileListControl; });
__webpack_require__.d(__webpack_exports__, "MultiSelectControl", function() { return /* binding */ parameters_MultiSelectControl; });
__webpack_require__.d(__webpack_exports__, "GroupControl", function() { return /* binding */ parameters_GroupControl; });
__webpack_require__.d(__webpack_exports__, "MappedControl", function() { return /* binding */ parameters_MappedControl; });
__webpack_require__.d(__webpack_exports__, "ObjectListControl", function() { return /* binding */ parameters_ObjectListControl; });
__webpack_require__.d(__webpack_exports__, "ConditionedControl", function() { return /* binding */ parameters_ConditionedControl; });
__webpack_require__.d(__webpack_exports__, "ConvertedControl", function() { return /* binding */ parameters_ConvertedControl; });
__webpack_require__.d(__webpack_exports__, "ScriptControl", function() { return /* binding */ parameters_ScriptControl; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/lists.js
var lists = __webpack_require__(88);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/memoize.js
var memoize = __webpack_require__(155);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/number.js
var number = __webpack_require__(174);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string.js
var string = __webpack_require__(41);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/action-menu.js
var action_menu = __webpack_require__(56);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/color.js
var color_color = __webpack_require__(43);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/color/swatches.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var DefaultColorSwatch = Object(color_color["ColorSwatch"])([
    ['black', 0x000000],
    ['gray', 0x808080],
    ['white', 0xFFFFFF],
    ['red', 0xD33115],
    ['orange', 0xE27300],
    ['yellow', 0xFCC400],
    ['green', 0x68BC00],
    ['cyan', 0x16A5A5],
    ['blue', 0x009CE0],
    ['purple', 0x7B64FF],
    ['magenta', 0xFA28FF],
    ['violet', 0x7D2187]
]);
//# sourceMappingURL=swatches.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/color.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var color_CombinedColorControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(CombinedColorControl, _super);
    function CombinedColorControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isExpanded: !!_this.props.param.isExpanded,
            lightness: 0
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        _this.onClickSwatch = function (e) {
            var value = Object(mol_util_color["Color"])(+(e.currentTarget.getAttribute('data-color') || '0'));
            if (value !== _this.props.value) {
                if (!_this.props.param.isExpanded)
                    _this.setState({ isExpanded: false });
                _this.update(value);
            }
        };
        _this.onR = function (v) {
            var _a = mol_util_color["Color"].toRgb(_this.props.value), g = _a[1], b = _a[2];
            var value = mol_util_color["Color"].fromRgb(v, g, b);
            if (value !== _this.props.value)
                _this.update(value);
        };
        _this.onG = function (v) {
            var _a = mol_util_color["Color"].toRgb(_this.props.value), r = _a[0], b = _a[2];
            var value = mol_util_color["Color"].fromRgb(r, v, b);
            if (value !== _this.props.value)
                _this.update(value);
        };
        _this.onB = function (v) {
            var _a = mol_util_color["Color"].toRgb(_this.props.value), r = _a[0], g = _a[1];
            var value = mol_util_color["Color"].fromRgb(r, g, v);
            if (value !== _this.props.value)
                _this.update(value);
        };
        _this.onLighten = function () {
            _this.update(mol_util_color["Color"].lighten(_this.props.value, 0.1));
        };
        _this.onDarken = function () {
            _this.update(mol_util_color["Color"].darken(_this.props.value, 0.1));
        };
        return _this;
    }
    CombinedColorControl.prototype.update = function (value) {
        this.props.onChange({ param: this.props.param, name: this.props.name, value: value });
    };
    CombinedColorControl.prototype.swatch = function () {
        var _this = this;
        return react["createElement"]("div", { className: 'msp-combined-color-swatch' }, DefaultColorSwatch.map(function (c) { return react["createElement"](common["Button"], { key: c[1], inline: true, "data-color": c[1], onClick: _this.onClickSwatch, style: { background: mol_util_color["Color"].toStyle(c[1]) } }); }));
    };
    CombinedColorControl.prototype.render = function () {
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var _a = mol_util_color["Color"].toRgb(this.props.value), r = _a[0], g = _a[1], b = _a[2];
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { title: this.props.param.description, label: label, control: react["createElement"](common["Button"], { onClick: this.toggleExpanded, inline: true, className: 'msp-combined-color-button', style: { background: mol_util_color["Color"].toStyle(this.props.value) } }) }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                this.swatch(),
                react["createElement"](common["ControlRow"], { label: 'RGB', className: 'msp-control-label-short', control: react["createElement"]("div", { style: { display: 'flex', textAlignLast: 'center', left: '80px' } },
                        react["createElement"](common["TextInput"], { onChange: this.onR, numeric: true, value: r, delayMs: 250, style: { order: 1, flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control', onEnter: this.props.onEnter, blurOnEnter: true, blurOnEscape: true }),
                        react["createElement"](common["TextInput"], { onChange: this.onG, numeric: true, value: g, delayMs: 250, style: { order: 2, flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control', onEnter: this.props.onEnter, blurOnEnter: true, blurOnEscape: true }),
                        react["createElement"](common["TextInput"], { onChange: this.onB, numeric: true, value: b, delayMs: 250, style: { order: 3, flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control', onEnter: this.props.onEnter, blurOnEnter: true, blurOnEscape: true })) }),
                react["createElement"]("div", { style: { display: 'flex', textAlignLast: 'center' } },
                    react["createElement"](common["Button"], { onClick: this.onLighten, style: { order: 1, flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control' }, "Lighten"),
                    react["createElement"](common["Button"], { onClick: this.onDarken, style: { order: 1, flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control' }, "Darken"))));
    };
    return CombinedColorControl;
}(react["PureComponent"]));

var _colors = void 0;
function ColorOptions() {
    if (_colors)
        return _colors;
    _colors = react["createElement"](react["Fragment"], null, DefaultColorSwatch.map(function (v) {
        return react["createElement"]("option", { key: v[1], value: v[1], style: { background: "" + mol_util_color["Color"].toStyle(v[1]) } }, Object(string["d" /* stringToWords */])(v[0]));
    }));
    return _colors;
}
var DefaultColorSwatchMap = (function () {
    var map = new Map();
    for (var _i = 0, DefaultColorSwatch_1 = DefaultColorSwatch; _i < DefaultColorSwatch_1.length; _i++) {
        var v = DefaultColorSwatch_1[_i];
        map.set(v[1], v[0]);
    }
    return map;
})();
function ColorValueOption(color) {
    return !DefaultColorSwatchMap.has(color) ? react["createElement"]("option", { key: mol_util_color["Color"].toHexString(color), value: color, style: { background: "" + mol_util_color["Color"].toStyle(color) } }, mol_util_color["Color"].toRgbString(color)) : null;
}
//# sourceMappingURL=color.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/legend.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function legendFor(legend) {
    switch (legend.kind) {
        case 'scale-legend': return legend_ScaleLegend;
        case 'table-legend': return legend_TableLegend;
        default:
            var _ = legend;
            console.warn(_ + " has no associated UI component");
            return void 0;
    }
}
var legend_ScaleLegend = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ScaleLegend, _super);
    function ScaleLegend() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ScaleLegend.prototype.render = function () {
        var legend = this.props.legend;
        var colors = legend.colors.map(function (c) { return mol_util_color["Color"].toStyle(c); }).join(', ');
        return react["createElement"]("div", { className: 'msp-scale-legend' },
            react["createElement"]("div", { style: { background: "linear-gradient(to right, " + colors + ")" } },
                react["createElement"]("span", { style: { float: 'left' } }, legend.minLabel),
                react["createElement"]("span", { style: { float: 'right' } }, legend.maxLabel)));
    };
    return ScaleLegend;
}(react["PureComponent"]));

var legend_TableLegend = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(TableLegend, _super);
    function TableLegend() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TableLegend.prototype.render = function () {
        var legend = this.props.legend;
        return react["createElement"]("div", { className: 'msp-table-legend' }, legend.table.map(function (value, i) {
            var name = value[0], color = value[1];
            return react["createElement"]("div", { key: i },
                react["createElement"]("div", { className: 'msp-table-legend-color', style: { backgroundColor: mol_util_color["Color"].toStyle(color) } }),
                react["createElement"]("div", { className: 'msp-table-legend-text' }, name));
        }));
    };
    return TableLegend;
}(react["PureComponent"]));

//# sourceMappingURL=legend.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/line-graph/point-component.js



var point_component_PointComponent = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PointComponent, _super);
    function PointComponent(props) {
        var _this = _super.call(this, props) || this;
        _this.state = { show: false };
        _this.handleHover = _this.handleHover.bind(_this);
        _this.handleHoverOff = _this.handleHoverOff.bind(_this);
        _this.deletePoint = _this.deletePoint.bind(_this);
        return _this;
    }
    PointComponent.prototype.handleHover = function () {
        this.setState({ show: true });
        var point = linear_algebra["Vec2"].create(this.props.nX, this.props.nY);
        this.props.onmouseover(point);
    };
    PointComponent.prototype.handleHoverOff = function () {
        this.setState({ show: false });
        this.props.onmouseover(undefined);
    };
    PointComponent.prototype.deletePoint = function () {
        this.props.delete(this.props.id);
    };
    PointComponent.prototype.render = function () {
        return ([
            react["createElement"]("circle", { r: "10", key: this.props.id + "circle", id: "" + this.props.id, cx: this.props.x, cy: this.props.y, onClick: this.props.onclick, onDoubleClick: this.props.delete(this.props.id), onMouseEnter: this.handleHover, onMouseLeave: this.handleHoverOff, onMouseDown: this.props.onmousedown, fill: "black" })
        ]);
    };
    return PointComponent;
}(react["Component"]));
/* harmony default export */ var point_component = (point_component_PointComponent);
//# sourceMappingURL=point-component.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/line-graph/line-graph-component.js

/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Paul Luna <paulluna0215@gmail.com>
 */



var line_graph_component_LineGraphComponent = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(LineGraphComponent, _super);
    function LineGraphComponent(props) {
        var _this = _super.call(this, props) || this;
        _this.handleKeyDown = function (event) {
            // TODO: set canSelectMultiple = true
        };
        _this.handleKeyUp = function (event) {
            // TODO: SET canSelectMultiple = fasle
        };
        _this.handleClick = function (id) { return function (event) {
            // TODO: add point to selected array
        }; };
        _this.handleMouseDown = function (id) { return function (event) {
            if (id === 0 || id === _this.state.points.length - 1) {
                return;
            }
            if (_this.state.canSelectMultiple) {
                return;
            }
            var copyPoint = _this.normalizePoint(linear_algebra["Vec2"].create(_this.state.points[id][0], _this.state.points[id][1]));
            _this.ghostPoints.push(document.createElementNS(_this.namespace, 'circle'));
            _this.ghostPoints[0].setAttribute('r', '10');
            _this.ghostPoints[0].setAttribute('fill', 'orange');
            _this.ghostPoints[0].setAttribute('cx', "" + copyPoint[0]);
            _this.ghostPoints[0].setAttribute('cy', "" + copyPoint[1]);
            _this.ghostPoints[0].setAttribute('style', 'display: none');
            _this.gElement.appendChild(_this.ghostPoints[0]);
            _this.updatedX = copyPoint[0];
            _this.updatedY = copyPoint[1];
            _this.selected = [id];
        }; };
        _this.deletePoint = function (i) { return function (event) {
            if (i === 0 || i === _this.state.points.length - 1) {
                return;
            }
            var points = _this.state.points.filter(function (_, j) { return j !== i; });
            points.sort(function (a, b) {
                if (a[0] === b[0]) {
                    if (a[0] === 0) {
                        return a[1] - b[1];
                    }
                    if (a[1] === 1) {
                        return b[1] - a[1];
                    }
                    return a[1] - b[1];
                }
                return a[0] - b[0];
            });
            _this.setState({ points: points });
            _this.change(points);
            event.stopPropagation();
        }; };
        _this.myRef = react["createRef"]();
        _this.state = {
            points: [
                linear_algebra["Vec2"].create(0, 0),
                linear_algebra["Vec2"].create(1, 0)
            ],
            copyPoint: undefined,
            canSelectMultiple: false,
        };
        _this.height = 400;
        _this.width = 600;
        _this.padding = 70;
        _this.selected = undefined;
        _this.ghostPoints = [];
        _this.namespace = 'http://www.w3.org/2000/svg';
        for (var _i = 0, _a = _this.props.data; _i < _a.length; _i++) {
            var point = _a[_i];
            _this.state.points.push(point);
        }
        _this.state.points.sort(function (a, b) {
            if (a[0] === b[0]) {
                if (a[0] === 0) {
                    return a[1] - b[1];
                }
                if (a[1] === 1) {
                    return b[1] - a[1];
                }
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });
        _this.handleDrag = _this.handleDrag.bind(_this);
        _this.handleMultipleDrag = _this.handleMultipleDrag.bind(_this);
        _this.handleDoubleClick = _this.handleDoubleClick.bind(_this);
        _this.refCallBack = _this.refCallBack.bind(_this);
        _this.handlePointUpdate = _this.handlePointUpdate.bind(_this);
        _this.change = _this.change.bind(_this);
        _this.handleKeyUp = _this.handleKeyUp.bind(_this);
        _this.handleLeave = _this.handleLeave.bind(_this);
        _this.handleEnter = _this.handleEnter.bind(_this);
        return _this;
    }
    LineGraphComponent.prototype.render = function () {
        var points = this.renderPoints();
        var lines = this.renderLines();
        return ([
            react["createElement"]("div", { key: "LineGraph" },
                react["createElement"]("svg", { className: "msp-canvas", ref: this.refCallBack, viewBox: "0 0 " + (this.width + this.padding) + " " + (this.height + this.padding), onMouseMove: this.handleDrag, onMouseUp: this.handlePointUpdate, onMouseLeave: this.handleLeave, onMouseEnter: this.handleEnter, tabIndex: 0, onKeyDown: this.handleKeyDown, onKeyUp: this.handleKeyUp, onDoubleClick: this.handleDoubleClick },
                    react["createElement"]("g", { stroke: "black", fill: "black" },
                        lines,
                        points),
                    react["createElement"]("g", { className: "ghost-points", stroke: "black", fill: "black" }))),
            react["createElement"]("div", { key: "modal", id: "modal-root" })
        ]);
    };
    LineGraphComponent.prototype.componentDidMount = function () {
        this.gElement = document.getElementsByClassName('ghost-points')[0];
    };
    LineGraphComponent.prototype.change = function (points) {
        var copyPoints = points.slice();
        copyPoints.shift();
        copyPoints.pop();
        this.props.onChange(copyPoints);
    };
    LineGraphComponent.prototype.handleDrag = function (event) {
        if (this.selected === undefined) {
            return;
        }
        var pt = this.myRef.createSVGPoint();
        var updatedCopyPoint;
        var padding = this.padding / 2;
        pt.x = event.clientX;
        pt.y = event.clientY;
        var svgP = pt.matrixTransform(this.myRef.getScreenCTM().inverse());
        updatedCopyPoint = linear_algebra["Vec2"].create(svgP.x, svgP.y);
        if ((svgP.x < (padding) || svgP.x > (this.width + (padding))) && (svgP.y > (this.height + (padding)) || svgP.y < (padding))) {
            updatedCopyPoint = linear_algebra["Vec2"].create(this.updatedX, this.updatedY);
        }
        else if (svgP.x < padding) {
            updatedCopyPoint = linear_algebra["Vec2"].create(padding, svgP.y);
        }
        else if (svgP.x > (this.width + (padding))) {
            updatedCopyPoint = linear_algebra["Vec2"].create(this.width + padding, svgP.y);
        }
        else if (svgP.y > (this.height + (padding))) {
            updatedCopyPoint = linear_algebra["Vec2"].create(svgP.x, this.height + padding);
        }
        else if (svgP.y < (padding)) {
            updatedCopyPoint = linear_algebra["Vec2"].create(svgP.x, padding);
        }
        else {
            updatedCopyPoint = linear_algebra["Vec2"].create(svgP.x, svgP.y);
        }
        this.updatedX = updatedCopyPoint[0];
        this.updatedY = updatedCopyPoint[1];
        var unNormalizePoint = this.unNormalizePoint(updatedCopyPoint);
        this.ghostPoints[0].setAttribute('style', 'display: visible');
        this.ghostPoints[0].setAttribute('cx', "" + updatedCopyPoint[0]);
        this.ghostPoints[0].setAttribute('cy', "" + updatedCopyPoint[1]);
        this.props.onDrag(unNormalizePoint);
    };
    LineGraphComponent.prototype.handleMultipleDrag = function () {
        // TODO
    };
    LineGraphComponent.prototype.handlePointUpdate = function (event) {
        var selected = this.selected;
        if (this.state.canSelectMultiple) {
            return;
        }
        if (selected === undefined || selected[0] === 0 || selected[0] === this.state.points.length - 1) {
            this.setState({
                copyPoint: undefined,
            });
            return;
        }
        this.selected = undefined;
        var updatedPoint = this.unNormalizePoint(linear_algebra["Vec2"].create(this.updatedX, this.updatedY));
        var points = this.state.points.filter(function (_, i) { return i !== selected[0]; });
        points.push(updatedPoint);
        ;
        points.sort(function (a, b) {
            if (a[0] === b[0]) {
                if (a[0] === 0) {
                    return a[1] - b[1];
                }
                if (a[1] === 1) {
                    return b[1] - a[1];
                }
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });
        this.setState({
            points: points,
        });
        this.change(points);
        this.gElement.innerHTML = '';
        this.ghostPoints = [];
        document.removeEventListener('mousemove', this.handleDrag, true);
        document.removeEventListener('mouseup', this.handlePointUpdate, true);
    };
    LineGraphComponent.prototype.handleDoubleClick = function (event) {
        var newPoint;
        var pt = this.myRef.createSVGPoint();
        pt.x = event.clientX;
        pt.y = event.clientY;
        var svgP = pt.matrixTransform(this.myRef.getScreenCTM().inverse());
        var points = this.state.points;
        var padding = this.padding / 2;
        if (svgP.x < (padding) ||
            svgP.x > (this.width + (padding)) ||
            svgP.y > (this.height + (padding)) ||
            svgP.y < (this.padding / 2)) {
            return;
        }
        newPoint = this.unNormalizePoint(linear_algebra["Vec2"].create(svgP.x, svgP.y));
        points.push(newPoint);
        points.sort(function (a, b) {
            if (a[0] === b[0]) {
                if (a[0] === 0) {
                    return a[1] - b[1];
                }
                if (a[1] === 1) {
                    return b[1] - a[1];
                }
                return a[1] - b[1];
            }
            return a[0] - b[0];
        });
        this.setState({ points: points });
        this.change(points);
    };
    LineGraphComponent.prototype.handleLeave = function () {
        if (this.selected === undefined) {
            return;
        }
        document.addEventListener('mousemove', this.handleDrag, true);
        document.addEventListener('mouseup', this.handlePointUpdate, true);
    };
    LineGraphComponent.prototype.handleEnter = function () {
        document.removeEventListener('mousemove', this.handleDrag, true);
        document.removeEventListener('mouseup', this.handlePointUpdate, true);
    };
    LineGraphComponent.prototype.normalizePoint = function (point) {
        var min = this.padding / 2;
        var maxX = this.width + min;
        var maxY = this.height + min;
        var normalizedX = (point[0] * (maxX - min)) + min;
        var normalizedY = (point[1] * (maxY - min)) + min;
        var reverseY = (this.height + this.padding) - normalizedY;
        var newPoint = linear_algebra["Vec2"].create(normalizedX, reverseY);
        return newPoint;
    };
    LineGraphComponent.prototype.unNormalizePoint = function (point) {
        var min = this.padding / 2;
        var maxX = this.width + min;
        var maxY = this.height + min;
        var unNormalizedX = (point[0] - min) / (maxX - min);
        // we have to take into account that we reversed y when we first normalized it.
        var unNormalizedY = ((this.height + this.padding) - point[1] - min) / (maxY - min);
        return linear_algebra["Vec2"].create(unNormalizedX, unNormalizedY);
    };
    LineGraphComponent.prototype.refCallBack = function (element) {
        if (element) {
            this.myRef = element;
        }
    };
    LineGraphComponent.prototype.renderPoints = function () {
        var points = [];
        var point;
        for (var i = 0; i < this.state.points.length; i++) {
            if (i !== 0 && i !== this.state.points.length - 1) {
                point = this.normalizePoint(this.state.points[i]);
                points.push(react["createElement"](point_component, { key: i, id: i, x: point[0], y: point[1], nX: this.state.points[i][0], nY: this.state.points[i][1], selected: false, delete: this.deletePoint, onmouseover: this.props.onHover, onmousedown: this.handleMouseDown(i), onclick: this.handleClick(i) }));
            }
        }
        return points;
    };
    LineGraphComponent.prototype.renderLines = function () {
        var points = [];
        var lines = [];
        var min;
        var maxX;
        var maxY;
        var normalizedX;
        var normalizedY;
        var reverseY;
        for (var _i = 0, _a = this.state.points; _i < _a.length; _i++) {
            var point = _a[_i];
            min = this.padding / 2;
            maxX = this.width + min;
            maxY = this.height + min;
            normalizedX = (point[0] * (maxX - min)) + min;
            normalizedY = (point[1] * (maxY - min)) + min;
            reverseY = this.height + this.padding - normalizedY;
            points.push(linear_algebra["Vec2"].create(normalizedX, reverseY));
        }
        var data = points;
        var size = data.length;
        for (var i = 0; i < size - 1; i++) {
            var x1 = data[i][0];
            var y1 = data[i][1];
            var x2 = data[i + 1][0];
            var y2 = data[i + 1][1];
            lines.push(react["createElement"]("line", { key: "lineOf" + i, x1: x1, x2: x2, y1: y1, y2: y2, stroke: "#cec9ba", strokeWidth: "5" }));
        }
        return lines;
    };
    return LineGraphComponent;
}(react["Component"]));
/* harmony default export */ var line_graph_component = (line_graph_component_LineGraphComponent);
//# sourceMappingURL=line-graph-component.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/slider.js
var slider = __webpack_require__(328);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/assets.js
var assets = __webpack_require__(114);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















var parameters_ParameterControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ParameterControls, _super);
    function ParameterControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (params) {
            var _a;
            var _b, _c;
            (_c = (_b = _this.props).onChange) === null || _c === void 0 ? void 0 : _c.call(_b, params, _this.props.values);
            if (_this.props.onChangeValues) {
                var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.props.values), (_a = {}, _a[params.name] = params.value, _a));
                _this.props.onChangeValues(values, _this.props.values);
            }
        };
        _this.paramGroups = Object(memoize["b" /* memoizeLatest */])(function (params) { return classifyParams(params); });
        return _this;
    }
    ParameterControls.prototype.renderGroup = function (group) {
        var _a;
        if (group.length === 0)
            return null;
        var values = this.props.values;
        var ctrls = null;
        var category = void 0;
        for (var _i = 0, group_1 = group; _i < group_1.length; _i++) {
            var _b = group_1[_i], key = _b[0], p = _b[1], Control = _b[2];
            if ((_a = p.hideIf) === null || _a === void 0 ? void 0 : _a.call(p, values))
                continue;
            if (!ctrls)
                ctrls = [];
            category = p.category;
            ctrls.push(react["createElement"](Control, { param: p, key: key, onChange: this.onChange, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled, name: key, value: values[key] }));
        }
        if (!ctrls)
            return null;
        if (category) {
            return [react["createElement"](common["ExpandGroup"], { key: category, header: category }, ctrls)];
        }
        return ctrls;
    };
    ParameterControls.prototype.renderPart = function (groups) {
        var parts = null;
        for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
            var g = groups_1[_i];
            var ctrls = this.renderGroup(g);
            if (!ctrls)
                continue;
            if (!parts)
                parts = [];
            for (var _a = 0, ctrls_1 = ctrls; _a < ctrls_1.length; _a++) {
                var c = ctrls_1[_a];
                parts.push(c);
            }
        }
        return parts;
    };
    ParameterControls.prototype.render = function () {
        var groups = this.paramGroups(this.props.params);
        var essentials = this.renderPart(groups.essentials);
        var advanced = this.renderPart(groups.advanced);
        if (essentials && advanced) {
            return react["createElement"](react["Fragment"], null,
                essentials,
                react["createElement"](common["ExpandGroup"], { header: 'Advanced Options' }, advanced));
        }
        else if (essentials) {
            return essentials;
        }
        else {
            return advanced;
        }
    };
    return ParameterControls;
}(react["PureComponent"]));

var parameters_ParameterMappingControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ParameterMappingControl, _super);
    function ParameterMappingControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.setSettings = function (p, old) {
            var _a;
            var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, old), (_a = {}, _a[p.name] = p.value, _a));
            var t = _this.props.mapping.update(values, _this.plugin);
            _this.props.mapping.apply(t, _this.plugin);
        };
        return _this;
    }
    ParameterMappingControl.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
    };
    ParameterMappingControl.prototype.render = function () {
        var t = this.props.mapping.getTarget(this.plugin);
        var values = this.props.mapping.getValues(t, this.plugin);
        var params = this.props.mapping.params(this.plugin);
        return react["createElement"](parameters_ParameterControls, { params: params, values: values, onChange: this.setSettings });
    };
    return ParameterMappingControl;
}(base["PluginUIComponent"]));

function classifyParams(params) {
    function addParam(k, p, group) {
        var ctrl = controlFor(p);
        if (!ctrl)
            return;
        if (!p.category)
            group.params[0].push([k, p, ctrl]);
        else {
            if (!group.map)
                group.map = new Map();
            var c = group.map.get(p.category);
            if (!c) {
                c = [];
                group.map.set(p.category, c);
                group.params.push(c);
            }
            c.push([k, p, ctrl]);
        }
    }
    function sortGroups(x, y) {
        var a = x[0], b = y[0];
        if (!a || !a[1].category)
            return -1;
        if (!b || !b[1].category)
            return 1;
        return a[1].category < b[1].category ? -1 : 1;
    }
    var keys = Object.keys(params);
    var essentials = { params: [[]], map: void 0 };
    var advanced = { params: [[]], map: void 0 };
    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
        var k = keys_1[_i];
        var p = params[k];
        if (p.isHidden)
            continue;
        if (p.isEssential)
            addParam(k, p, essentials);
        else
            addParam(k, p, advanced);
    }
    essentials.params.sort(sortGroups);
    advanced.params.sort(sortGroups);
    return { essentials: essentials.params, advanced: advanced.params };
}
function controlFor(param) {
    switch (param.type) {
        case 'value': return void 0;
        case 'boolean': return parameters_BoolControl;
        case 'number': return typeof param.min !== 'undefined' && typeof param.max !== 'undefined'
            ? parameters_NumberRangeControl : parameters_NumberInputControl;
        case 'converted': return parameters_ConvertedControl;
        case 'conditioned': return parameters_ConditionedControl;
        case 'multi-select': return parameters_MultiSelectControl;
        case 'color': return color_CombinedColorControl;
        case 'color-list': return parameters_ColorListControl;
        case 'vec3': return parameters_Vec3Control;
        case 'mat4': return parameters_Mat4Control;
        case 'url': return parameters_UrlControl;
        case 'file': return parameters_FileControl;
        case 'file-list': return parameters_FileListControl;
        case 'select': return parameters_SelectControl;
        case 'text': return parameters_TextControl;
        case 'interval': return typeof param.min !== 'undefined' && typeof param.max !== 'undefined'
            ? parameters_BoundedIntervalControl : parameters_IntervalControl;
        case 'group': return parameters_GroupControl;
        case 'mapped': return parameters_MappedControl;
        case 'line-graph': return parameters_LineGraphControl;
        case 'script': return parameters_ScriptControl;
        case 'object-list': return parameters_ObjectListControl;
        default:
            var _ = param;
            console.warn(_ + " has no associated UI component");
            return void 0;
    }
}
var parameters_ParamHelp = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ParamHelp, _super);
    function ParamHelp() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ParamHelp.prototype.render = function () {
        var _a = this.props, legend = _a.legend, description = _a.description;
        var Legend = legend && legendFor(legend);
        return react["createElement"]("div", { className: 'msp-help-text' },
            react["createElement"]("div", null,
                react["createElement"]("div", { className: 'msp-help-description' },
                    react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"], inline: true }),
                    description),
                Legend && react["createElement"]("div", { className: 'msp-help-legend' },
                    react["createElement"](Legend, { legend: legend }))));
    };
    return ParamHelp;
}(react["PureComponent"]));

function renderSimple(options) {
    var props = options.props, state = options.state, control = options.control, toggleHelp = options.toggleHelp, addOn = options.addOn;
    var _className = [];
    if (props.param.shortLabel)
        _className.push('msp-control-label-short');
    if (props.param.twoColumns)
        _className.push('msp-control-col-2');
    var className = _className.join(' ');
    var label = props.param.label || Object(string["a" /* camelCaseToWords */])(props.name);
    var help = props.param.help
        ? props.param.help(props.value)
        : { description: props.param.description, legend: props.param.legend };
    var desc = props.param.description;
    var hasHelp = help.description || help.legend;
    return react["createElement"](react["Fragment"], null,
        react["createElement"](common["ControlRow"], { className: className, title: desc, label: react["createElement"](react["Fragment"], null,
                label,
                hasHelp &&
                    react["createElement"]("button", { className: 'msp-help msp-btn-link msp-btn-icon msp-control-group-expander', onClick: toggleHelp, title: desc || (state.showHelp ? 'Hide' : 'Show') + " help", style: { background: 'transparent', textAlign: 'left', padding: '0' } },
                        react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"] }))), control: control }),
        hasHelp && state.showHelp && react["createElement"]("div", { className: 'msp-control-offset' },
            react["createElement"](parameters_ParamHelp, { legend: help.legend, description: help.description })),
        addOn);
}
var parameters_SimpleParam = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SimpleParam, _super);
    function SimpleParam() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showHelp: false };
        _this.toggleHelp = function () { return _this.setState({ showHelp: !_this.state.showHelp }); };
        return _this;
    }
    SimpleParam.prototype.update = function (value) {
        this.props.onChange({ param: this.props.param, name: this.props.name, value: value });
    };
    SimpleParam.prototype.renderAddOn = function () { return null; };
    SimpleParam.prototype.render = function () {
        return renderSimple({
            props: this.props,
            state: this.state,
            control: this.renderControl(),
            toggleHelp: this.toggleHelp,
            addOn: this.renderAddOn()
        });
    };
    return SimpleParam;
}(react["PureComponent"]));

var parameters_BoolControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(BoolControl, _super);
    function BoolControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onClick = function (e) { _this.update(!_this.props.value); e.currentTarget.blur(); };
        return _this;
    }
    BoolControl.prototype.renderControl = function () {
        return react["createElement"]("button", { onClick: this.onClick, disabled: this.props.isDisabled },
            react["createElement"](icons["Icon"], { svg: this.props.value ? icons["CheckSvg"] : icons["ClearSvg"] }),
            this.props.value ? 'On' : 'Off');
    };
    return BoolControl;
}(parameters_SimpleParam));

var parameters_LineGraphControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(LineGraphControl, _super);
    function LineGraphControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isExpanded: false,
            isOverPoint: false,
            message: _this.props.param.defaultValue.length + " points",
        };
        _this.onHover = function (point) {
            _this.setState({ isOverPoint: !_this.state.isOverPoint });
            if (point) {
                _this.setState({ message: "(" + point[0].toFixed(2) + ", " + point[1].toFixed(2) + ")" });
                return;
            }
            _this.setState({ message: _this.props.value.length + " points" });
        };
        _this.onDrag = function (point) {
            _this.setState({ message: "(" + point[0].toFixed(2) + ", " + point[1].toFixed(2) + ")" });
        };
        _this.onChange = function (value) {
            _this.props.onChange({ name: _this.props.name, param: _this.props.param, value: value });
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    LineGraphControl.prototype.render = function () {
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, "" + this.state.message) }),
            react["createElement"]("div", { className: 'msp-control-offset', style: { display: this.state.isExpanded ? 'block' : 'none' } },
                react["createElement"](line_graph_component, { data: this.props.param.defaultValue, onChange: this.onChange, onHover: this.onHover, onDrag: this.onDrag })));
    };
    return LineGraphControl;
}(react["PureComponent"]));

var parameters_NumberInputControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(NumberInputControl, _super);
    function NumberInputControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { value: '0' };
        _this.update = function (value) {
            var p = Object(number["b" /* getPrecision */])(_this.props.param.step || 0.01);
            value = parseFloat(value.toFixed(p));
            _this.props.onChange({ param: _this.props.param, name: _this.props.name, value: value });
        };
        return _this;
    }
    NumberInputControl.prototype.render = function () {
        var placeholder = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var p = Object(number["b" /* getPrecision */])(this.props.param.step || 0.01);
        return react["createElement"](common["ControlRow"], { title: this.props.param.description, label: label, control: react["createElement"](common["TextInput"], { numeric: true, value: parseFloat(this.props.value.toFixed(p)), onEnter: this.props.onEnter, placeholder: placeholder, isDisabled: this.props.isDisabled, onChange: this.update }) });
    };
    return NumberInputControl;
}(react["PureComponent"]));

var parameters_NumberRangeControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(NumberRangeControl, _super);
    function NumberRangeControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (v) { _this.update(v); };
        return _this;
    }
    NumberRangeControl.prototype.renderControl = function () {
        var value = typeof this.props.value === 'undefined' ? this.props.param.defaultValue : this.props.value;
        return react["createElement"](slider["a" /* Slider */], { value: value, min: this.props.param.min, max: this.props.param.max, step: this.props.param.step, onChange: this.onChange, disabled: this.props.isDisabled, onEnter: this.props.onEnter });
    };
    return NumberRangeControl;
}(parameters_SimpleParam));

var parameters_TextControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(TextControl, _super);
    function TextControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            var value = e.target.value;
            if (value !== _this.props.value) {
                _this.update(value);
            }
        };
        _this.onKeyPress = function (e) {
            if ((e.keyCode === 13 || e.charCode === 13)) {
                if (_this.props.onEnter)
                    _this.props.onEnter();
            }
            e.stopPropagation();
        };
        return _this;
    }
    TextControl.prototype.renderControl = function () {
        var placeholder = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"]("input", { type: 'text', value: this.props.value || '', placeholder: placeholder, onChange: this.onChange, onKeyPress: this.props.onEnter ? this.onKeyPress : void 0, disabled: this.props.isDisabled });
    };
    return TextControl;
}(parameters_SimpleParam));

var parameters_PureSelectControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PureSelectControl, _super);
    function PureSelectControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            if (typeof _this.props.param.defaultValue === 'number') {
                _this.update(parseInt(e.target.value, 10));
            }
            else {
                _this.update(e.target.value);
            }
        };
        return _this;
    }
    PureSelectControl.prototype.update = function (value) {
        this.props.onChange({ param: this.props.param, name: this.props.name, value: value });
    };
    PureSelectControl.prototype.render = function () {
        var _this = this;
        var isInvalid = this.props.value !== void 0 && !this.props.param.options.some(function (e) { return e[0] === _this.props.value; });
        return react["createElement"]("select", { className: 'msp-form-control', title: this.props.title, value: this.props.value !== void 0 ? this.props.value : this.props.param.defaultValue, onChange: this.onChange, disabled: this.props.isDisabled },
            isInvalid && react["createElement"]("option", { key: this.props.value, value: this.props.value }, "[Invalid] " + this.props.value),
            this.props.param.options.map(function (_a) {
                var value = _a[0], label = _a[1];
                return react["createElement"]("option", { key: value, value: value }, label);
            }));
    };
    return PureSelectControl;
}(react["PureComponent"]));

var parameters_SelectControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SelectControl, _super);
    function SelectControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showHelp: false, showOptions: false };
        _this.onSelect = function (item) {
            if (!item || item.value === _this.props.value) {
                _this.setState({ showOptions: false });
            }
            else {
                _this.setState({ showOptions: false }, function () {
                    _this.props.onChange({ param: _this.props.param, name: _this.props.name, value: item.value });
                });
            }
        };
        _this.toggle = function () { return _this.setState({ showOptions: !_this.state.showOptions }); };
        _this.cycle = function () {
            var options = _this.props.param.options;
            var current = options.findIndex(function (o) { return o[0] === _this.props.value; });
            var next = current === options.length - 1 ? 0 : current + 1;
            _this.props.onChange({ param: _this.props.param, name: _this.props.name, value: options[next][0] });
        };
        _this.items = Object(memoize["b" /* memoizeLatest */])(function (param) { return action_menu["a" /* ActionMenu */].createItemsFromSelectOptions(param.options); });
        _this.toggleHelp = function () { return _this.setState({ showHelp: !_this.state.showHelp }); };
        return _this;
    }
    SelectControl.prototype.renderControl = function () {
        var _a;
        var items = this.items(this.props.param);
        var current = this.props.value !== undefined ? action_menu["a" /* ActionMenu */].findItem(items, this.props.value) : void 0;
        var label = current
            ? current.label
            : typeof this.props.value === 'undefined'
                ? (((_a = action_menu["a" /* ActionMenu */].getFirstItem(items)) === null || _a === void 0 ? void 0 : _a.label) || '') + " [Default]"
                : "[Invalid] " + this.props.value;
        var toggle = this.props.param.cycle ? this.cycle : this.toggle;
        var textAlign = this.props.param.cycle ? 'center' : 'left';
        var icon = this.props.param.cycle
            ? (this.props.value === 'on' ? icons["CheckSvg"]
                : this.props.value === 'off' ? icons["ClearSvg"] : void 0)
            : void 0;
        return react["createElement"](common["ToggleButton"], { disabled: this.props.isDisabled, style: { textAlign: textAlign, overflow: 'hidden', textOverflow: 'ellipsis' }, label: label, title: label, icon: icon, toggle: toggle, isSelected: this.state.showOptions });
    };
    SelectControl.prototype.renderAddOn = function () {
        if (!this.state.showOptions)
            return null;
        var items = this.items(this.props.param);
        var current = action_menu["a" /* ActionMenu */].findItem(items, this.props.value);
        return react["createElement"](action_menu["a" /* ActionMenu */], { items: items, current: current, onSelect: this.onSelect });
    };
    SelectControl.prototype.render = function () {
        return renderSimple({
            props: this.props,
            state: this.state,
            control: this.renderControl(),
            toggleHelp: this.toggleHelp,
            addOn: this.renderAddOn()
        });
    };
    return SelectControl;
}(react["PureComponent"]));

var parameters_IntervalControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(IntervalControl, _super);
    function IntervalControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.components = {
            0: param_definition["ParamDefinition"].Numeric(0, { step: _this.props.param.step }, { label: 'Min' }),
            1: param_definition["ParamDefinition"].Numeric(0, { step: _this.props.param.step }, { label: 'Max' })
        };
        _this.componentChange = function (_a) {
            var name = _a.name, value = _a.value;
            var v = Object(tslib_es6["__spreadArrays"])(_this.props.value);
            v[+name] = value;
            _this.change(v);
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    IntervalControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    IntervalControl.prototype.render = function () {
        var v = this.props.value;
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var p = Object(number["b" /* getPrecision */])(this.props.param.step || 0.01);
        var value = "[" + v[0].toFixed(p) + ", " + v[1].toFixed(p) + "]";
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, value) }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](parameters_ParameterControls, { params: this.components, values: v, onChange: this.componentChange, onEnter: this.props.onEnter })));
    };
    return IntervalControl;
}(react["PureComponent"]));

var parameters_BoundedIntervalControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(BoundedIntervalControl, _super);
    function BoundedIntervalControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (v) { _this.update(v); };
        return _this;
    }
    BoundedIntervalControl.prototype.renderControl = function () {
        return react["createElement"](slider["b" /* Slider2 */], { value: this.props.value, min: this.props.param.min, max: this.props.param.max, step: this.props.param.step, onChange: this.onChange, disabled: this.props.isDisabled, onEnter: this.props.onEnter });
    };
    return BoundedIntervalControl;
}(parameters_SimpleParam));

var parameters_ColorControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ColorControl, _super);
    function ColorControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            _this.update(Object(mol_util_color["Color"])(parseInt(e.target.value)));
        };
        return _this;
    }
    ColorControl.prototype.stripStyle = function () {
        return {
            background: mol_util_color["Color"].toStyle(this.props.value),
            position: 'absolute',
            bottom: '0',
            height: '4px',
            right: '0',
            left: '0'
        };
    };
    ColorControl.prototype.renderControl = function () {
        return react["createElement"]("div", { style: { position: 'relative' } },
            react["createElement"]("select", { value: this.props.value, onChange: this.onChange },
                ColorValueOption(this.props.value),
                ColorOptions()),
            react["createElement"]("div", { style: this.stripStyle() }));
    };
    return ColorControl;
}(parameters_SimpleParam));

var colorGradientInterpolated = Object(memoize["a" /* memoize1 */])(function (colors) {
    var styles = colors.map(function (c) { return mol_util_color["Color"].toStyle(c); });
    return "linear-gradient(to right, " + styles.join(', ') + ")";
});
var colorGradientBanded = Object(memoize["a" /* memoize1 */])(function (colors) {
    var n = colors.length;
    var styles = [mol_util_color["Color"].toStyle(colors[0]) + " " + 100 * (1 / n) + "%"];
    for (var i = 1, il = n - 1; i < il; ++i) {
        styles.push(mol_util_color["Color"].toStyle(colors[i]) + " " + 100 * (i / n) + "%", mol_util_color["Color"].toStyle(colors[i]) + " " + 100 * ((i + 1) / n) + "%");
    }
    styles.push(mol_util_color["Color"].toStyle(colors[n - 1]) + " " + 100 * ((n - 1) / n) + "%");
    return "linear-gradient(to right, " + styles.join(', ') + ")";
});
function colorStripStyle(list, right) {
    if (right === void 0) { right = '0'; }
    return {
        background: colorGradient(list.colors, list.kind === 'set'),
        position: 'absolute',
        bottom: '0',
        height: '4px',
        right: right,
        left: '0'
    };
}
function colorGradient(colors, banded) {
    return banded ? colorGradientBanded(colors) : colorGradientInterpolated(colors);
}
function createColorListHelpers() {
    var addOn = function (l) {
        var preset = Object(lists["getColorListFromName"])(l[0]);
        return react["createElement"]("div", { style: colorStripStyle({ kind: preset.type !== 'qualitative' ? 'interpolate' : 'set', colors: preset.list }) });
    };
    return {
        ColorPresets: {
            all: action_menu["a" /* ActionMenu */].createItemsFromSelectOptions(lists["ColorListOptions"], { addOn: addOn }),
            scale: action_menu["a" /* ActionMenu */].createItemsFromSelectOptions(lists["ColorListOptionsScale"], { addOn: addOn }),
            set: action_menu["a" /* ActionMenu */].createItemsFromSelectOptions(lists["ColorListOptionsSet"], { addOn: addOn })
        },
        ColorsParam: param_definition["ParamDefinition"].ObjectList({ color: param_definition["ParamDefinition"].Color(0x0) }, function (_a) {
            var color = _a.color;
            return mol_util_color["Color"].toHexString(color).toUpperCase();
        }),
        IsInterpolatedParam: param_definition["ParamDefinition"].Boolean(false, { label: 'Interpolated' })
    };
}
var _colorListHelpers;
function ColorListHelpers() {
    if (_colorListHelpers)
        return _colorListHelpers;
    _colorListHelpers = createColorListHelpers();
    return _colorListHelpers;
}
var parameters_ColorListControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ColorListControl, _super);
    function ColorListControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showHelp: false, show: void 0 };
        _this.toggleEdit = function () { return _this.setState({ show: _this.state.show === 'edit' ? void 0 : 'edit' }); };
        _this.togglePresets = function () { return _this.setState({ show: _this.state.show === 'presets' ? void 0 : 'presets' }); };
        _this.selectPreset = function (item) {
            if (!item)
                return;
            _this.setState({ show: void 0 });
            var preset = Object(lists["getColorListFromName"])(item.value);
            _this.update({ kind: preset.type !== 'qualitative' ? 'interpolate' : 'set', colors: preset.list });
        };
        _this.colorsChanged = function (_a) {
            var value = _a.value;
            _this.update({
                kind: _this.props.value.kind,
                colors: value.map(function (c) { return c.color; })
            });
        };
        _this.isInterpolatedChanged = function (_a) {
            var value = _a.value;
            _this.update({ kind: value ? 'interpolate' : 'set', colors: _this.props.value.colors });
        };
        _this.toggleHelp = function () { return _this.setState({ showHelp: !_this.state.showHelp }); };
        return _this;
    }
    ColorListControl.prototype.update = function (value) {
        this.props.onChange({ param: this.props.param, name: this.props.name, value: value });
    };
    ColorListControl.prototype.renderControl = function () {
        var value = this.props.value;
        // TODO: fix the button right offset
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("button", { onClick: this.toggleEdit, style: { position: 'relative', paddingRight: '33px' } },
                value.colors.length === 1 ? '1 color' : value.colors.length + " colors",
                react["createElement"]("div", { style: colorStripStyle(value, '33px') })),
            react["createElement"](common["IconButton"], { svg: icons["BookmarksOutlinedSvg"], onClick: this.togglePresets, toggleState: this.state.show === 'presets', title: 'Color Presets', style: { padding: 0, position: 'absolute', right: 0, top: 0, width: '32px' } }));
    };
    ColorListControl.prototype.renderColors = function () {
        if (!this.state.show)
            return null;
        var _a = ColorListHelpers(), ColorPresets = _a.ColorPresets, ColorsParam = _a.ColorsParam, IsInterpolatedParam = _a.IsInterpolatedParam;
        var preset = ColorPresets[this.props.param.presetKind];
        if (this.state.show === 'presets')
            return react["createElement"](action_menu["a" /* ActionMenu */], { items: preset, onSelect: this.selectPreset });
        var values = this.props.value.colors.map(function (color) { return ({ color: color }); });
        return react["createElement"]("div", { className: 'msp-control-offset' },
            react["createElement"](parameters_ObjectListControl, { name: 'colors', param: ColorsParam, value: values, onChange: this.colorsChanged, isDisabled: this.props.isDisabled, onEnter: this.props.onEnter }),
            react["createElement"](parameters_BoolControl, { name: 'isInterpolated', param: IsInterpolatedParam, value: this.props.value.kind === 'interpolate', onChange: this.isInterpolatedChanged, isDisabled: this.props.isDisabled, onEnter: this.props.onEnter }));
    };
    ColorListControl.prototype.render = function () {
        return renderSimple({
            props: this.props,
            state: this.state,
            control: this.renderControl(),
            toggleHelp: this.toggleHelp,
            addOn: this.renderColors()
        });
    };
    return ColorListControl;
}(react["PureComponent"]));

var parameters_Vec3Control = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Vec3Control, _super);
    function Vec3Control() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.components = {
            0: param_definition["ParamDefinition"].Numeric(0, { step: _this.props.param.step }, { label: (_this.props.param.fieldLabels && _this.props.param.fieldLabels.x) || 'X' }),
            1: param_definition["ParamDefinition"].Numeric(0, { step: _this.props.param.step }, { label: (_this.props.param.fieldLabels && _this.props.param.fieldLabels.y) || 'Y' }),
            2: param_definition["ParamDefinition"].Numeric(0, { step: _this.props.param.step }, { label: (_this.props.param.fieldLabels && _this.props.param.fieldLabels.z) || 'Z' })
        };
        _this.componentChange = function (_a) {
            var name = _a.name, value = _a.value;
            var v = linear_algebra["Vec3"].copy(linear_algebra["Vec3"].zero(), _this.props.value);
            v[+name] = value;
            _this.change(v);
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    Vec3Control.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    Vec3Control.prototype.render = function () {
        var v = this.props.value;
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var p = Object(number["b" /* getPrecision */])(this.props.param.step || 0.01);
        var value = "[" + v[0].toFixed(p) + ", " + v[1].toFixed(p) + ", " + v[2].toFixed(p) + "]";
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, value) }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](parameters_ParameterControls, { params: this.components, values: v, onChange: this.componentChange, onEnter: this.props.onEnter })));
    };
    return Vec3Control;
}(react["PureComponent"]));

var parameters_Mat4Control = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Mat4Control, _super);
    function Mat4Control() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.components = {
            json: param_definition["ParamDefinition"].Text(JSON.stringify(Object(linear_algebra["Mat4"])()), { description: 'JSON array with 4x4 matrix in a column major (j * 4 + i indexing) format' })
        };
        _this.componentChange = function (_a) {
            var name = _a.name, value = _a.value;
            var v = linear_algebra["Mat4"].copy(Object(linear_algebra["Mat4"])(), _this.props.value);
            if (name === 'json') {
                linear_algebra["Mat4"].copy(v, JSON.parse(value));
            }
            else {
                v[+name] = value;
            }
            _this.change(v);
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    Mat4Control.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    Mat4Control.prototype.changeValue = function (idx) {
        var _this = this;
        return function (v) {
            var m = linear_algebra["Mat4"].copy(Object(linear_algebra["Mat4"])(), _this.props.value);
            m[idx] = v;
            _this.change(m);
        };
    };
    Object.defineProperty(Mat4Control.prototype, "grid", {
        get: function () {
            var v = this.props.value;
            var rows = [];
            for (var i = 0; i < 4; i++) {
                var row = [];
                for (var j = 0; j < 4; j++) {
                    row.push(react["createElement"](common["TextInput"], { key: j, numeric: true, delayMs: 50, value: linear_algebra["Mat4"].getValue(v, i, j), onChange: this.changeValue(4 * j + i), className: 'msp-form-control', blurOnEnter: true, isDisabled: this.props.isDisabled }));
                }
                rows.push(react["createElement"]("div", { className: 'msp-flex-row', key: i }, row));
            }
            return react["createElement"]("div", { className: 'msp-parameter-matrix' }, rows);
        },
        enumerable: false,
        configurable: true
    });
    Mat4Control.prototype.render = function () {
        var v = {
            json: JSON.stringify(this.props.value)
        };
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, '4\u00D74 Matrix') }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                this.grid,
                react["createElement"](parameters_ParameterControls, { params: this.components, values: v, onChange: this.componentChange, onEnter: this.props.onEnter })));
    };
    return Mat4Control;
}(react["PureComponent"]));

var parameters_UrlControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(UrlControl, _super);
    function UrlControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            var value = e.target.value;
            if (value !== assets["Asset"].getUrl(_this.props.value || '')) {
                _this.update(assets["Asset"].Url(value));
            }
        };
        _this.onKeyPress = function (e) {
            if ((e.keyCode === 13 || e.charCode === 13)) {
                if (_this.props.onEnter)
                    _this.props.onEnter();
            }
            e.stopPropagation();
        };
        return _this;
    }
    UrlControl.prototype.renderControl = function () {
        var placeholder = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"]("input", { type: 'text', value: assets["Asset"].getUrl(this.props.value || ''), placeholder: placeholder, onChange: this.onChange, onKeyPress: this.props.onEnter ? this.onKeyPress : void 0, disabled: this.props.isDisabled });
    };
    return UrlControl;
}(parameters_SimpleParam));

var parameters_FileControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(FileControl, _super);
    function FileControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChangeFile = function (e) {
            _this.change(e.target.files[0]);
        };
        return _this;
    }
    FileControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: assets["Asset"].File(value) });
    };
    FileControl.prototype.render = function () {
        var value = this.props.value;
        return react["createElement"]("div", { className: 'msp-btn msp-btn-block msp-btn-action msp-loader-msp-btn-file', style: { marginTop: '1px' } },
            value ? value.name : 'Select a file...',
            " ",
            react["createElement"]("input", { disabled: this.props.isDisabled, onChange: this.onChangeFile, type: 'file', multiple: false, accept: this.props.param.accept }));
    };
    return FileControl;
}(react["PureComponent"]));

var parameters_FileListControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(FileListControl, _super);
    function FileListControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChangeFileList = function (e) {
            _this.change(e.target.files);
        };
        return _this;
    }
    FileListControl.prototype.change = function (value) {
        var files = [];
        if (value) {
            for (var i = 0, il = value.length; i < il; ++i) {
                files.push(assets["Asset"].File(value[i]));
            }
        }
        this.props.onChange({ name: this.props.name, param: this.props.param, value: files });
    };
    FileListControl.prototype.render = function () {
        var value = this.props.value;
        var names = [];
        if (value) {
            for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
                var file = value_1[_i];
                names.push(file.name);
            }
        }
        var label = names.length === 0
            ? 'Select files...' : names.length === 1
            ? names[0] : names.length + " files selected";
        return react["createElement"]("div", { className: 'msp-btn msp-btn-block msp-btn-action msp-loader-msp-btn-file', style: { marginTop: '1px' } },
            label,
            " ",
            react["createElement"]("input", { disabled: this.props.isDisabled, onChange: this.onChangeFileList, type: 'file', multiple: true, accept: this.props.param.accept }));
    };
    return FileListControl;
}(react["PureComponent"]));

var parameters_MultiSelectControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(MultiSelectControl, _super);
    function MultiSelectControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    MultiSelectControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    MultiSelectControl.prototype.toggle = function (key) {
        var _this = this;
        return function (e) {
            if (_this.props.value.indexOf(key) < 0)
                _this.change(_this.props.value.concat(key));
            else
                _this.change(_this.props.value.filter(function (v) { return v !== key; }));
            e.currentTarget.blur();
        };
    };
    MultiSelectControl.prototype.render = function () {
        var _this = this;
        var current = this.props.value;
        var emptyLabel = this.props.param.emptyValue;
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, current.length === 0 && emptyLabel ? emptyLabel : current.length + " of " + this.props.param.options.length) }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' }, this.props.param.options.map(function (_a) {
                var value = _a[0], label = _a[1];
                var sel = current.indexOf(value) >= 0;
                return react["createElement"](common["Button"], { key: value, onClick: _this.toggle(value), disabled: _this.props.isDisabled, style: { marginTop: '1px' } },
                    react["createElement"]("span", { style: { float: sel ? 'left' : 'right' } }, sel ? "\u2713 " + label : label + " \u2717"));
            })));
    };
    return MultiSelectControl;
}(react["PureComponent"]));

var parameters_GroupControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(GroupControl, _super);
    function GroupControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: !!_this.props.param.isExpanded, showHelp: false };
        _this.onChangeParam = function (e) {
            var _a;
            _this.change(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.props.value), (_a = {}, _a[e.name] = e.value, _a)));
        };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        return _this;
    }
    GroupControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    GroupControl.prototype.pivoted = function () {
        var key = this.props.param.pivot;
        var params = this.props.param.params;
        var pivot = params[key];
        var Control = controlFor(pivot);
        var ctrl = react["createElement"](Control, { name: key, param: pivot, value: this.props.value[key], onChange: this.onChangeParam, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled });
        if (!this.state.isExpanded) {
            return react["createElement"]("div", { className: 'msp-mapped-parameter-group' },
                ctrl,
                react["createElement"](common["IconButton"], { svg: icons["MoreHorizSvg"], onClick: this.toggleExpanded, toggleState: this.state.isExpanded, title: "More Options" }));
        }
        var filtered = Object.create(null);
        for (var _i = 0, _a = Object.keys(params); _i < _a.length; _i++) {
            var k = _a[_i];
            if (k !== key)
                filtered[k] = params[k];
        }
        return react["createElement"]("div", { className: 'msp-mapped-parameter-group' },
            ctrl,
            react["createElement"](common["IconButton"], { svg: icons["MoreHorizSvg"], onClick: this.toggleExpanded, toggleState: this.state.isExpanded, title: "More Options" }),
            react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](parameters_ParameterControls, { params: filtered, onEnter: this.props.onEnter, values: this.props.value, onChange: this.onChangeParam, isDisabled: this.props.isDisabled })));
    };
    GroupControl.prototype.render = function () {
        var params = this.props.param.params;
        // Do not show if there are no params.
        if (Object.keys(params).length === 0)
            return null;
        if (this.props.param.pivot)
            return this.pivoted();
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var controls = react["createElement"](parameters_ParameterControls, { params: params, onChange: this.onChangeParam, values: this.props.value, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled });
        if (this.props.inMapped) {
            return react["createElement"]("div", { className: 'msp-control-offset' }, controls);
        }
        if (this.props.param.isFlat) {
            return controls;
        }
        return react["createElement"]("div", { className: 'msp-control-group-wrapper' },
            react["createElement"]("div", { className: 'msp-control-group-header' },
                react["createElement"]("button", { className: 'msp-btn msp-form-control msp-btn-block', onClick: this.toggleExpanded },
                    react["createElement"](icons["Icon"], { svg: this.state.isExpanded ? icons["ArrowDropDownSvg"] : icons["ArrowRightSvg"] }),
                    label)),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' }, controls));
    };
    return GroupControl;
}(react["PureComponent"]));

var parameters_MappedControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(MappedControl, _super);
    function MappedControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        // TODO: this could lead to a rare bug where the component is reused with different mapped control.
        // I think there are currently no cases where this could happen in the UI, but still need to watch out..
        _this.valuesCache = {};
        _this.onChangeName = function (e) {
            _this.change({ name: e.value, params: _this.getValues(e.value) });
        };
        _this.onChangeParam = function (e) {
            _this.setValues(_this.props.value.name, e.value);
            _this.change({ name: _this.props.value.name, params: e.value });
        };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        return _this;
    }
    MappedControl.prototype.setValues = function (name, values) {
        this.valuesCache[name] = values;
    };
    MappedControl.prototype.getValues = function (name) {
        if (name in this.valuesCache) {
            return this.valuesCache[name];
        }
        else {
            return this.props.param.map(name).defaultValue;
        }
    };
    MappedControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    MappedControl.prototype.areParamsEmpty = function (params) {
        for (var _i = 0, _a = Object.keys(params); _i < _a.length; _i++) {
            var k = _a[_i];
            if (!params[k].isHidden)
                return false;
        }
        return true;
    };
    MappedControl.prototype.render = function () {
        var _this = this;
        var value = this.props.value;
        var param = this.props.param.map(value.name);
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var Mapped = controlFor(param);
        var help = this.props.param.help;
        var select = help
            ? Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, this.props.param.select), { help: function (name) { return help({ name: name, params: _this.getValues(name) }); } }) : this.props.param.select;
        var Select = react["createElement"](parameters_SelectControl, { param: select, isDisabled: this.props.isDisabled, onChange: this.onChangeName, onEnter: this.props.onEnter, name: label, value: value.name });
        if (!Mapped) {
            return Select;
        }
        if (param.type === 'group' && !param.isFlat) {
            if (!this.areParamsEmpty(param.params)) {
                return react["createElement"]("div", { className: 'msp-mapped-parameter-group' },
                    Select,
                    react["createElement"](common["IconButton"], { svg: icons["MoreHorizSvg"], onClick: this.toggleExpanded, toggleState: this.state.isExpanded, title: label + " Properties" }),
                    this.state.isExpanded && react["createElement"](parameters_GroupControl, { inMapped: true, param: param, value: value.params, name: value.name, onChange: this.onChangeParam, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled }));
            }
            return Select;
        }
        return react["createElement"](react["Fragment"], null,
            Select,
            react["createElement"](Mapped, { param: param, value: value.params, name: value.name, onChange: this.onChangeParam, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled }));
    };
    return MappedControl;
}(react["PureComponent"]));

var parameters_ObjectListEditor = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ObjectListEditor, _super);
    function ObjectListEditor() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { current: _this.props.value };
        _this.onChangeParam = function (e) {
            var _a;
            _this.setState({ current: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.state.current), (_a = {}, _a[e.name] = e.value, _a)) });
        };
        _this.apply = function () {
            _this.props.apply(_this.state.current);
        };
        return _this;
    }
    ObjectListEditor.prototype.componentDidUpdate = function (prevProps) {
        if (this.props.params !== prevProps.params || this.props.value !== prevProps.value) {
            this.setState({ current: this.props.value });
        }
    };
    ObjectListEditor.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"](parameters_ParameterControls, { params: this.props.params, onChange: this.onChangeParam, values: this.state.current, onEnter: this.apply, isDisabled: this.props.isDisabled }),
            react["createElement"]("button", { className: "msp-btn msp-btn-block msp-form-control msp-control-top-offset", onClick: this.apply, disabled: this.props.isDisabled }, this.props.isUpdate ? 'Update' : 'Add'));
    };
    return ObjectListEditor;
}(react["PureComponent"]));
var parameters_ObjectListItem = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ObjectListItem, _super);
    function ObjectListItem() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.update = function (v) {
            // this.setState({ isExpanded: false }); // TODO auto update? mark changed state?
            _this.props.actions.update(v, _this.props.index);
        };
        _this.moveUp = function () {
            _this.props.actions.move(_this.props.index, -1);
        };
        _this.moveDown = function () {
            _this.props.actions.move(_this.props.index, 1);
        };
        _this.remove = function () {
            _this.setState({ isExpanded: false });
            _this.props.actions.remove(_this.props.index);
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    ObjectListItem.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-param-object-list-item' },
                react["createElement"]("button", { className: 'msp-btn msp-btn-block msp-form-control', onClick: this.toggleExpanded },
                    react["createElement"]("span", null, this.props.index + 1 + ": "),
                    this.props.param.getLabel(this.props.value)),
                react["createElement"]("div", null,
                    react["createElement"](common["IconButton"], { svg: icons["ArrowDownwardSvg"], title: 'Move Up', onClick: this.moveUp, small: true }),
                    react["createElement"](common["IconButton"], { svg: icons["ArrowUpwardSvg"], title: 'Move Down', onClick: this.moveDown, small: true }),
                    react["createElement"](common["IconButton"], { svg: icons["DeleteOutlinedSvg"], title: 'Remove', onClick: this.remove, small: true }))),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](parameters_ObjectListEditor, { params: this.props.param.element, apply: this.update, value: this.props.value, isUpdate: true, isDisabled: this.props.isDisabled })));
    };
    return ObjectListItem;
}(react["PureComponent"]));
var parameters_ObjectListControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ObjectListControl, _super);
    function ObjectListControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isExpanded: false };
        _this.add = function (v) {
            _this.change(Object(tslib_es6["__spreadArrays"])(_this.props.value, [v]));
        };
        _this.actions = {
            update: function (v, i) {
                var value = _this.props.value.slice(0);
                value[i] = v;
                _this.change(value);
            },
            move: function (i, dir) {
                var xs = _this.props.value;
                if (xs.length === 1)
                    return;
                var j = (i + dir) % xs.length;
                if (j < 0)
                    j += xs.length;
                xs = xs.slice(0);
                var t = xs[i];
                xs[i] = xs[j];
                xs[j] = t;
                _this.change(xs);
            },
            remove: function (i) {
                var xs = _this.props.value;
                var update = [];
                for (var j = 0; j < xs.length; j++) {
                    if (i !== j)
                        update.push(xs[j]);
                }
                _this.change(update);
            }
        };
        _this.toggleExpanded = function (e) {
            _this.setState({ isExpanded: !_this.state.isExpanded });
            e.currentTarget.blur();
        };
        return _this;
    }
    ObjectListControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    ObjectListControl.prototype.render = function () {
        var _this = this;
        var v = this.props.value;
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var value = v.length + " item" + (v.length !== 1 ? 's' : '');
        return react["createElement"](react["Fragment"], null,
            react["createElement"](common["ControlRow"], { label: label, control: react["createElement"]("button", { onClick: this.toggleExpanded, disabled: this.props.isDisabled }, value) }),
            this.state.isExpanded && react["createElement"]("div", { className: 'msp-control-offset' },
                this.props.value.map(function (v, i) { return react["createElement"](parameters_ObjectListItem, { key: i, param: _this.props.param, value: v, index: i, actions: _this.actions, isDisabled: _this.props.isDisabled }); }),
                react["createElement"](common["ControlGroup"], { header: 'New Item' },
                    react["createElement"](parameters_ObjectListEditor, { params: this.props.param.element, apply: this.add, value: this.props.param.ctor(), isDisabled: this.props.isDisabled }))));
    };
    return ObjectListControl;
}(react["PureComponent"]));

var parameters_ConditionedControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ConditionedControl, _super);
    function ConditionedControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChangeCondition = function (e) {
            _this.change(_this.props.param.conditionedValue(_this.props.value, e.value));
        };
        _this.onChangeParam = function (e) {
            _this.change(e.value);
        };
        return _this;
    }
    ConditionedControl.prototype.change = function (value) {
        this.props.onChange({ name: this.props.name, param: this.props.param, value: value });
    };
    ConditionedControl.prototype.render = function () {
        var value = this.props.value;
        var condition = this.props.param.conditionForValue(value);
        var param = this.props.param.conditionParams[condition];
        var label = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        var Conditioned = controlFor(param);
        var select = react["createElement"](parameters_SelectControl, { param: this.props.param.select, isDisabled: this.props.isDisabled, onChange: this.onChangeCondition, onEnter: this.props.onEnter, name: label + " Kind", value: condition });
        if (!Conditioned) {
            return select;
        }
        return react["createElement"](react["Fragment"], null,
            select,
            react["createElement"](Conditioned, { param: param, value: value, name: label, onChange: this.onChangeParam, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled }));
    };
    return ConditionedControl;
}(react["PureComponent"]));

var parameters_ConvertedControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ConvertedControl, _super);
    function ConvertedControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            _this.props.onChange({
                name: _this.props.name,
                param: _this.props.param,
                value: _this.props.param.toValue(e.value)
            });
        };
        return _this;
    }
    ConvertedControl.prototype.render = function () {
        var value = this.props.param.fromValue(this.props.value);
        var Converted = controlFor(this.props.param.converted);
        if (!Converted)
            return null;
        return react["createElement"](Converted, { param: this.props.param.converted, value: value, name: this.props.name, onChange: this.onChange, onEnter: this.props.onEnter, isDisabled: this.props.isDisabled });
    };
    return ConvertedControl;
}(react["PureComponent"]));

var parameters_ScriptControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ScriptControl, _super);
    function ScriptControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (e) {
            var value = e.target.value;
            if (value !== _this.props.value.expression) {
                _this.update({ language: _this.props.value.language, expression: value });
            }
        };
        _this.onKeyPress = function (e) {
            if ((e.keyCode === 13 || e.charCode === 13)) {
                if (_this.props.onEnter)
                    _this.props.onEnter();
            }
            e.stopPropagation();
        };
        return _this;
    }
    ScriptControl.prototype.renderControl = function () {
        // TODO: improve!
        var placeholder = this.props.param.label || Object(string["a" /* camelCaseToWords */])(this.props.name);
        return react["createElement"]("input", { type: 'text', value: this.props.value.expression || '', placeholder: placeholder, onChange: this.onChange, onKeyPress: this.props.onEnter ? this.onKeyPress : void 0, disabled: this.props.isDisabled });
    };
    return ScriptControl;
}(parameters_SimpleParam));

//# sourceMappingURL=parameters.js.map

/***/ }),
/* 67 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ReaderResult; });
/*
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * from https://github.com/dsehnal/CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var ReaderResult;
(function (ReaderResult) {
    function error(message, line) {
        if (line === void 0) { line = -1; }
        return new Error(message, line);
    }
    ReaderResult.error = error;
    function success(result, warnings) {
        if (warnings === void 0) { warnings = []; }
        return new Success(result, warnings);
    }
    ReaderResult.success = success;
    var Error = /** @class */ (function () {
        function Error(message, line) {
            this.message = message;
            this.line = line;
            this.isError = true;
        }
        Error.prototype.toString = function () {
            if (this.line >= 0) {
                return "[Line " + this.line + "] " + this.message;
            }
            return this.message;
        };
        return Error;
    }());
    ReaderResult.Error = Error;
    var Success = /** @class */ (function () {
        function Success(result, warnings) {
            this.result = result;
            this.warnings = warnings;
            this.isError = false;
        }
        return Success;
    }());
    ReaderResult.Success = Success;
})(ReaderResult || (ReaderResult = {}));

//# sourceMappingURL=result.js.map

/***/ }),
/* 68 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginBehavior", function() { return PluginBehavior; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(8);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(16);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var PluginBehavior;
(function (PluginBehavior) {
    var Root = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Root, _super);
        function Root() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Root;
    }(_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__[/* PluginStateObject */ "a"].Create({ name: 'Root', typeClass: 'Root' })));
    PluginBehavior.Root = Root;
    var Category = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Category, _super);
        function Category() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Category;
    }(_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__[/* PluginStateObject */ "a"].Create({ name: 'Category', typeClass: 'Object' })));
    PluginBehavior.Category = Category;
    var Behavior = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Behavior, _super);
        function Behavior() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return Behavior;
    }(_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__[/* PluginStateObject */ "a"].CreateBehavior({ name: 'Behavior' })));
    PluginBehavior.Behavior = Behavior;
    PluginBehavior.Categories = {
        'common': 'Common',
        'representation': 'Representation',
        'interaction': 'Interaction',
        'custom-props': 'Custom Properties',
        'misc': 'Miscellaneous'
    };
    PluginBehavior.CreateCategory = _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__[/* PluginStateTransform */ "b"].BuiltIn({
        name: 'create-behavior-category',
        display: { name: 'Behavior Category' },
        from: Root,
        to: Category,
        params: {
            label: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Text('', { isHidden: true }),
        }
    })({
        apply: function (_a) {
            var params = _a.params;
            return new Category({}, { label: params.label });
        }
    });
    var categoryMap = new Map();
    function getCategoryId(t) {
        return categoryMap.get(t.id);
    }
    PluginBehavior.getCategoryId = getCategoryId;
    function create(params) {
        var t = _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_1__[/* PluginStateTransform */ "b"].CreateBuiltIn({
            name: params.name,
            display: params.display,
            from: [Root],
            to: [Behavior],
            params: params.params,
            apply: function (_a, ctx) {
                var p = _a.params;
                var label = params.label ? params.label(p) : { label: params.display.name, description: params.display.description };
                return new Behavior(new params.ctor(ctx, p), label);
            },
            update: function (_a) {
                var _this = this;
                var b = _a.b, newParams = _a.newParams;
                return _mol_task__WEBPACK_IMPORTED_MODULE_3__[/* Task */ "b"].create('Update Behavior', function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                    var updated;
                    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                if (!b.data.update)
                                    return [2 /*return*/, _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateTransformer"].UpdateResult.Unchanged];
                                return [4 /*yield*/, b.data.update(newParams)];
                            case 1:
                                updated = _a.sent();
                                return [2 /*return*/, updated ? _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateTransformer"].UpdateResult.Updated : _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateTransformer"].UpdateResult.Unchanged];
                        }
                    });
                }); });
            },
            canAutoUpdate: params.canAutoUpdate
        });
        categoryMap.set(t.id, params.category);
        return t;
    }
    PluginBehavior.create = create;
    function simpleCommandHandler(cmd, action) {
        return /** @class */ (function () {
            // TODO can't be private due to bug with generating declerations, see https://github.com/Microsoft/TypeScript/issues/17293
            function class_1(/** private */ ctx) {
                this.ctx = ctx;
                // TODO can't be private due to bug with generating declerations, see https://github.com/Microsoft/TypeScript/issues/17293
                /** private */ this.sub = void 0;
            }
            class_1.prototype.register = function () {
                var _this = this;
                this.sub = cmd.subscribe(this.ctx, function (data) { return action(data, _this.ctx); });
            };
            class_1.prototype.unregister = function () {
                if (this.sub)
                    this.sub.unsubscribe();
                this.sub = void 0;
            };
            return class_1;
        }());
    }
    PluginBehavior.simpleCommandHandler = simpleCommandHandler;
    var Handler = /** @class */ (function () {
        function Handler(ctx, params) {
            this.ctx = ctx;
            this.params = params;
            this.subs = [];
        }
        Handler.prototype.subscribeCommand = function (cmd, action) {
            this.subs.push(cmd.subscribe(this.ctx, action));
        };
        Handler.prototype.subscribeObservable = function (o, action) {
            this.subs.push(o.subscribe(action));
        };
        Handler.prototype.track = function (sub) {
            this.subs.push(sub);
        };
        Handler.prototype.unregister = function () {
            for (var _i = 0, _a = this.subs; _i < _a.length; _i++) {
                var s = _a[_i];
                s.unsubscribe();
            }
            this.subs = [];
        };
        Handler.prototype.update = function (params) {
            if (Object(_mol_util__WEBPACK_IMPORTED_MODULE_5__[/* shallowEqualObjects */ "m"])(params, this.params))
                return false;
            this.params = params;
            return true;
        };
        return Handler;
    }());
    PluginBehavior.Handler = Handler;
    var WithSubscribers = /** @class */ (function () {
        function WithSubscribers(plugin, params) {
            this.plugin = plugin;
            this.params = params;
            this.subs = [];
        }
        WithSubscribers.prototype.subscribeCommand = function (cmd, action) {
            this.subs.push(cmd.subscribe(this.plugin, action));
        };
        WithSubscribers.prototype.subscribeObservable = function (o, action) {
            this.subs.push(o.subscribe(action));
        };
        WithSubscribers.prototype.unregister = function () {
            for (var _i = 0, _a = this.subs; _i < _a.length; _i++) {
                var s = _a[_i];
                s.unsubscribe();
            }
            this.subs = [];
        };
        return WithSubscribers;
    }());
    PluginBehavior.WithSubscribers = WithSubscribers;
})(PluginBehavior || (PluginBehavior = {}));
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 69 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Visual; });
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(182);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(53);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5);
/* harmony import */ var _mol_geo_geometry_overpaint_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(134);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(6);
/* harmony import */ var _mol_geo_geometry_transparency_data__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(142);
/* harmony import */ var _mol_geo_geometry_clipping_data__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(143);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










// export type VisualFactory<D, P extends PD.Params> = (ctx: VisualContext) => Visual<D, P>

var Visual;
(function (Visual) {
    function setVisibility(renderObject, visible) {
        if (renderObject)
            renderObject.state.visible = visible;
    }
    Visual.setVisibility = setVisibility;
    function setAlphaFactor(renderObject, alphaFactor) {
        if (renderObject)
            renderObject.state.alphaFactor = alphaFactor;
    }
    Visual.setAlphaFactor = setAlphaFactor;
    function setPickable(renderObject, pickable) {
        if (renderObject)
            renderObject.state.pickable = pickable;
    }
    Visual.setPickable = setPickable;
    function mark(renderObject, loci, action, lociApply) {
        if (!renderObject)
            return false;
        var _a = renderObject.values, tMarker = _a.tMarker, uGroupCount = _a.uGroupCount, instanceCount = _a.instanceCount;
        var count = uGroupCount.ref.value * instanceCount.ref.value;
        var array = tMarker.ref.value.array;
        var changed = false;
        if (Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["isEveryLoci"])(loci)) {
            changed = Object(_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__[/* applyMarkerAction */ "c"])(array, _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].ofLength(count), action);
        }
        else if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["isEmptyLoci"])(loci)) {
            changed = lociApply(loci, function (interval) { return Object(_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__[/* applyMarkerAction */ "c"])(array, interval, action); }, true);
        }
        if (changed)
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(tMarker, tMarker.ref.value);
        return changed;
    }
    Visual.mark = mark;
    function setOverpaint(renderObject, overpaint, lociApply, clear) {
        if (!renderObject)
            return;
        var _a = renderObject.values, tOverpaint = _a.tOverpaint, uGroupCount = _a.uGroupCount, instanceCount = _a.instanceCount;
        var count = uGroupCount.ref.value * instanceCount.ref.value;
        // ensure texture has right size
        Object(_mol_geo_geometry_overpaint_data__WEBPACK_IMPORTED_MODULE_6__[/* createOverpaint */ "d"])(overpaint.layers.length ? count : 0, renderObject.values);
        var array = tOverpaint.ref.value.array;
        // clear all if requested
        if (clear)
            Object(_mol_geo_geometry_overpaint_data__WEBPACK_IMPORTED_MODULE_6__[/* clearOverpaint */ "b"])(array, 0, count);
        var _loop_1 = function (i, il) {
            var _a = overpaint.layers[i], loci = _a.loci, color = _a.color, clear_1 = _a.clear;
            var apply = function (interval) {
                var start = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].start(interval);
                var end = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].end(interval);
                return clear_1
                    ? Object(_mol_geo_geometry_overpaint_data__WEBPACK_IMPORTED_MODULE_6__[/* clearOverpaint */ "b"])(array, start, end)
                    : Object(_mol_geo_geometry_overpaint_data__WEBPACK_IMPORTED_MODULE_6__[/* applyOverpaintColor */ "a"])(array, start, end, color);
            };
            lociApply(loci, apply, false);
        };
        for (var i = 0, il = overpaint.layers.length; i < il; ++i) {
            _loop_1(i, il);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(tOverpaint, tOverpaint.ref.value);
    }
    Visual.setOverpaint = setOverpaint;
    function setTransparency(renderObject, transparency, lociApply, clear) {
        if (!renderObject)
            return;
        var _a = renderObject.values, tTransparency = _a.tTransparency, uGroupCount = _a.uGroupCount, instanceCount = _a.instanceCount;
        var count = uGroupCount.ref.value * instanceCount.ref.value;
        // ensure texture has right size and variant
        Object(_mol_geo_geometry_transparency_data__WEBPACK_IMPORTED_MODULE_8__[/* createTransparency */ "d"])(transparency.layers.length ? count : 0, renderObject.values);
        var array = tTransparency.ref.value.array;
        // clear if requested
        if (clear)
            Object(_mol_geo_geometry_transparency_data__WEBPACK_IMPORTED_MODULE_8__[/* clearTransparency */ "b"])(array, 0, count);
        var _loop_2 = function (i, il) {
            var _a = transparency.layers[i], loci = _a.loci, value = _a.value;
            var apply = function (interval) {
                var start = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].start(interval);
                var end = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].end(interval);
                return Object(_mol_geo_geometry_transparency_data__WEBPACK_IMPORTED_MODULE_8__[/* applyTransparencyValue */ "a"])(array, start, end, value);
            };
            lociApply(loci, apply, false);
        };
        for (var i = 0, il = transparency.layers.length; i < il; ++i) {
            _loop_2(i, il);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(tTransparency, tTransparency.ref.value);
    }
    Visual.setTransparency = setTransparency;
    function setClipping(renderObject, clipping, lociApply, clear) {
        if (!renderObject)
            return;
        var _a = renderObject.values, tClipping = _a.tClipping, uGroupCount = _a.uGroupCount, instanceCount = _a.instanceCount;
        var count = uGroupCount.ref.value * instanceCount.ref.value;
        // ensure texture has right size
        Object(_mol_geo_geometry_clipping_data__WEBPACK_IMPORTED_MODULE_9__[/* createClipping */ "c"])(clipping.layers.length ? count : 0, renderObject.values);
        var array = tClipping.ref.value.array;
        // clear if requested
        if (clear)
            Object(_mol_geo_geometry_clipping_data__WEBPACK_IMPORTED_MODULE_9__[/* clearClipping */ "b"])(array, 0, count);
        var _loop_3 = function (i, il) {
            var _a = clipping.layers[i], loci = _a.loci, groups = _a.groups;
            var apply = function (interval) {
                var start = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].start(interval);
                var end = _mol_data_int__WEBPACK_IMPORTED_MODULE_7__["Interval"].end(interval);
                return Object(_mol_geo_geometry_clipping_data__WEBPACK_IMPORTED_MODULE_9__[/* applyClippingGroups */ "a"])(array, start, end, groups);
            };
            lociApply(loci, apply, false);
        };
        for (var i = 0, il = clipping.layers.length; i < il; ++i) {
            _loop_3(i, il);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(tClipping, tClipping.ref.value);
    }
    Visual.setClipping = setClipping;
    function setTransform(renderObject, transform, instanceTransforms) {
        if (!renderObject || (!transform && !instanceTransforms))
            return;
        var values = renderObject.values;
        if (transform) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Mat4"].copy(values.matrix.ref.value, transform);
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.matrix, values.matrix.ref.value);
        }
        if (instanceTransforms) {
            values.extraTransform.ref.value.set(instanceTransforms);
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.extraTransform, values.extraTransform.ref.value);
        }
        else if (instanceTransforms === null) {
            Object(_mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_3__[/* fillIdentityTransform */ "c"])(values.extraTransform.ref.value, values.instanceCount.ref.value);
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.extraTransform, values.extraTransform.ref.value);
        }
        Object(_mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_3__[/* updateTransformData */ "d"])(values);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_4__[/* calculateTransformBoundingSphere */ "b"])(values.invariantBoundingSphere.ref.value, values.aTransform.ref.value, values.instanceCount.ref.value);
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
    }
    Visual.setTransform = setTransform;
})(Visual || (Visual = {}));
//# sourceMappingURL=visual.js.map

/***/ }),
/* 70 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Subscription; });
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(100);
/* harmony import */ var _util_isObject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(301);
/* harmony import */ var _util_isFunction__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(215);
/* harmony import */ var _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(278);
/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */




var Subscription = /*@__PURE__*/ (function () {
    function Subscription(unsubscribe) {
        this.closed = false;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (unsubscribe) {
            this._unsubscribe = unsubscribe;
        }
    }
    Subscription.prototype.unsubscribe = function () {
        var errors;
        if (this.closed) {
            return;
        }
        var _a = this, _parentOrParents = _a._parentOrParents, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions;
        this.closed = true;
        this._parentOrParents = null;
        this._subscriptions = null;
        if (_parentOrParents instanceof Subscription) {
            _parentOrParents.remove(this);
        }
        else if (_parentOrParents !== null) {
            for (var index = 0; index < _parentOrParents.length; ++index) {
                var parent_1 = _parentOrParents[index];
                parent_1.remove(this);
            }
        }
        if (Object(_util_isFunction__WEBPACK_IMPORTED_MODULE_2__[/* isFunction */ "a"])(_unsubscribe)) {
            try {
                _unsubscribe.call(this);
            }
            catch (e) {
                errors = e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__[/* UnsubscriptionError */ "a"] ? flattenUnsubscriptionErrors(e.errors) : [e];
            }
        }
        if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_0__[/* isArray */ "a"])(_subscriptions)) {
            var index = -1;
            var len = _subscriptions.length;
            while (++index < len) {
                var sub = _subscriptions[index];
                if (Object(_util_isObject__WEBPACK_IMPORTED_MODULE_1__[/* isObject */ "a"])(sub)) {
                    try {
                        sub.unsubscribe();
                    }
                    catch (e) {
                        errors = errors || [];
                        if (e instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__[/* UnsubscriptionError */ "a"]) {
                            errors = errors.concat(flattenUnsubscriptionErrors(e.errors));
                        }
                        else {
                            errors.push(e);
                        }
                    }
                }
            }
        }
        if (errors) {
            throw new _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__[/* UnsubscriptionError */ "a"](errors);
        }
    };
    Subscription.prototype.add = function (teardown) {
        var subscription = teardown;
        if (!teardown) {
            return Subscription.EMPTY;
        }
        switch (typeof teardown) {
            case 'function':
                subscription = new Subscription(teardown);
            case 'object':
                if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {
                    return subscription;
                }
                else if (this.closed) {
                    subscription.unsubscribe();
                    return subscription;
                }
                else if (!(subscription instanceof Subscription)) {
                    var tmp = subscription;
                    subscription = new Subscription();
                    subscription._subscriptions = [tmp];
                }
                break;
            default: {
                throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');
            }
        }
        var _parentOrParents = subscription._parentOrParents;
        if (_parentOrParents === null) {
            subscription._parentOrParents = this;
        }
        else if (_parentOrParents instanceof Subscription) {
            if (_parentOrParents === this) {
                return subscription;
            }
            subscription._parentOrParents = [_parentOrParents, this];
        }
        else if (_parentOrParents.indexOf(this) === -1) {
            _parentOrParents.push(this);
        }
        else {
            return subscription;
        }
        var subscriptions = this._subscriptions;
        if (subscriptions === null) {
            this._subscriptions = [subscription];
        }
        else {
            subscriptions.push(subscription);
        }
        return subscription;
    };
    Subscription.prototype.remove = function (subscription) {
        var subscriptions = this._subscriptions;
        if (subscriptions) {
            var subscriptionIndex = subscriptions.indexOf(subscription);
            if (subscriptionIndex !== -1) {
                subscriptions.splice(subscriptionIndex, 1);
            }
        }
    };
    Subscription.EMPTY = (function (empty) {
        empty.closed = true;
        return empty;
    }(new Subscription()));
    return Subscription;
}());

function flattenUnsubscriptionErrors(errors) {
    return errors.reduce(function (errs, err) { return errs.concat((err instanceof _util_UnsubscriptionError__WEBPACK_IMPORTED_MODULE_3__[/* UnsubscriptionError */ "a"]) ? err.errors : err); }, []);
}
//# sourceMappingURL=Subscription.js.map


/***/ }),
/* 71 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MmcifFormat", function() { return MmcifFormat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "trajectoryFromMmCIF", function() { return trajectoryFromMmCIF; });
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(16);
/* harmony import */ var _mol_io_reader_cif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(31);
/* harmony import */ var _basic_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(154);
/* harmony import */ var _property_symmetry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(113);
/* harmony import */ var _property_secondary_structure__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(280);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(7);
/* harmony import */ var _property_anisotropic__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(211);
/* harmony import */ var _property_bonds_comp__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(325);
/* harmony import */ var _property_bonds_struct_conn__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(267);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









function modelSymmetryFromMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return;
    return _property_symmetry__WEBPACK_IMPORTED_MODULE_3__[/* ModelSymmetry */ "a"].fromData(model.sourceData.data.db);
}
_property_symmetry__WEBPACK_IMPORTED_MODULE_3__[/* ModelSymmetry */ "a"].Provider.formatRegistry.add('mmCIF', modelSymmetryFromMmcif);
function secondaryStructureFromMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return;
    var _a = model.sourceData.data.db, struct_conf = _a.struct_conf, struct_sheet_range = _a.struct_sheet_range;
    return _property_secondary_structure__WEBPACK_IMPORTED_MODULE_4__[/* ModelSecondaryStructure */ "a"].fromStruct(struct_conf, struct_sheet_range, model.atomicHierarchy);
}
_property_secondary_structure__WEBPACK_IMPORTED_MODULE_4__[/* ModelSecondaryStructure */ "a"].Provider.formatRegistry.add('mmCIF', secondaryStructureFromMmcif);
function atomSiteAnisotropFromMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return;
    var atom_site_anisotrop = model.sourceData.data.db.atom_site_anisotrop;
    var data = _mol_data_db__WEBPACK_IMPORTED_MODULE_5__["Table"].ofColumns(_property_anisotropic__WEBPACK_IMPORTED_MODULE_6__[/* AtomSiteAnisotrop */ "a"].Schema, atom_site_anisotrop);
    var elementToAnsiotrop = _property_anisotropic__WEBPACK_IMPORTED_MODULE_6__[/* AtomSiteAnisotrop */ "a"].getElementToAnsiotrop(model.atomicConformation.atomId, atom_site_anisotrop.id);
    return { data: data, elementToAnsiotrop: elementToAnsiotrop };
}
function atomSiteAnisotropApplicableMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return false;
    return model.sourceData.data.db.atom_site_anisotrop.U.isDefined;
}
_property_anisotropic__WEBPACK_IMPORTED_MODULE_6__[/* AtomSiteAnisotrop */ "a"].Provider.formatRegistry.add('mmCIF', atomSiteAnisotropFromMmcif, atomSiteAnisotropApplicableMmcif);
function componentBondFromMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return;
    var chem_comp_bond = model.sourceData.data.db.chem_comp_bond;
    if (chem_comp_bond._rowCount === 0)
        return;
    return {
        data: chem_comp_bond,
        entries: _property_bonds_comp__WEBPACK_IMPORTED_MODULE_7__[/* ComponentBond */ "a"].getEntriesFromChemCompBond(chem_comp_bond)
    };
}
_property_bonds_comp__WEBPACK_IMPORTED_MODULE_7__[/* ComponentBond */ "a"].Provider.formatRegistry.add('mmCIF', componentBondFromMmcif);
function structConnFromMmcif(model) {
    if (!MmcifFormat.is(model.sourceData))
        return;
    var struct_conn = model.sourceData.data.db.struct_conn;
    if (struct_conn._rowCount === 0)
        return;
    var entries = _property_bonds_struct_conn__WEBPACK_IMPORTED_MODULE_8__[/* StructConn */ "a"].getEntriesFromStructConn(struct_conn, model);
    return {
        data: struct_conn,
        byAtomIndex: _property_bonds_struct_conn__WEBPACK_IMPORTED_MODULE_8__[/* StructConn */ "a"].getAtomIndexFromEntries(entries),
        entries: entries,
    };
}
_property_bonds_struct_conn__WEBPACK_IMPORTED_MODULE_8__[/* StructConn */ "a"].Provider.formatRegistry.add('mmCIF', structConnFromMmcif);
//

var MmcifFormat;
(function (MmcifFormat) {
    function is(x) {
        return x.kind === 'mmCIF';
    }
    MmcifFormat.is = is;
    function fromFrame(frame, db) {
        if (!db)
            db = _mol_io_reader_cif__WEBPACK_IMPORTED_MODULE_1__[/* CIF */ "a"].schema.mmCIF(frame);
        return { kind: 'mmCIF', name: db._name, data: { db: db, frame: frame } };
    }
    MmcifFormat.fromFrame = fromFrame;
})(MmcifFormat || (MmcifFormat = {}));
function trajectoryFromMmCIF(frame) {
    var format = MmcifFormat.fromFrame(frame);
    return _mol_task__WEBPACK_IMPORTED_MODULE_0__[/* Task */ "b"].create('Create mmCIF Model', function (ctx) { return Object(_basic_parser__WEBPACK_IMPORTED_MODULE_2__[/* createModels */ "a"])(format.data.db, format, ctx); });
}
//# sourceMappingURL=mmcif.js.map

/***/ }),
/* 72 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLabelOptions", function() { return DefaultLabelOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "lociLabel", function() { return lociLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "structureElementStatsLabel", function() { return structureElementStatsLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bondLabel", function() { return bondLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bundleLabel", function() { return bundleLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "_bundleLabel", function() { return _bundleLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elementLabel", function() { return elementLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "distanceLabel", function() { return distanceLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "angleLabel", function() { return angleLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dihedralLabel", function() { return dihedralLabel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(6);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1);
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(46);
/* harmony import */ var _mol_model_volume__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(36);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var DefaultLabelOptions = {
    granularity: 'element',
    condensed: false,
    reverse: false,
    countsOnly: false,
    hidePrefix: false,
    htmlStyling: true,
};
function lociLabel(loci, options) {
    if (options === void 0) { options = {}; }
    switch (loci.kind) {
        case 'structure-loci':
            return loci.structure.models.map(function (m) { return m.entry; }).filter(function (l) { return !!l; }).join(', ');
        case 'element-loci':
            return structureElementStatsLabel(_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Stats.ofLoci(loci), options);
        case 'bond-loci':
            var bond = loci.bonds[0];
            return bond ? bondLabel(bond) : '';
        case 'shape-loci':
            return loci.shape.name;
        case 'group-loci':
            var g = loci.groups[0];
            return g ? loci.shape.getLabel(_mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].start(g.ids), g.instance) : '';
        case 'every-loci':
            return 'Everything';
        case 'empty-loci':
            return 'Nothing';
        case 'data-loci':
            return loci.getLabel();
        case 'volume-loci':
            return loci.volume.label || 'Volume';
        case 'isosurface-loci':
            return [
                "" + (loci.volume.label || 'Volume'),
                "Isosurface at " + _mol_model_volume__WEBPACK_IMPORTED_MODULE_7__[/* Volume */ "b"].IsoValue.toString(loci.isoValue)
            ].join(' | ');
        case 'cell-loci':
            var size = _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].size(loci.indices);
            var start = _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].start(loci.indices);
            var absVal = _mol_model_volume__WEBPACK_IMPORTED_MODULE_7__[/* Volume */ "b"].IsoValue.absolute(loci.volume.grid.cells.data[start]);
            var relVal = _mol_model_volume__WEBPACK_IMPORTED_MODULE_7__[/* Volume */ "b"].IsoValue.toRelative(absVal, loci.volume.grid.stats);
            var label = [
                "" + (loci.volume.label || 'Volume'),
                "" + (size === 1 ? "Cell #" + start : size + " Cells")
            ];
            if (size === 1) {
                label.push(_mol_model_volume__WEBPACK_IMPORTED_MODULE_7__[/* Volume */ "b"].IsoValue.toString(absVal) + " (" + _mol_model_volume__WEBPACK_IMPORTED_MODULE_7__[/* Volume */ "b"].IsoValue.toString(relVal) + ")");
            }
            return label.join(' | ');
    }
}
function countLabel(count, label) {
    return count === 1 ? "1 " + label : count + " " + label + "s";
}
function otherLabel(count, location, granularity, hidePrefix, reverse, condensed) {
    return elementLabel(location, { granularity: granularity, hidePrefix: hidePrefix, reverse: reverse, condensed: condensed }) + " <small>[+ " + countLabel(count - 1, "other " + Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* capitalize */ "b"])(granularity)) + "]</small>";
}
/** Gets residue count of the model chain segments the unit is a subset of */
function getResidueCount(unit) {
    var elements = unit.elements, model = unit.model;
    var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments;
    var elementStart = chainAtomSegments.offsets[chainAtomSegments.index[elements[0]]];
    var elementEnd = chainAtomSegments.offsets[chainAtomSegments.index[elements[elements.length - 1]] + 1] - 1;
    return residueAtomSegments.index[elementEnd] - residueAtomSegments.index[elementStart] + 1;
}
function structureElementStatsLabel(stats, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), options);
    var label = _structureElementStatsLabel(stats, o.countsOnly, o.hidePrefix, o.condensed, o.reverse);
    return o.htmlStyling ? label : Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* stripTags */ "e"])(label);
}
function _structureElementStatsLabel(stats, countsOnly, hidePrefix, condensed, reverse) {
    if (countsOnly === void 0) { countsOnly = false; }
    if (hidePrefix === void 0) { hidePrefix = false; }
    if (condensed === void 0) { condensed = false; }
    if (reverse === void 0) { reverse = false; }
    var structureCount = stats.structureCount, chainCount = stats.chainCount, residueCount = stats.residueCount, conformationCount = stats.conformationCount, elementCount = stats.elementCount;
    if (!countsOnly && elementCount === 1 && residueCount === 0 && chainCount === 0) {
        return elementLabel(stats.firstElementLoc, { hidePrefix: hidePrefix, condensed: condensed, granularity: 'element', reverse: reverse });
    }
    else if (!countsOnly && elementCount === 0 && residueCount === 1 && chainCount === 0) {
        return elementLabel(stats.firstResidueLoc, { hidePrefix: hidePrefix, condensed: condensed, granularity: 'residue', reverse: reverse });
    }
    else if (!countsOnly && elementCount === 0 && residueCount === 0 && chainCount === 1) {
        var unit = stats.firstChainLoc.unit;
        var granularity = (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isAtomic(unit) && getResidueCount(unit) === 1)
            ? 'residue' : _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].Traits.is(unit.traits, 1 /* MultiChain */)
            ? 'residue' : 'chain';
        return elementLabel(stats.firstChainLoc, { hidePrefix: hidePrefix, condensed: condensed, granularity: granularity, reverse: reverse });
    }
    else if (!countsOnly) {
        var label = [];
        if (structureCount > 0) {
            label.push(structureCount === 1 ? elementLabel(stats.firstStructureLoc, { hidePrefix: hidePrefix, condensed: condensed, granularity: 'structure', reverse: reverse }) : otherLabel(structureCount, stats.firstStructureLoc, 'structure', hidePrefix, reverse, condensed));
        }
        if (chainCount > 0) {
            label.push(chainCount === 1 ? elementLabel(stats.firstChainLoc, { condensed: condensed, granularity: 'chain', hidePrefix: hidePrefix, reverse: reverse }) : otherLabel(chainCount, stats.firstChainLoc, 'chain', hidePrefix, reverse, condensed));
            hidePrefix = true;
        }
        if (residueCount > 0) {
            label.push(residueCount === 1 ? elementLabel(stats.firstResidueLoc, { condensed: condensed, granularity: 'residue', hidePrefix: hidePrefix, reverse: reverse }) : otherLabel(residueCount, stats.firstResidueLoc, 'residue', hidePrefix, reverse, condensed));
            hidePrefix = true;
        }
        if (conformationCount > 0) {
            label.push(conformationCount === 1 ? elementLabel(stats.firstConformationLoc, { condensed: condensed, granularity: 'conformation', hidePrefix: hidePrefix, reverse: reverse }) : otherLabel(conformationCount, stats.firstConformationLoc, 'conformation', hidePrefix, reverse, condensed));
            hidePrefix = true;
        }
        if (elementCount > 0) {
            label.push(elementCount === 1 ? elementLabel(stats.firstElementLoc, { condensed: condensed, granularity: 'element', hidePrefix: hidePrefix, reverse: reverse }) : otherLabel(elementCount, stats.firstElementLoc, 'element', hidePrefix, reverse, condensed));
        }
        return label.join('<small> + </small>');
    }
    else {
        var label = [];
        if (structureCount > 0)
            label.push(countLabel(structureCount, 'Structure'));
        if (chainCount > 0)
            label.push(countLabel(chainCount, 'Chain'));
        if (residueCount > 0)
            label.push(countLabel(residueCount, 'Residue'));
        if (conformationCount > 0)
            label.push(countLabel(conformationCount, 'Conformation'));
        if (elementCount > 0)
            label.push(countLabel(elementCount, 'Element'));
        return label.join('<small> + </small>');
    }
}
function bondLabel(bond, options) {
    if (options === void 0) { options = {}; }
    return bundleLabel({ loci: [
            _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci(bond.aStructure, [{ unit: bond.aUnit, indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofSingleton(bond.aIndex) }]),
            _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci(bond.bStructure, [{ unit: bond.bUnit, indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].ofSingleton(bond.bIndex) }])
        ] }, options);
}
function bundleLabel(bundle, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), options);
    var label = _bundleLabel(bundle, o);
    return o.htmlStyling ? label : Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* stripTags */ "e"])(label);
}
function _bundleLabel(bundle, options) {
    var granularity = options.granularity, hidePrefix = options.hidePrefix, reverse = options.reverse, condensed = options.condensed;
    var isSingleElements = true;
    for (var _i = 0, _a = bundle.loci; _i < _a.length; _i++) {
        var l = _a[_i];
        if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.is(l) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.size(l) !== 1) {
            isSingleElements = false;
            break;
        }
    }
    if (isSingleElements) {
        var locations = bundle.loci.map(function (l) {
            var _a = l.elements[0], unit = _a.unit, indices = _a.indices;
            return _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.create(l.structure, unit, unit.elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_3__["OrderedSet"].start(indices)]);
        });
        var labels = locations.map(function (l) { return _elementLabel(l, granularity, hidePrefix, reverse || condensed); });
        if (condensed) {
            return labels.map(function (l) { return l[0].replace(/\[.*\]/g, '').trim(); }).filter(function (l) { return !!l; }).join(' \u2014 ');
        }
        var offset = 0;
        for (var i = 0, il = Math.min.apply(Math, labels.map(function (l) { return l.length; })) - 1; i < il; ++i) {
            var areIdentical = true;
            for (var j = 1, jl = labels.length; j < jl; ++j) {
                if (labels[0][i] !== labels[j][i]) {
                    areIdentical = false;
                    break;
                }
            }
            if (areIdentical)
                offset += 1;
            else
                break;
        }
        if (offset > 0) {
            var offsetLabels = [labels[0].join(' | ')];
            for (var j = 1, jl = labels.length; j < jl; ++j) {
                offsetLabels.push(labels[j].slice(offset).filter(function (l) { return !!l; }).join(' | '));
            }
            return offsetLabels.join(' \u2014 ');
        }
        else {
            return labels.map(function (l) { return l.filter(function (l) { return !!l; }).join(' | '); }).filter(function (l) { return !!l; }).join('</br>');
        }
    }
    else {
        var labels = bundle.loci.map(function (l) { return lociLabel(l, options); });
        return labels.filter(function (l) { return !!l; }).join(condensed ? ' \u2014 ' : '</br>');
    }
}
function elementLabel(location, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), options);
    var _label = _elementLabel(location, o.granularity, o.hidePrefix, o.reverse || o.condensed);
    var label = o.condensed ? _label[0].replace(/\[.*\]/g, '').trim() : _label.filter(function (l) { return !!l; }).join(' | ');
    return o.htmlStyling ? label : Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* stripTags */ "e"])(label);
}
function _elementLabel(location, granularity, hidePrefix, reverse) {
    if (granularity === void 0) { granularity = 'element'; }
    if (hidePrefix === void 0) { hidePrefix = false; }
    if (reverse === void 0) { reverse = false; }
    var label = [];
    if (!hidePrefix) {
        var entry = location.unit.model.entry;
        if (entry.length > 30)
            entry = entry.substr(0, 27) + '\u2026'; // ellipsis
        label.push("<small>" + entry + "</small>"); // entry
        if (granularity !== 'structure') {
            label.push("<small>Model " + location.unit.model.modelNum + "</small>"); // model
            label.push("<small>Instance " + location.unit.conformation.operator.name + "</small>"); // instance
        }
    }
    if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isAtomic(location.unit)) {
        label.push.apply(label, _atomicElementLabel(location, granularity, reverse));
    }
    else if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isCoarse(location.unit)) {
        label.push.apply(label, _coarseElementLabel(location, granularity));
    }
    else {
        label.push('Unknown');
    }
    return reverse ? label.reverse() : label;
}
function _atomicElementLabel(location, granularity, hideOccupancy) {
    if (hideOccupancy === void 0) { hideOccupancy = false; }
    var rI = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.residueIndex(location);
    var label_asym_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].chain.label_asym_id(location);
    var auth_asym_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].chain.auth_asym_id(location);
    var has_label_seq_id = location.unit.model.atomicHierarchy.residues.label_seq_id.valueKind(rI) === 0 /* Present */;
    var label_seq_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].residue.label_seq_id(location);
    var auth_seq_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].residue.auth_seq_id(location);
    var ins_code = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].residue.pdbx_PDB_ins_code(location);
    var comp_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].atom.label_comp_id(location);
    var atom_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].atom.label_atom_id(location);
    var alt_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].atom.label_alt_id(location);
    var occupancy = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].atom.occupancy(location);
    var microHetCompIds = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].residue.microheterogeneityCompIds(location);
    var compId = granularity === 'residue' && microHetCompIds.length > 1 ?
        "(" + microHetCompIds.join('|') + ")" : comp_id;
    var label = [];
    switch (granularity) {
        case 'element':
            label.push("<b>" + atom_id + "</b>" + (alt_id ? "%" + alt_id : ''));
        case 'conformation':
            if (granularity === 'conformation' && alt_id) {
                label.push("<small>Conformation</small> <b>" + alt_id + "</b>");
            }
        case 'residue':
            var seq_id = label_seq_id === auth_seq_id || !has_label_seq_id ? auth_seq_id : label_seq_id;
            label.push("<b>" + compId + " " + seq_id + "</b>" + (seq_id !== auth_seq_id ? " <small>[auth</small> <b>" + auth_seq_id + "</b><small>]</small>" : '') + "<b>" + (ins_code ? ins_code : '') + "</b>");
        case 'chain':
            if (label_asym_id === auth_asym_id) {
                label.push("<b>" + label_asym_id + "</b>");
            }
            else {
                if (granularity === 'chain' && _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].Traits.is(location.unit.traits, 1 /* MultiChain */)) {
                    label.push("<small>[auth</small> <b>" + auth_asym_id + "</b><small>]</small>");
                }
                else {
                    label.push("<b>" + label_asym_id + "</b> <small>[auth</small> <b>" + auth_asym_id + "</b><small>]</small>");
                }
            }
    }
    if (label.length > 0 && occupancy !== 1 && !hideOccupancy) {
        label[0] = label[0] + " <small>[occupancy</small> <b>" + Math.round(100 * occupancy) / 100 + "</b><small>]</small>";
    }
    return label.reverse();
}
function _coarseElementLabel(location, granularity) {
    var asym_id = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].coarse.asym_id(location);
    var seq_id_begin = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].coarse.seq_id_begin(location);
    var seq_id_end = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].coarse.seq_id_end(location);
    var label = [];
    switch (granularity) {
        case 'element':
        case 'conformation':
        case 'residue':
            if (seq_id_begin === seq_id_end) {
                var entityIndex = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].coarse.entityKey(location);
                var seq = location.unit.model.sequence.byEntityKey[entityIndex];
                var comp_id = seq.sequence.compId.value(seq_id_begin - 1); // 1-indexed
                label.push("<b>" + comp_id + " " + seq_id_begin + "-" + seq_id_end + "</b>");
            }
            else {
                label.push("<b>" + seq_id_begin + "-" + seq_id_end + "</b>");
            }
        case 'chain':
            label.push("<b>" + asym_id + "</b>");
    }
    return label.reverse();
}
//
function distanceLabel(pair, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), { measureOnly: false, unitLabel: '\u212B' }), options);
    var _a = pair.loci.map(function (l) { return _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__["Loci"].getCenter(l); }), cA = _a[0], cB = _a[1];
    var distance = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].distance(cA, cB).toFixed(2) + " " + o.unitLabel;
    if (o.measureOnly)
        return distance;
    var label = bundleLabel(pair, o);
    return o.condensed ? distance + " | " + label : "Distance " + distance + "</br>" + label;
}
function angleLabel(triple, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), { measureOnly: false }), options);
    var _a = triple.loci.map(function (l) { return _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__["Loci"].getCenter(l); }), cA = _a[0], cB = _a[1], cC = _a[2];
    var vAB = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].sub(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"])(), cA, cB);
    var vCB = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].sub(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"])(), cC, cB);
    var angle = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_6__[/* radToDeg */ "f"])(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].angle(vAB, vCB)).toFixed(2) + "\u00B0";
    if (o.measureOnly)
        return angle;
    var label = bundleLabel(triple, o);
    return o.condensed ? angle + " | " + label : "Angle " + angle + "</br>" + label;
}
function dihedralLabel(quad, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultLabelOptions), { measureOnly: false }), options);
    var _a = quad.loci.map(function (l) { return _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__["Loci"].getCenter(l); }), cA = _a[0], cB = _a[1], cC = _a[2], cD = _a[3];
    var dihedral = Math.abs(Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_6__[/* radToDeg */ "f"])(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].dihedralAngle(cA, cB, cC, cD))).toFixed(2) + "\u00B0";
    if (o.measureOnly)
        return dihedral;
    var label = bundleLabel(quad, o);
    return o.condensed ? dihedral + " | " + label : "Dihedral " + dihedral + "</br>" + label;
}
//# sourceMappingURL=label.js.map

/***/ }),
/* 73 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return TokenColumnProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TokenColumn; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return areValuesEqualProvider; });
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/* harmony import */ var _number_parser__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(97);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function TokenColumnProvider(tokens) {
    return function (type) {
        return TokenColumn(tokens, type);
    };
}
function TokenColumn(tokens, schema) {
    var data = tokens.data, indices = tokens.indices, rowCount = tokens.count;
    var type = schema.valueType;
    var value = type === 'str'
        ? function (row) { return data.substring(indices[2 * row], indices[2 * row + 1]); }
        : type === 'int'
            ? function (row) { return Object(_number_parser__WEBPACK_IMPORTED_MODULE_1__[/* parseInt */ "d"])(data, indices[2 * row], indices[2 * row + 1]) || 0; }
            : function (row) { return Object(_number_parser__WEBPACK_IMPORTED_MODULE_1__[/* parseFloat */ "b"])(data, indices[2 * row], indices[2 * row + 1]) || 0; };
    return {
        schema: schema,
        __array: void 0,
        isDefined: true,
        rowCount: rowCount,
        value: value,
        valueKind: function (row) { return 0 /* Present */; },
        toArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["ColumnHelpers"].createAndFillArray(rowCount, value, params); },
        areValuesEqual: areValuesEqualProvider(tokens)
    };
}
function areValuesEqualProvider(tokens) {
    var data = tokens.data, indices = tokens.indices;
    return function (rowA, rowB) {
        var aS = indices[2 * rowA], bS = indices[2 * rowB];
        var len = indices[2 * rowA + 1] - aS;
        if (len !== indices[2 * rowB + 1] - bS)
            return false;
        for (var i = 0; i < len; i++) {
            if (data.charCodeAt(i + aS) !== data.charCodeAt(i + bS)) {
                return false;
            }
        }
        return true;
    };
}
//# sourceMappingURL=token.js.map

/***/ }),
/* 74 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Lines; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(124);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(117);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(125);
/* harmony import */ var _size_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(146);
/* harmony import */ var _lines_builder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(172);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(53);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(11);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(142);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(9);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(143);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var Lines;
(function (Lines) {
    function create(mappings, indices, groups, starts, ends, lineCount, lines) {
        return lines ?
            update(mappings, indices, groups, starts, ends, lineCount, lines) :
            fromArrays(mappings, indices, groups, starts, ends, lineCount);
    }
    Lines.create = create;
    function createEmpty(lines) {
        var mb = lines ? lines.mappingBuffer.ref.value : new Float32Array(0);
        var ib = lines ? lines.indexBuffer.ref.value : new Uint32Array(0);
        var gb = lines ? lines.groupBuffer.ref.value : new Float32Array(0);
        var sb = lines ? lines.startBuffer.ref.value : new Float32Array(0);
        var eb = lines ? lines.endBuffer.ref.value : new Float32Array(0);
        return create(mb, ib, gb, sb, eb, 0, lines);
    }
    Lines.createEmpty = createEmpty;
    function fromMesh(mesh, lines) {
        var vb = mesh.vertexBuffer.ref.value;
        var ib = mesh.indexBuffer.ref.value;
        var gb = mesh.groupBuffer.ref.value;
        var builder = _lines_builder__WEBPACK_IMPORTED_MODULE_7__[/* LinesBuilder */ "a"].create(mesh.triangleCount * 3, mesh.triangleCount / 10, lines);
        // TODO avoid duplicate lines
        for (var i = 0, il = mesh.triangleCount * 3; i < il; i += 3) {
            var i0 = ib[i], i1 = ib[i + 1], i2 = ib[i + 2];
            var x0 = vb[i0 * 3], y0 = vb[i0 * 3 + 1], z0 = vb[i0 * 3 + 2];
            var x1 = vb[i1 * 3], y1 = vb[i1 * 3 + 1], z1 = vb[i1 * 3 + 2];
            var x2 = vb[i2 * 3], y2 = vb[i2 * 3 + 1], z2 = vb[i2 * 3 + 2];
            builder.add(x0, y0, z0, x1, y1, z1, gb[i0]);
            builder.add(x0, y0, z0, x2, y2, z2, gb[i0]);
            builder.add(x1, y1, z1, x2, y2, z2, gb[i1]);
        }
        return builder.getLines();
    }
    Lines.fromMesh = fromMesh;
    function hashCode(lines) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_14__[/* hashFnv32a */ "l"])([
            lines.lineCount, lines.mappingBuffer.ref.version, lines.indexBuffer.ref.version,
            lines.groupBuffer.ref.version, lines.startBuffer.ref.version, lines.startBuffer.ref.version
        ]);
    }
    function fromArrays(mappings, indices, groups, starts, ends, lineCount) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"])();
        var groupMapping;
        var currentHash = -1;
        var currentGroup = -1;
        var lines = {
            kind: 'lines',
            lineCount: lineCount,
            mappingBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(mappings),
            indexBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(indices),
            groupBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(groups),
            startBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(starts),
            endBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(ends),
            get boundingSphere() {
                var newHash = hashCode(lines);
                if (newHash !== currentHash) {
                    var s = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateInvariantBoundingSphere */ "a"])(lines.startBuffer.ref.value, lines.lineCount * 4, 4);
                    var e = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateInvariantBoundingSphere */ "a"])(lines.endBuffer.ref.value, lines.lineCount * 4, 4);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].expandBySphere(boundingSphere, s, e);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
            get groupMapping() {
                if (lines.groupBuffer.ref.version !== currentGroup) {
                    groupMapping = Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* createGroupMapping */ "c"])(lines.groupBuffer.ref.value, lines.lineCount, 4);
                    currentGroup = lines.groupBuffer.ref.version;
                }
                return groupMapping;
            },
            setBoundingSphere: function (sphere) {
                _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].copy(boundingSphere, sphere);
                currentHash = hashCode(lines);
            }
        };
        return lines;
    }
    function update(mappings, indices, groups, starts, ends, lineCount, lines) {
        lines.lineCount = lineCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.mappingBuffer, mappings);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.indexBuffer, indices);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.groupBuffer, groups);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.startBuffer, starts);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.endBuffer, ends);
        return lines;
    }
    function transform(lines, t) {
        var start = lines.startBuffer.ref.value;
        Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* transformPositionArray */ "e"])(t, start, 0, lines.lineCount * 4);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.startBuffer, start);
        var end = lines.endBuffer.ref.value;
        Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* transformPositionArray */ "e"])(t, end, 0, lines.lineCount * 4);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(lines.endBuffer, end);
    }
    Lines.transform = transform;
    //
    Lines.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].Params), { sizeFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), lineSizeAttenuation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false) });
    Lines.Utils = {
        Params: Lines.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].createRenderableState,
        updateRenderableState: _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].updateRenderableState
    };
    function createValues(lines, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_4__[/* createColors */ "a"])(locationIt, theme.color);
        var size = Object(_size_data__WEBPACK_IMPORTED_MODULE_6__[/* createSizes */ "a"])(locationIt, theme.size);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_5__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_12__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_13__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_15__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: lines.lineCount * 2 * 3, groupCount: groupCount, instanceCount: instanceCount };
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].clone(lines.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ aMapping: lines.mappingBuffer, aGroup: lines.groupBuffer, aStart: lines.startBuffer, aEnd: lines.endBuffer, elements: lines.indexBuffer, boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].ofSphere(invariantBoundingSphere)) }, color), size), marker), overpaint), transparency), clipping), transform), _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].createValues(props, counts)), { uSizeFactor: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.sizeFactor), dLineSizeAttenuation: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.lineSizeAttenuation), dDoubleSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(true), dFlipSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(false) });
    }
    function createValuesSimple(lines, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].getDefaultValues(Lines.Params)), props);
        return createValues(lines, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_11__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.uSizeFactor, props.sizeFactor);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dLineSizeAttenuation, props.lineSizeAttenuation);
    }
    function updateBoundingSphere(values, lines) {
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].clone(lines.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
})(Lines || (Lines = {}));
//# sourceMappingURL=lines.js.map

/***/ }),
/* 75 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getSphere; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addSphere; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mesh_builder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34);
/* harmony import */ var _primitive_sphere__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(264);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var sphereMap = new Map();
var tmpSphereMat = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].identity();
function setSphereMat(m, center, radius) {
    return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].scaleUniformly(m, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].fromTranslation(m, center), radius);
}
function getSphere(detail) {
    var sphere = sphereMap.get(detail);
    if (sphere === undefined) {
        sphere = Object(_primitive_sphere__WEBPACK_IMPORTED_MODULE_2__[/* Sphere */ "a"])(detail);
        sphereMap.set(detail, sphere);
    }
    return sphere;
}
function addSphere(state, center, radius, detail) {
    _mesh_builder__WEBPACK_IMPORTED_MODULE_1__[/* MeshBuilder */ "a"].addPrimitive(state, setSphereMat(tmpSphereMat, center, radius), getSphere(detail));
}
//# sourceMappingURL=sphere.js.map

/***/ }),
/* 76 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Transform; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _transformer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(191);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var Transform;
(function (Transform) {
    Transform.RootRef = '-=root=-';
    function areStatesEqual(a, b) {
        return !!a.isHidden !== !!b.isHidden || !!a.isCollapsed !== !!b.isCollapsed
            || !!a.isGhost !== !!b.isGhost || !!a.isLocked !== !!b.isLocked;
    }
    Transform.areStatesEqual = areStatesEqual;
    function isStateChange(a, b) {
        if (!b)
            return false;
        if (typeof b.isCollapsed !== 'undefined' && a.isCollapsed !== b.isCollapsed)
            return true;
        if (typeof b.isHidden !== 'undefined' && a.isHidden !== b.isHidden)
            return true;
        if (typeof b.isGhost !== 'undefined' && a.isGhost !== b.isGhost)
            return true;
        if (typeof b.isLocked !== 'undefined' && a.isLocked !== b.isLocked)
            return true;
        return false;
    }
    Transform.isStateChange = isStateChange;
    function assignState(a, b) {
        if (!b)
            return false;
        var changed = false;
        for (var _i = 0, _a = Object.keys(b); _i < _a.length; _i++) {
            var k = _a[_i];
            var s = b[k], t = a[k];
            if (!!s === !!t)
                continue;
            changed = true;
            a[k] = s;
        }
        return changed;
    }
    Transform.assignState = assignState;
    function syncState(a, b) {
        if (!b)
            return false;
        var changed = false;
        for (var _i = 0, _a = Object.keys(b); _i < _a.length; _i++) {
            var k = _a[_i];
            var s = b[k], t = a[k];
            if (!!s === !!t)
                continue;
            changed = true;
            a[k] = s;
        }
        for (var _b = 0, _c = Object.keys(a); _b < _c.length; _b++) {
            var k = _c[_b];
            var s = b[k], t = a[k];
            if (!!s === !!t)
                continue;
            changed = true;
            a[k] = s;
        }
        return changed;
    }
    Transform.syncState = syncState;
    function create(parent, transformer, params, options) {
        var ref = options && options.ref ? options.ref : _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22();
        var tags = void 0;
        if (options && options.tags) {
            tags = typeof options.tags === 'string' ? [options.tags] : options.tags;
            if (tags.length === 0)
                tags = void 0;
            else
                tags.sort();
        }
        return {
            parent: parent,
            transformer: transformer,
            state: (options === null || options === void 0 ? void 0 : options.state) || {},
            tags: tags,
            ref: ref,
            dependsOn: options && options.dependsOn,
            params: params,
            version: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22()
        };
    }
    Transform.create = create;
    function withParams(t, params) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, t), { params: params, version: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22() });
    }
    Transform.withParams = withParams;
    function withState(t, state) {
        if (!state)
            return t;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, t), { state: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, t.state), state) });
    }
    Transform.withState = withState;
    function withTags(t, newTags) {
        var tags = void 0;
        if (newTags) {
            tags = typeof newTags === 'string' ? [newTags] : newTags;
            if (tags.length === 0)
                tags = void 0;
            else
                tags.sort();
        }
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, t), { tags: tags, version: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22() });
    }
    Transform.withTags = withTags;
    function withParent(t, parent) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, t), { parent: parent, version: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22() });
    }
    Transform.withParent = withParent;
    function createRoot(state) {
        return create(Transform.RootRef, _transformer__WEBPACK_IMPORTED_MODULE_1__[/* StateTransformer */ "a"].ROOT, {}, { ref: Transform.RootRef, state: state });
    }
    Transform.createRoot = createRoot;
    function hasTag(t, tag) {
        if (!t.tags)
            return false;
        return t.tags.indexOf(tag) >= 0;
    }
    Transform.hasTag = hasTag;
    function hasTags(t, tags) {
        if (!t.tags)
            return typeof tags !== 'string' && tags.length === 0;
        if (typeof tags === 'string')
            return hasTag(t, tags);
        for (var _i = 0, tags_1 = tags; _i < tags_1.length; _i++) {
            var tag = tags_1[_i];
            if (t.tags.indexOf(tag) < 0)
                return false;
        }
        return true;
    }
    Transform.hasTags = hasTags;
    function _id(x) { return x; }
    function toJSON(t) {
        var pToJson = t.transformer.definition.customSerialization
            ? t.transformer.definition.customSerialization.toJSON
            : _id;
        var state = void 0;
        for (var _i = 0, _a = Object.keys(t.state); _i < _a.length; _i++) {
            var k = _a[_i];
            var s = t.state[k];
            if (!s)
                continue;
            if (!state)
                state = {};
            state[k] = true;
        }
        return {
            parent: t.parent,
            transformer: t.transformer.id,
            params: t.params ? pToJson(t.params) : void 0,
            state: state,
            tags: t.tags,
            ref: t.ref,
            dependsOn: t.dependsOn,
            version: t.version
        };
    }
    Transform.toJSON = toJSON;
    function fromJSON(t) {
        var transformer = _transformer__WEBPACK_IMPORTED_MODULE_1__[/* StateTransformer */ "a"].get(t.transformer);
        var pFromJson = transformer.definition.customSerialization
            ? transformer.definition.customSerialization.toJSON
            : _id;
        return {
            parent: t.parent,
            transformer: transformer,
            params: t.params ? pFromJson(t.params) : void 0,
            state: t.state || {},
            tags: t.tags,
            ref: t.ref,
            dependsOn: t.dependsOn,
            version: t.version
        };
    }
    Transform.fromJSON = fromJSON;
})(Transform || (Transform = {}));
//# sourceMappingURL=transform.js.map

/***/ }),
/* 77 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Clipping; });
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_script_script__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(120);
/* harmony import */ var _mol_util_bit_flags__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(207);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function Clipping(layers) {
    return { layers: layers };
}
(function (Clipping) {
    Clipping.Empty = { layers: [] };
    var Groups;
    (function (Groups) {
        Groups.is = _mol_util_bit_flags__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].has;
        function create(flags) {
            return _mol_util_bit_flags__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].create(flags);
        }
        Groups.create = create;
        Groups.Names = {
            'one': 1 /* One */,
            'two': 2 /* Two */,
            'three': 4 /* Three */,
            'four': 8 /* Four */,
            'five': 16 /* Five */,
            'six': 32 /* Six */,
        };
        function isName(name) {
            return name in Groups.Names;
        }
        Groups.isName = isName;
        function fromName(name) {
            switch (name) {
                case 'one': return 1 /* One */;
                case 'two': return 2 /* Two */;
                case 'three': return 4 /* Three */;
                case 'four': return 8 /* Four */;
                case 'five': return 16 /* Five */;
                case 'six': return 32 /* Six */;
            }
        }
        Groups.fromName = fromName;
        function fromNames(names) {
            var f = 0 /* None */;
            for (var i = 0, il = names.length; i < il; ++i) {
                f |= fromName(names[i]);
            }
            return f;
        }
        Groups.fromNames = fromNames;
        function toNames(groups) {
            var names = [];
            if (Groups.is(groups, 1 /* One */))
                names.push('one');
            if (Groups.is(groups, 2 /* Two */))
                names.push('two');
            if (Groups.is(groups, 4 /* Three */))
                names.push('three');
            if (Groups.is(groups, 8 /* Four */))
                names.push('four');
            if (Groups.is(groups, 16 /* Five */))
                names.push('five');
            if (Groups.is(groups, 32 /* Six */))
                names.push('six');
            return names;
        }
        Groups.toNames = toNames;
    })(Groups = Clipping.Groups || (Clipping.Groups = {}));
    /** Clip object types */
    Clipping.Type = {
        none: 0,
        plane: 1,
        sphere: 2,
        cube: 3,
        cylinder: 4,
        infiniteCone: 5,
    };
    function areEqual(cA, cB) {
        if (cA.layers.length === 0 && cB.layers.length === 0)
            return true;
        if (cA.layers.length !== cB.layers.length)
            return false;
        for (var i = 0, il = cA.layers.length; i < il; ++i) {
            if (cA.layers[i].groups !== cB.layers[i].groups)
                return false;
            if (!_mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["Loci"].areEqual(cA.layers[i].loci, cB.layers[i].loci))
                return false;
        }
        return true;
    }
    Clipping.areEqual = areEqual;
    function isEmpty(clipping) {
        return clipping.layers.length === 0;
    }
    Clipping.isEmpty = isEmpty;
    function remap(clipping, structure) {
        var layers = [];
        for (var _i = 0, _a = clipping.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, groups = layer.groups;
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(loci, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, groups: groups });
            }
        }
        return { layers: layers };
    }
    Clipping.remap = remap;
    function merge(clipping) {
        if (isEmpty(clipping))
            return clipping;
        var structure = clipping.layers[0].loci.structure;
        var map = new Map();
        var shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.none(structure);
        for (var i = 0, il = clipping.layers.length; i < il; ++i) {
            var _a = clipping.layers[il - i - 1], loci = _a.loci, groups = _a.groups; // process from end
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.subtract(loci, shadowed);
            shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.union(loci, shadowed);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                if (map.has(groups)) {
                    loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.union(loci, map.get(groups));
                }
                map.set(groups, loci);
            }
        }
        var layers = [];
        map.forEach(function (loci, groups) {
            layers.push({ loci: loci, groups: groups });
        });
        return { layers: layers };
    }
    Clipping.merge = merge;
    function filter(clipping, filter) {
        if (isEmpty(clipping))
            return clipping;
        var structure = clipping.layers[0].loci.structure;
        var layers = [];
        for (var _i = 0, _a = clipping.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, groups = layer.groups;
            // filter by first map to the `filter` structure and
            // then map back to the original structure of the clipping loci
            var filtered = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(loci, filter);
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(filtered, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, groups: groups });
            }
        }
        return { layers: layers };
    }
    Clipping.filter = filter;
    function ofScript(scriptLayers, structure) {
        var layers = [];
        for (var i = 0, il = scriptLayers.length; i < il; ++i) {
            var _a = scriptLayers[i], script = _a.script, groups = _a.groups;
            var loci = _mol_script_script__WEBPACK_IMPORTED_MODULE_2__["Script"].toLoci(script, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, groups: groups });
            }
        }
        return { layers: layers };
    }
    Clipping.ofScript = ofScript;
    function ofBundle(bundleLayers, structure) {
        var layers = [];
        for (var i = 0, il = bundleLayers.length; i < il; ++i) {
            var _a = bundleLayers[i], bundle = _a.bundle, groups = _a.groups;
            var loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Bundle.toLoci(bundle, structure.root);
            layers.push({ loci: loci, groups: groups });
        }
        return { layers: layers };
    }
    Clipping.ofBundle = ofBundle;
    function toBundle(clipping) {
        var layers = [];
        for (var i = 0, il = clipping.layers.length; i < il; ++i) {
            var _a = clipping.layers[i], loci = _a.loci, groups = _a.groups;
            var bundle = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Bundle.fromLoci(loci);
            layers.push({ bundle: bundle, groups: groups });
        }
        return { layers: layers };
    }
    Clipping.toBundle = toBundle;
})(Clipping || (Clipping = {}));
//# sourceMappingURL=clipping.js.map

/***/ }),
/* 78 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export normalize */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return clamp; });
/* unused harmony export pclamp */
/* unused harmony export saturate */
/* unused harmony export damp */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return lerp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return spline; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return quadraticBezier; });
/* unused harmony export smoothstep */
/* unused harmony export smootherstep */
/* unused harmony export smootheststep */
/* unused harmony export almostIdentity */
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function normalize(value, min, max) {
    return (value - min) / (max - min);
}
function clamp(value, min, max) {
    return Math.max(min, Math.min(max, value));
}
function pclamp(value) {
    return clamp(value, 0, 100);
}
function saturate(value) {
    return clamp(value, 0, 1);
}
function damp(value, dampingFactor) {
    var dampedValue = value * dampingFactor;
    return Math.abs(dampedValue) < 0.1 ? 0 : dampedValue;
}
function lerp(start, stop, alpha) {
    return start + (stop - start) * alpha;
}
/** Catmul-Rom spline */
function spline(p0, p1, p2, p3, t, tension) {
    var v0 = (p2 - p0) * tension;
    var v1 = (p3 - p1) * tension;
    var t2 = t * t;
    var t3 = t * t2;
    return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
}
function quadraticBezier(p0, p1, p2, t) {
    var k = 1 - t;
    return (k * k * p0) + (2 * k * t * p1) + (t * t * p2);
}
function smoothstep(min, max, x) {
    x = saturate(normalize(x, min, max));
    return x * x * (3 - 2 * x);
}
function smootherstep(min, max, x) {
    x = saturate(normalize(x, min, max));
    return x * x * x * (x * (x * 6 - 15) + 10);
}
function smootheststep(min, max, x) {
    x = saturate(normalize(x, min, max));
    return -20 * Math.pow(x, 7) + 70 * Math.pow(x, 6) - 84 * Math.pow(x, 5) + 35 * Math.pow(x, 4);
}
function almostIdentity(value, start, stop) {
    if (value > start)
        return value;
    var a = 2 * stop - start;
    var b = 2 * start - 3 * stop;
    var t = value / start;
    return (a * t + b) * t * t + stop;
}
//# sourceMappingURL=interpolate.js.map

/***/ }),
/* 79 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var SortedRanges;
(function (SortedRanges) {
    function ofSortedRanges(array) { return _int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(array); }
    SortedRanges.ofSortedRanges = ofSortedRanges;
    function start(ranges) { return ranges[0]; }
    SortedRanges.start = start;
    function end(ranges) { return ranges[ranges.length - 1] + 1; }
    SortedRanges.end = end;
    function min(ranges) { return ranges[0]; }
    SortedRanges.min = min;
    function max(ranges) { return ranges[ranges.length - 1]; }
    SortedRanges.max = max;
    function size(ranges) {
        var size = 0;
        for (var i = 0, il = ranges.length; i < il; i += 2) {
            size += ranges[i + 1] - ranges[i] + 1;
        }
        return size;
    }
    SortedRanges.size = size;
    function count(ranges) { return ranges.length / 2; }
    SortedRanges.count = count;
    function startAt(ranges, index) {
        return ranges[index * 2];
    }
    SortedRanges.startAt = startAt;
    function endAt(ranges, index) {
        return ranges[index * 2 + 1] + 1;
    }
    SortedRanges.endAt = endAt;
    function minAt(ranges, index) {
        return ranges[index * 2];
    }
    SortedRanges.minAt = minAt;
    function maxAt(ranges, index) {
        return ranges[index * 2 + 1];
    }
    SortedRanges.maxAt = maxAt;
    function areEqual(a, b) {
        if (a.length !== b.length)
            return false;
        for (var i = 0, il = a.length; i < il; ++i) {
            if (a[i] !== b[i])
                return false;
        }
        return true;
    }
    SortedRanges.areEqual = areEqual;
    function forEach(ranges, f) {
        var k = 0;
        for (var i = 0, il = ranges.length; i < il; i += 2) {
            for (var j = ranges[i], jl = ranges[i + 1]; j <= jl; ++j) {
                f(j, k);
                ++k;
            }
        }
    }
    SortedRanges.forEach = forEach;
    /** Returns if a value of `set` is included in `ranges` */
    function has(ranges, set) {
        return firstIntersectionIndex(ranges, set) !== -1;
    }
    SortedRanges.has = has;
    /** Returns if a value of `set` is included in `ranges` from given index */
    function hasFrom(ranges, set, from) {
        return firstIntersectionIndexFrom(ranges, set, from) !== -1;
    }
    SortedRanges.hasFrom = hasFrom;
    function firstIntersectionIndex(ranges, set) {
        return firstIntersectionIndexFrom(ranges, set, 0);
    }
    SortedRanges.firstIntersectionIndex = firstIntersectionIndex;
    function firstIntersectionIndexFrom(ranges, set, from) {
        if (minAt(ranges, from) > _int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].max(set) || max(ranges) < _int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].min(set))
            return -1;
        for (var i = from, il = count(ranges); i < il; ++i) {
            var interval = _int__WEBPACK_IMPORTED_MODULE_0__["Interval"].ofRange(minAt(ranges, i), maxAt(ranges, i));
            if (_int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].areIntersecting(interval, set))
                return i;
        }
        return -1;
    }
    SortedRanges.firstIntersectionIndexFrom = firstIntersectionIndexFrom;
    function transientSegments(ranges, set) {
        return new Iterator(ranges, set);
    }
    SortedRanges.transientSegments = transientSegments;
    var Iterator = /** @class */ (function () {
        function Iterator(ranges, set) {
            this.ranges = ranges;
            this.set = set;
            this.value = { index: 0, start: 0, end: 0 };
            this.curIndex = 0;
            this.hasNext = false;
            this.curIndex = firstIntersectionIndex(ranges, set);
            this.hasNext = this.curIndex !== -1;
        }
        Iterator.prototype.updateValue = function () {
            this.value.index = this.curIndex;
            this.value.start = _int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].findPredecessorIndex(this.set, startAt(this.ranges, this.curIndex));
            this.value.end = _int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].findPredecessorIndex(this.set, endAt(this.ranges, this.curIndex));
        };
        Iterator.prototype.move = function () {
            if (this.hasNext) {
                this.updateValue();
                this.curIndex = firstIntersectionIndexFrom(this.ranges, this.set, this.curIndex + 1);
                this.hasNext = this.curIndex !== -1;
            }
            return this.value;
        };
        return Iterator;
    }());
    SortedRanges.Iterator = Iterator;
})(SortedRanges || (SortedRanges = {}));
/* harmony default export */ __webpack_exports__["a"] = (SortedRanges);
//# sourceMappingURL=sorted-ranges.js.map

/***/ }),
/* 80 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructureSelectionCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StructureSelectionQuery; });
/* unused harmony export ResidueQuery */
/* unused harmony export ElementSymbolQuery */
/* unused harmony export EntityDescriptionQuery */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getElementQueries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getNonStandardResidueQueries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getPolymerAndBranchedEntityQueries; });
/* unused harmony export applyBuiltInSelection */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StructureSelectionQueries; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return StructureSelectionQueryRegistry; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(22);
/* harmony import */ var _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10);
/* harmony import */ var _mol_script_runtime_query_compiler__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(163);
/* harmony import */ var _mol_util_set__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(90);
/* harmony import */ var _transforms__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(28);
/* harmony import */ var _mol_model_structure_model_properties_atomic_types__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(245);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var StructureSelectionCategory;
(function (StructureSelectionCategory) {
    StructureSelectionCategory["Type"] = "Type";
    StructureSelectionCategory["Structure"] = "Structure Property";
    StructureSelectionCategory["Atom"] = "Atom Property";
    StructureSelectionCategory["Bond"] = "Bond Property";
    StructureSelectionCategory["Residue"] = "Residue Property";
    StructureSelectionCategory["AminoAcid"] = "Amino Acid";
    StructureSelectionCategory["NucleicBase"] = "Nucleic Base";
    StructureSelectionCategory["Manipulate"] = "Manipulate Selection";
    StructureSelectionCategory["Validation"] = "Validation";
    StructureSelectionCategory["Misc"] = "Miscellaneous";
    StructureSelectionCategory["Internal"] = "Internal";
})(StructureSelectionCategory || (StructureSelectionCategory = {}));

function StructureSelectionQuery(label, expression, props) {
    var _a;
    if (props === void 0) { props = {}; }
    var _query;
    return {
        label: label,
        expression: expression,
        description: props.description || '',
        category: (_a = props.category) !== null && _a !== void 0 ? _a : StructureSelectionCategory.Misc,
        isHidden: !!props.isHidden,
        priority: props.priority || 0,
        referencesCurrent: !!props.referencesCurrent,
        get query() {
            if (!_query)
                _query = Object(_mol_script_runtime_query_compiler__WEBPACK_IMPORTED_MODULE_4__["compile"])(expression);
            return _query;
        },
        ensureCustomProperties: props.ensureCustomProperties,
        getSelection: function (plugin, runtime, structure) {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
                var current, currentSelection;
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            current = plugin.managers.structure.selection.getStructure(structure);
                            currentSelection = current ? _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSelection"].Sequence(structure, [current]) : _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSelection"].Empty(structure);
                            if (!props.ensureCustomProperties) return [3 /*break*/, 2];
                            return [4 /*yield*/, props.ensureCustomProperties({ runtime: runtime, assetManager: plugin.managers.asset }, structure)];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            if (!_query)
                                _query = Object(_mol_script_runtime_query_compiler__WEBPACK_IMPORTED_MODULE_4__["compile"])(expression);
                            return [2 /*return*/, _query(new _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["QueryContext"](structure, { currentSelection: currentSelection }))];
                    }
                });
            });
        }
    };
}
var all = StructureSelectionQuery('All', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.all(), { category: '', priority: 1000 });
var current = StructureSelectionQuery('Current Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current(), { category: '', referencesCurrent: true });
var polymer = StructureSelectionQuery('Polymer', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
                _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('(polypeptide|cyclic-pseudo-peptide|nucleotide|peptide nucleic acid)', 'i'),
                _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype')
            ])
        ])
    })
]), { category: StructureSelectionCategory.Type });
var trace = StructureSelectionQuery('Trace', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set('sphere', 'gaussian'), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive')
                ])
            })
        ]),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set('CA', 'P'), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
            })
        ])
    ])
]), { category: StructureSelectionCategory.Structure });
var _proteinEntityTest = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('(polypeptide|cyclic-pseudo-peptide)', 'i'),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype')
    ])
]);
var _nucleiEntityTest = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('(nucleotide|peptide nucleic acid)', 'i'),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype')
    ])
]);
/**
 * this is to get non-polymer and peptide terminus components in polymer entities,
 * - non-polymer, e.g. PXZ in 4HIV or generally ACE
 * - carboxy terminus, e.g. FC0 in 4BP9, or ETA in 6DDE
 * - amino terminus, e.g. ARF in 3K4V, or 4MM in 3EGV
 */
var _nonPolymerResidueTest = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('non-polymer|(amino|carboxy) terminus|peptide-like', 'i'),
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('chemCompType')
]);
// TODO maybe pre-calculate backbone atom properties
var backbone = StructureSelectionQuery('Backbone', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _proteinEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["ProteinBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
            })
        ]),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _nucleiEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["NucleicBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
            })
        ])
    ])
]), { category: StructureSelectionCategory.Structure });
// TODO maybe pre-calculate sidechain atom property
var sidechain = StructureSelectionQuery('Sidechain', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _proteinEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["ProteinBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
                    ])
                ])
            })
        ]),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _nucleiEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["NucleicBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
                    ])
                ])
            })
        ])
    ])
]), { category: StructureSelectionCategory.Structure });
// TODO maybe pre-calculate sidechain atom property
var sidechainWithTrace = StructureSelectionQuery('Sidechain with Trace', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _proteinEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["ProteinBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
                    ]),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id'), 'CA']),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('auth_comp_id'), 'PRO']),
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id'), 'N'])
                    ])
                ])
            })
        ]),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _nucleiEntityTest,
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_nonPolymerResidueTest]),
                'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].toArray(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["NucleicBackboneAtoms"])), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id')])
                    ]),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('label_atom_id'), 'P'])
                ])
            })
        ])
    ])
]), { category: StructureSelectionCategory.Structure });
var protein = StructureSelectionQuery('Protein', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({ 'entity-test': _proteinEntityTest })
]), { category: StructureSelectionCategory.Type });
var nucleic = StructureSelectionQuery('Nucleic', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({ 'entity-test': _nucleiEntityTest })
]), { category: StructureSelectionCategory.Type });
var helix = StructureSelectionQuery('Helix', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _proteinEntityTest,
        'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.flags.hasAny([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('secondaryStructureFlags'),
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.bitflags([2 /* Helix */])
        ])
    })
]), { category: StructureSelectionCategory.Structure });
var beta = StructureSelectionQuery('Beta Strand/Sheet', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _proteinEntityTest,
        'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.flags.hasAny([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('secondaryStructureFlags'),
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.bitflags([4 /* Beta */])
        ])
    })
]), { category: StructureSelectionCategory.Structure });
var water = StructureSelectionQuery('Water', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'water'])
    })
]), { category: StructureSelectionCategory.Type });
var ion = StructureSelectionQuery('Ion', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype'), 'ion'])
    })
]), { category: StructureSelectionCategory.Type });
var lipid = StructureSelectionQuery('Lipid', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype'), 'lipid'])
    })
]), { category: StructureSelectionCategory.Type });
var branched = StructureSelectionQuery('Carbohydrate', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'branched']),
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
                _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'non-polymer']),
                _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('oligosaccharide', 'i'),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype')
                ])
            ])
        ])
    })
]), { category: StructureSelectionCategory.Type });
var branchedPlusConnected = StructureSelectionQuery('Carbohydrate with Connected', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.includeConnected({
        0: branched.expression, 'layer-count': 1, 'as-whole-residues': true
    })
]), { category: StructureSelectionCategory.Internal, isHidden: true });
var branchedConnectedOnly = StructureSelectionQuery('Connected to Carbohydrate', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.exceptBy({
        0: branchedPlusConnected.expression,
        by: branched.expression
    })
]), { category: StructureSelectionCategory.Internal, isHidden: true });
var ligand = StructureSelectionQuery('Ligand', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'non-polymer']),
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.neq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityPrdId'), ''])
                    ]),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([
                            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('(oligosaccharide|lipid|ion)', 'i'),
                            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entitySubtype')
                        ])])
                ]),
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.not([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.str.match([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].re('saccharide', 'i'), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('chemCompType')])
                ])
            })
        ]),
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
                'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': _nonPolymerResidueTest
            })
        ])
    ]),
]), { category: StructureSelectionCategory.Type });
// don't include branched entities as they have their own link representation
var ligandPlusConnected = StructureSelectionQuery('Ligand with Connected', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.exceptBy({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.includeConnected({
                0: ligand.expression,
                'layer-count': 1,
                'as-whole-residues': true,
                'bond-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.flags.hasAny([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.bondProperty.flags(),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.bitflags([
                        1 /* Covalent */ | 2 /* MetallicCoordination */
                    ])
                ])
            })
        ]),
        by: branched.expression
    })
]), { category: StructureSelectionCategory.Internal, isHidden: true });
var ligandConnectedOnly = StructureSelectionQuery('Connected to Ligand', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.exceptBy({
        0: ligandPlusConnected.expression,
        by: ligand.expression
    })
]), { category: StructureSelectionCategory.Internal, isHidden: true });
// residues connected to ligands or branched entities
var connectedOnly = StructureSelectionQuery('Connected to Ligand or Carbohydrate', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge([
        branchedConnectedOnly.expression,
        ligandConnectedOnly.expression
    ]),
]), { category: StructureSelectionCategory.Internal, isHidden: true });
var disulfideBridges = StructureSelectionQuery('Disulfide Bridges', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.wholeResidues([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.bondedAtomicPairs({
                0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.flags.hasAny([
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.bondProperty.flags(),
                    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.bitflags([8 /* Disulfide */])
                ])
            })
        ])
    ])
]), { category: StructureSelectionCategory.Bond });
var nonStandardPolymer = StructureSelectionQuery('Non-standard Residues in Polymers', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityType'), 'polymer']),
        'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
        'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('isNonStandard')
    })
]), { category: StructureSelectionCategory.Residue });
var coarse = StructureSelectionQuery('Coarse Elements', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
        'chain-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set('sphere', 'gaussian'), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('objectPrimitive')
        ])
    })
]), { category: StructureSelectionCategory.Type });
var ring = StructureSelectionQuery('Rings in Residues', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.rings()
]), { category: StructureSelectionCategory.Residue });
var aromaticRing = StructureSelectionQuery('Aromatic Rings in Residues', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.rings({ 'only-aromatic': true })
]), { category: StructureSelectionCategory.Residue });
var surroundings = StructureSelectionQuery('Surrounding Residues (5 \u212B) of Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.exceptBy({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.includeSurroundings({
            0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current(),
            radius: 5,
            'as-whole-residues': true
        }),
        by: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current()
    })
]), {
    description: 'Select residues within 5 \u212B of the current selection.',
    category: StructureSelectionCategory.Manipulate,
    referencesCurrent: true
});
var complement = StructureSelectionQuery('Inverse / Complement of Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.exceptBy({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.all(),
        by: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current()
    })
]), {
    description: 'Select everything not in the current selection.',
    category: StructureSelectionCategory.Manipulate,
    referencesCurrent: true
});
var covalentlyBonded = StructureSelectionQuery('Residues Covalently Bonded to Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.includeConnected({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current(), 'layer-count': 1, 'as-whole-residues': true
    })
]), {
    description: 'Select residues covalently bonded to current selection.',
    category: StructureSelectionCategory.Manipulate,
    referencesCurrent: true
});
var covalentlyOrMetallicBonded = StructureSelectionQuery('Residues with Cov. or Metallic Bond to Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.includeConnected({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current(),
        'layer-count': 1,
        'as-whole-residues': true,
        'bond-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.flags.hasAny([
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.bondProperty.flags(),
            _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.bitflags([
                1 /* Covalent */ | 2 /* MetallicCoordination */
            ])
        ])
    })
]), {
    description: 'Select residues with covalent or metallic bond to current selection.',
    category: StructureSelectionCategory.Manipulate,
    referencesCurrent: true
});
var wholeResidues = StructureSelectionQuery('Whole Residues of Selection', _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
    _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.wholeResidues({
        0: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].internal.generator.current()
    })
]), {
    description: 'Expand current selection to whole residues.',
    category: StructureSelectionCategory.Manipulate,
    referencesCurrent: true
});
var StandardAminoAcids = [
    [['HIS'], 'Histidine'],
    [['ARG'], 'Arginine'],
    [['LYS'], 'Lysine'],
    [['ILE'], 'Isoleucine'],
    [['PHE'], 'Phenylalanine'],
    [['LEU'], 'Leucine'],
    [['TRP'], 'Tryptophan'],
    [['ALA'], 'Alanine'],
    [['MET'], 'Methionine'],
    [['PRO'], 'Proline'],
    [['CYS'], 'Cysteine'],
    [['ASN'], 'Asparagine'],
    [['VAL'], 'Valine'],
    [['GLY'], 'Glycine'],
    [['SER'], 'Serine'],
    [['GLN'], 'Glutamine'],
    [['TYR'], 'Tyrosine'],
    [['ASP'], 'Aspartic Acid'],
    [['GLU'], 'Glutamic Acid'],
    [['THR'], 'Threonine'],
    [['SEC'], 'Selenocysteine'],
    [['PYL'], 'Pyrrolysine'],
    [['UNK'], 'Unknown'],
].sort(function (a, b) { return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0; });
var StandardNucleicBases = [
    [['A', 'DA'], 'Adenosine'],
    [['C', 'DC'], 'Cytidine'],
    [['T', 'DT'], 'Thymidine'],
    [['G', 'DG'], 'Guanosine'],
    [['I', 'DI'], 'Inosine'],
    [['U', 'DU'], 'Uridine'],
    [['N', 'DN'], 'Unknown'],
].sort(function (a, b) { return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0; });
function ResidueQuery(_a, category, priority) {
    var names = _a[0], label = _a[1];
    if (priority === void 0) { priority = 0; }
    var description = names.length === 1 && !StandardResidues.has(names[0])
        ? "[" + names[0] + "] " + label
        : label + " (" + names.join(', ') + ")";
    return StructureSelectionQuery(description, _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
            'residue-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], names), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('auth_comp_id')])
        })
    ]), { category: category, priority: priority, description: description });
}
function ElementSymbolQuery(_a, category, priority) {
    var names = _a[0], label = _a[1];
    var description = label + " (" + names.join(', ') + ")";
    return StructureSelectionQuery(description, _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
            'atom-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].set.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], names), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].acp('elementSymbol')])
        })
    ]), { category: category, priority: priority, description: description });
}
function EntityDescriptionQuery(_a, category, priority) {
    var names = _a[0], label = _a[1];
    var description = "" + label;
    return StructureSelectionQuery("" + label, _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
            'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.list.equal([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].list.apply(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"], names), _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].ammp('entityDescription')])
        })
    ]), { category: category, priority: priority, description: description });
}
var StandardResidues = _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].unionMany(_mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["AminoAcidNamesL"], _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["RnaBaseNames"], _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["DnaBaseNames"], _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_2__["WaterNames"]);
function getElementQueries(structures) {
    var uniqueElements = new Set();
    for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
        var structure = structures_1[_i];
        structure.uniqueElementSymbols.forEach(function (e) { return uniqueElements.add(e); });
    }
    var queries = [];
    uniqueElements.forEach(function (e) {
        var label = _mol_model_structure_model_properties_atomic_types__WEBPACK_IMPORTED_MODULE_7__[/* ElementNames */ "a"][e] || e;
        queries.push(ElementSymbolQuery([[e], label], 'Element Symbol', 0));
    });
    return queries;
}
function getNonStandardResidueQueries(structures) {
    var residueLabels = new Map();
    var uniqueResidues = new Set();
    for (var _i = 0, structures_2 = structures; _i < structures_2.length; _i++) {
        var structure = structures_2[_i];
        structure.uniqueResidueNames.forEach(function (r) { return uniqueResidues.add(r); });
        var _loop_1 = function (m) {
            structure.uniqueResidueNames.forEach(function (r) {
                var comp = m.properties.chemicalComponentMap.get(r);
                if (comp)
                    residueLabels.set(r, comp.name);
            });
        };
        for (var _a = 0, _b = structure.models; _a < _b.length; _a++) {
            var m = _b[_a];
            _loop_1(m);
        }
    }
    var queries = [];
    _mol_util_set__WEBPACK_IMPORTED_MODULE_5__[/* SetUtils */ "a"].difference(uniqueResidues, StandardResidues).forEach(function (r) {
        var label = residueLabels.get(r) || r;
        queries.push(ResidueQuery([[r], label], 'Ligand/Non-standard Residue', 200));
    });
    return queries;
}
function getPolymerAndBranchedEntityQueries(structures) {
    var uniqueEntities = new Map();
    var l = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.create();
    for (var _i = 0, structures_3 = structures; _i < structures_3.length; _i++) {
        var structure = structures_3[_i];
        l.structure = structure;
        for (var _a = 0, _b = structure.unitSymmetryGroups; _a < _b.length; _a++) {
            var ug = _b[_a];
            l.unit = ug.units[0];
            l.element = ug.elements[0];
            var entityType = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].entity.type(l);
            if (entityType === 'polymer' || entityType === 'branched') {
                var description = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].entity.pdbx_description(l);
                uniqueEntities.set(description.join(', '), description);
            }
        }
    }
    var queries = [];
    uniqueEntities.forEach(function (v, k) {
        queries.push(EntityDescriptionQuery([v, k], 'Polymer/Carbohydrate Entities', 300));
    });
    return queries;
}
function applyBuiltInSelection(to, query, customTag) {
    return to.apply(_transforms__WEBPACK_IMPORTED_MODULE_6__["StateTransforms"].Model.StructureSelectionFromExpression, { expression: StructureSelectionQueries[query].expression, label: StructureSelectionQueries[query].label }, { tags: customTag ? [query, customTag] : [query] });
}
var StructureSelectionQueries = {
    all: all,
    current: current,
    polymer: polymer,
    trace: trace,
    backbone: backbone,
    sidechain: sidechain,
    sidechainWithTrace: sidechainWithTrace,
    protein: protein,
    nucleic: nucleic,
    helix: helix,
    beta: beta,
    water: water,
    ion: ion,
    lipid: lipid,
    branched: branched,
    branchedPlusConnected: branchedPlusConnected,
    branchedConnectedOnly: branchedConnectedOnly,
    ligand: ligand,
    ligandPlusConnected: ligandPlusConnected,
    ligandConnectedOnly: ligandConnectedOnly,
    connectedOnly: connectedOnly,
    disulfideBridges: disulfideBridges,
    nonStandardPolymer: nonStandardPolymer,
    coarse: coarse,
    ring: ring,
    aromaticRing: aromaticRing,
    surroundings: surroundings,
    complement: complement,
    covalentlyBonded: covalentlyBonded,
    covalentlyOrMetallicBonded: covalentlyOrMetallicBonded,
    wholeResidues: wholeResidues,
};
var StructureSelectionQueryRegistry = /** @class */ (function () {
    function StructureSelectionQueryRegistry() {
        var _a, _b;
        this.list = [];
        this.options = [];
        this.version = 1;
        // add built-in
        (_a = this.list).push.apply(_a, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(Object.values(StructureSelectionQueries), StandardAminoAcids.map(function (v) { return ResidueQuery(v, StructureSelectionCategory.AminoAcid); }), StandardNucleicBases.map(function (v) { return ResidueQuery(v, StructureSelectionCategory.NucleicBase); })));
        (_b = this.options).push.apply(_b, this.list.map(function (q) { return [q, q.label, q.category]; }));
    }
    StructureSelectionQueryRegistry.prototype.add = function (q) {
        this.list.push(q);
        this.options.push([q, q.label, q.category]);
        this.version += 1;
    };
    StructureSelectionQueryRegistry.prototype.remove = function (q) {
        var idx = this.list.indexOf(q);
        if (idx !== -1) {
            this.list.splice(idx, 1);
            this.options.splice(idx, 1);
            this.version += 1;
        }
    };
    return StructureSelectionQueryRegistry;
}());

//# sourceMappingURL=structure-selection-query.js.map

/***/ }),
/* 81 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ addCylinder; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ addDoubleCylinder; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ addFixedCountDashedCylinder; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh-builder.js
var mesh_builder = __webpack_require__(34);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/primitive.js
var primitive = __webpack_require__(127);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/cylinder.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

// adapted from three.js, MIT License Copyright 2010-2018 three.js authors

var DefaultCylinderProps = {
    radiusTop: 1,
    radiusBottom: 1,
    height: 1,
    radialSegments: 8,
    heightSegments: 1,
    topCap: false,
    bottomCap: false,
    thetaStart: 0.0,
    thetaLength: Math.PI * 2
};
function Cylinder(props) {
    var _a = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultCylinderProps), props), radiusTop = _a.radiusTop, radiusBottom = _a.radiusBottom, height = _a.height, radialSegments = _a.radialSegments, heightSegments = _a.heightSegments, topCap = _a.topCap, bottomCap = _a.bottomCap, thetaStart = _a.thetaStart, thetaLength = _a.thetaLength;
    // buffers
    var indices = [];
    var vertices = [];
    var normals = [];
    // helper variables
    var index = 0;
    var indexArray = [];
    var halfHeight = height / 2;
    // generate geometry
    generateTorso();
    if (topCap && radiusTop > 0)
        generateCap(true);
    if (bottomCap && radiusBottom > 0)
        generateCap(false);
    return {
        vertices: new Float32Array(vertices),
        normals: new Float32Array(normals),
        indices: new Uint32Array(indices)
    };
    function generateTorso() {
        var normal = linear_algebra["Vec3"].zero();
        // this will be used to calculate the normal
        var slope = (radiusBottom - radiusTop) / height;
        // generate vertices, normals and uvs
        for (var y = 0; y <= heightSegments; ++y) {
            var indexRow = [];
            var v = y / heightSegments;
            // calculate the radius of the current row
            var radius = v * (radiusBottom - radiusTop) + radiusTop;
            for (var x = 0; x <= radialSegments; ++x) {
                var u = x / radialSegments;
                var theta = u * thetaLength + thetaStart;
                var sinTheta = Math.sin(theta);
                var cosTheta = Math.cos(theta);
                // vertex
                vertices.push(radius * sinTheta, -v * height + halfHeight, radius * cosTheta);
                // normal
                linear_algebra["Vec3"].normalize(normal, linear_algebra["Vec3"].set(normal, sinTheta, slope, cosTheta));
                normals.push.apply(normals, normal);
                // save index of vertex in respective row
                indexRow.push(index++);
            }
            // now save vertices of the row in our index array
            indexArray.push(indexRow);
        }
        // generate indices
        for (var x = 0; x < radialSegments; ++x) {
            for (var y = 0; y < heightSegments; ++y) {
                // we use the index array to access the correct indices
                var a = indexArray[y][x];
                var b = indexArray[y + 1][x];
                var c = indexArray[y + 1][x + 1];
                var d = indexArray[y][x + 1];
                // faces
                indices.push(a, b, d);
                indices.push(b, c, d);
            }
        }
    }
    function generateCap(top) {
        var radius = (top === true) ? radiusTop : radiusBottom;
        var sign = (top === true) ? 1 : -1;
        // save the index of the first center vertex
        var centerIndexStart = index;
        // first we generate the center vertex data of the cap.
        // because the geometry needs one set of uvs per face,
        // we must generate a center vertex per face/segment
        for (var x = 1; x <= radialSegments; ++x) {
            // vertex
            vertices.push(0, halfHeight * sign, 0);
            // normal
            normals.push(0, sign, 0);
            // increase index
            ++index;
        }
        // save the index of the last center vertex
        var centerIndexEnd = index;
        // now we generate the surrounding vertices, normals and uvs
        for (var x = 0; x <= radialSegments; ++x) {
            var u = x / radialSegments;
            var theta = u * thetaLength + thetaStart;
            var cosTheta = Math.cos(theta);
            var sinTheta = Math.sin(theta);
            // vertex
            vertices.push(radius * sinTheta, halfHeight * sign, radius * cosTheta);
            // normal
            normals.push(0, sign, 0);
            // increase index
            ++index;
        }
        // generate indices
        for (var x = 0; x < radialSegments; ++x) {
            var c = centerIndexStart + x;
            var i = centerIndexEnd + x;
            if (top === true) {
                indices.push(i, i + 1, c); // face top
            }
            else {
                indices.push(i + 1, i, c); // face bottom
            }
        }
    }
}
//# sourceMappingURL=cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/prism.js
var prism = __webpack_require__(234);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/polygon.js
var polygon = __webpack_require__(149);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/cylinder.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var cylinderMap = new Map();
var up = linear_algebra["Vec3"].create(0, 1, 0);
var tmpCylinderDir = linear_algebra["Vec3"].zero();
var tmpCylinderMatDir = linear_algebra["Vec3"].zero();
var tmpCylinderCenter = linear_algebra["Vec3"].zero();
var tmpCylinderMat = linear_algebra["Mat4"].zero();
var tmpCylinderStart = linear_algebra["Vec3"].zero();
var tmpUp = linear_algebra["Vec3"].zero();
function setCylinderMat(m, start, dir, length) {
    linear_algebra["Vec3"].setMagnitude(tmpCylinderMatDir, dir, length / 2);
    linear_algebra["Vec3"].add(tmpCylinderCenter, start, tmpCylinderMatDir);
    // ensure the direction used to create the rotation is always pointing in the same
    // direction so the triangles of adjacent cylinder will line up
    linear_algebra["Vec3"].matchDirection(tmpUp, up, tmpCylinderMatDir);
    linear_algebra["Vec3"].makeRotation(m, tmpUp, tmpCylinderMatDir);
    return linear_algebra["Mat4"].setTranslation(m, tmpCylinderCenter);
}
function getCylinder(props) {
    var key = JSON.stringify(props);
    var cylinder = cylinderMap.get(key);
    if (cylinder === undefined) {
        if (props.radialSegments && props.radialSegments <= 4) {
            var box = Object(prism["e" /* Prism */])(Object(polygon["a" /* polygon */])(4, true, props.radiusTop), props);
            cylinder = Object(primitive["c" /* transformPrimitive */])(box, linear_algebra["Mat4"].rotX90);
        }
        else {
            cylinder = Cylinder(props);
        }
        cylinderMap.set(key, cylinder);
    }
    return cylinder;
}
function addCylinder(state, start, end, lengthScale, props) {
    var d = linear_algebra["Vec3"].distance(start, end) * lengthScale;
    props.height = d;
    linear_algebra["Vec3"].sub(tmpCylinderDir, end, start);
    setCylinderMat(tmpCylinderMat, start, tmpCylinderDir, d);
    mesh_builder["a" /* MeshBuilder */].addPrimitive(state, tmpCylinderMat, getCylinder(props));
}
function addDoubleCylinder(state, start, end, lengthScale, shift, props) {
    var d = linear_algebra["Vec3"].distance(start, end) * lengthScale;
    props.height = d;
    var cylinder = getCylinder(props);
    linear_algebra["Vec3"].sub(tmpCylinderDir, end, start);
    // positivly shifted cylinder
    linear_algebra["Vec3"].add(tmpCylinderStart, start, shift);
    setCylinderMat(tmpCylinderMat, tmpCylinderStart, tmpCylinderDir, d);
    mesh_builder["a" /* MeshBuilder */].addPrimitive(state, tmpCylinderMat, cylinder);
    // negativly shifted cylinder
    linear_algebra["Vec3"].sub(tmpCylinderStart, start, shift);
    setCylinderMat(tmpCylinderMat, tmpCylinderStart, tmpCylinderDir, d);
    mesh_builder["a" /* MeshBuilder */].addPrimitive(state, tmpCylinderMat, cylinder);
}
function addFixedCountDashedCylinder(state, start, end, lengthScale, segmentCount, props) {
    var s = Math.floor(segmentCount / 2);
    var step = 1 / segmentCount;
    // automatically adjust length so links/bonds that are rendered as two half cylinders
    // have evenly spaced dashed cylinders
    if (lengthScale < 1) {
        var bias = lengthScale / 2 / segmentCount;
        lengthScale += segmentCount % 2 === 1 ? bias : -bias;
    }
    var d = linear_algebra["Vec3"].distance(start, end) * lengthScale;
    props.height = d * step;
    var cylinder = getCylinder(props);
    linear_algebra["Vec3"].sub(tmpCylinderDir, end, start);
    for (var j = 0; j < s; ++j) {
        var f = step * (j * 2 + 1);
        linear_algebra["Vec3"].setMagnitude(tmpCylinderDir, tmpCylinderDir, d * f);
        linear_algebra["Vec3"].add(tmpCylinderStart, start, tmpCylinderDir);
        setCylinderMat(tmpCylinderMat, tmpCylinderStart, tmpCylinderDir, d * step);
        mesh_builder["a" /* MeshBuilder */].addPrimitive(state, tmpCylinderMat, cylinder);
    }
}
//# sourceMappingURL=cylinder.js.map

/***/ }),
/* 82 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return EPSILON; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return equalEps; });
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */
var EPSILON = 0.000001;
function equalEps(a, b, eps) {
    return Math.abs(a - b) <= eps;
}
//# sourceMappingURL=common.js.map

/***/ }),
/* 83 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return now; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return formatTimespan; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var now = (function () {
    if (typeof window !== 'undefined' && window.performance) {
        var perf_1 = window.performance;
        return function () { return perf_1.now(); };
    }
    else if (typeof process !== 'undefined' && process.hrtime !== 'undefined' && typeof process.hrtime === 'function') {
        return function () {
            var t = process.hrtime();
            return t[0] * 1000 + t[1] / 1000000;
        };
    }
    else if (Date.now) {
        return function () { return Date.now(); };
    }
    else {
        return function () { return +new Date(); };
    }
}());
function formatTimespan(t, includeMsZeroes) {
    if (includeMsZeroes === void 0) { includeMsZeroes = true; }
    if (isNaN(t))
        return 'n/a';
    var h = Math.floor(t / (60 * 60 * 1000)), m = Math.floor(t / (60 * 1000) % 60), s = Math.floor(t / 1000 % 60), ms = Math.floor(t % 1000).toString();
    while (ms.length < 3)
        ms = '0' + ms;
    while (!includeMsZeroes && ms.length > 1 && ms[ms.length - 1] === '0')
        ms = ms.substr(0, ms.length - 1);
    if (h > 0)
        return h + "h" + m + "m" + s + "." + ms + "s";
    if (m > 0)
        return m + "m" + s + "." + ms + "s";
    if (s > 0)
        return s + "." + ms + "s";
    return t.toFixed(0) + "ms";
}

//# sourceMappingURL=now.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(383)))

/***/ }),
/* 84 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getButtons; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getModifiers; });
/* unused harmony export DefaultInputObserverProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ModifiersKeys; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ButtonsType; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(60);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getButtons(event) {
    if (typeof event === 'object') {
        if ('buttons' in event) {
            return event.buttons;
        }
        else if ('which' in event) {
            var b = event.which; // 'any' to support older browsers
            if (b === 2) {
                return 4;
            }
            else if (b === 3) {
                return 2;
            }
            else if (b > 0) {
                return 1 << (b - 1);
            }
        }
    }
    return 0;
}
function getButton(event) {
    if (typeof event === 'object') {
        if ('button' in event) {
            var b = event.button;
            if (b === 1) {
                return 4;
            }
            else if (b === 2) {
                return 2;
            }
            else if (b >= 0) {
                return 1 << b;
            }
        }
    }
    return 0;
}
function getModifiers(event) {
    return {
        alt: 'altKey' in event ? event.altKey : false,
        shift: 'shiftKey' in event ? event.shiftKey : false,
        control: 'ctrlKey' in event ? event.ctrlKey : false,
        meta: 'metaKey' in event ? event.metaKey : false
    };
}
var DefaultInputObserverProps = {
    noScroll: true,
    noMiddleClickScroll: true,
    noContextMenu: true,
    noPinchZoom: true
};
var ModifiersKeys;
(function (ModifiersKeys) {
    ModifiersKeys.None = create();
    function areEqual(a, b) {
        return a.shift === b.shift && a.alt === b.alt && a.control === b.control && a.meta === b.meta;
    }
    ModifiersKeys.areEqual = areEqual;
    function size(a) {
        if (!a)
            return 0;
        var ret = 0;
        if (!!a.shift)
            ret++;
        if (!!a.alt)
            ret++;
        if (!!a.control)
            ret++;
        if (!!a.meta)
            ret++;
        return ret;
    }
    ModifiersKeys.size = size;
    function create(modifierKeys) {
        if (modifierKeys === void 0) { modifierKeys = {}; }
        return {
            shift: !!modifierKeys.shift,
            alt: !!modifierKeys.alt,
            control: !!modifierKeys.control,
            meta: !!modifierKeys.meta
        };
    }
    ModifiersKeys.create = create;
})(ModifiersKeys || (ModifiersKeys = {}));
var ButtonsType;
(function (ButtonsType) {
    ButtonsType.has = _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* BitFlags */ "a"].has;
    ButtonsType.create = _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* BitFlags */ "a"].create;
})(ButtonsType || (ButtonsType = {}));
function createEvents() {
    return {
        drag: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        interactionEnd: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        click: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        move: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        wheel: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        pinch: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        resize: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        leave: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        enter: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
        modifiers: new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"](),
    };
}
var InputObserver;
(function (InputObserver) {
    function create(props) {
        if (props === void 0) { props = {}; }
        var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultInputObserverProps), props), noScroll = _a.noScroll, noContextMenu = _a.noContextMenu;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ noScroll: noScroll,
            noContextMenu: noContextMenu }, createEvents()), { dispose: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"] });
    }
    InputObserver.create = create;
    function fromElement(element, props) {
        if (props === void 0) { props = {}; }
        var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultInputObserverProps), props), noScroll = _a.noScroll, noMiddleClickScroll = _a.noMiddleClickScroll, noContextMenu = _a.noContextMenu, noPinchZoom = _a.noPinchZoom;
        var lastTouchDistance = 0;
        var pointerDown = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].zero();
        var pointerStart = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].zero();
        var pointerEnd = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].zero();
        var pointerDelta = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].zero();
        var rectSize = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].zero();
        var modifierKeys = {
            shift: false,
            alt: false,
            control: false,
            meta: false
        };
        function getModifierKeys() {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, modifierKeys);
        }
        var dragging = 0 /* Stopped */;
        var disposed = false;
        var buttons = ButtonsType.create(0 /* None */);
        var button = 0 /* None */;
        var isInside = false;
        var events = createEvents();
        var drag = events.drag, interactionEnd = events.interactionEnd, wheel = events.wheel, pinch = events.pinch, click = events.click, move = events.move, leave = events.leave, enter = events.enter, resize = events.resize, modifiers = events.modifiers;
        attach();
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ get noScroll() { return noScroll; }, set noScroll(value) { noScroll = value; }, get noContextMenu() { return noContextMenu; }, set noContextMenu(value) { noContextMenu = value; } }, events), { dispose: dispose });
        function attach() {
            element.addEventListener('contextmenu', onContextMenu, false);
            element.addEventListener('wheel', onMouseWheel, false);
            element.addEventListener('mousedown', onMouseDown, false);
            // for dragging to work outside canvas bounds,
            // mouse move/up events have to be added to a parent, i.e. window
            window.addEventListener('mousemove', onMouseMove, false);
            window.addEventListener('mouseup', onMouseUp, false);
            element.addEventListener('mouseenter', onMouseEnter, false);
            element.addEventListener('mouseleave', onMouseLeave, false);
            element.addEventListener('touchstart', onTouchStart, false);
            element.addEventListener('touchmove', onTouchMove, false);
            element.addEventListener('touchend', onTouchEnd, false);
            // reset buttons and modifier keys state when browser window looses focus
            window.addEventListener('blur', handleBlur);
            window.addEventListener('keyup', handleKeyUp, false);
            window.addEventListener('keydown', handleKeyDown, false);
            window.addEventListener('resize', onResize, false);
        }
        function dispose() {
            if (disposed)
                return;
            disposed = true;
            element.removeEventListener('contextmenu', onContextMenu, false);
            element.removeEventListener('wheel', onMouseWheel, false);
            element.removeEventListener('mousedown', onMouseDown, false);
            window.removeEventListener('mousemove', onMouseMove, false);
            window.removeEventListener('mouseup', onMouseUp, false);
            element.removeEventListener('mouseenter', onMouseEnter, false);
            element.removeEventListener('mouseleave', onMouseLeave, false);
            element.removeEventListener('touchstart', onTouchStart, false);
            element.removeEventListener('touchmove', onTouchMove, false);
            element.removeEventListener('touchend', onTouchEnd, false);
            window.removeEventListener('blur', handleBlur);
            window.removeEventListener('keyup', handleKeyUp, false);
            window.removeEventListener('keydown', handleKeyDown, false);
            window.removeEventListener('resize', onResize, false);
        }
        function onContextMenu(event) {
            if (noContextMenu) {
                event.preventDefault();
            }
        }
        function updateModifierKeys(event) {
            modifierKeys.alt = event.altKey;
            modifierKeys.shift = event.shiftKey;
            modifierKeys.control = event.ctrlKey;
            modifierKeys.meta = event.metaKey;
        }
        function handleBlur() {
            if (buttons || modifierKeys.shift || modifierKeys.alt || modifierKeys.meta || modifierKeys.control) {
                buttons = 0;
                modifierKeys.shift = modifierKeys.alt = modifierKeys.control = modifierKeys.meta = false;
            }
        }
        function handleKeyDown(event) {
            var changed = false;
            if (!modifierKeys.alt && event.altKey) {
                changed = true;
                modifierKeys.alt = true;
            }
            if (!modifierKeys.shift && event.shiftKey) {
                changed = true;
                modifierKeys.shift = true;
            }
            if (!modifierKeys.control && event.ctrlKey) {
                changed = true;
                modifierKeys.control = true;
            }
            if (!modifierKeys.meta && event.metaKey) {
                changed = true;
                modifierKeys.meta = true;
            }
            if (changed && isInside)
                modifiers.next(getModifierKeys());
        }
        function handleKeyUp(event) {
            var changed = false;
            if (modifierKeys.alt && !event.altKey) {
                changed = true;
                modifierKeys.alt = false;
            }
            if (modifierKeys.shift && !event.shiftKey) {
                changed = true;
                modifierKeys.shift = false;
            }
            if (modifierKeys.control && !event.ctrlKey) {
                changed = true;
                modifierKeys.control = false;
            }
            if (modifierKeys.meta && !event.metaKey) {
                changed = true;
                modifierKeys.meta = false;
            }
            if (changed && isInside)
                modifiers.next(getModifierKeys());
        }
        function getCenterTouch(ev) {
            var t0 = ev.touches[0];
            var t1 = ev.touches[1];
            return {
                clientX: (t0.clientX + t1.clientX) / 2,
                clientY: (t0.clientY + t1.clientY) / 2,
                pageX: (t0.pageX + t1.pageX) / 2,
                pageY: (t0.pageY + t1.pageY) / 2
            };
        }
        function getTouchDistance(ev) {
            var dx = ev.touches[0].pageX - ev.touches[1].pageX;
            var dy = ev.touches[0].pageY - ev.touches[1].pageY;
            return Math.sqrt(dx * dx + dy * dy);
        }
        function onTouchStart(ev) {
            if (ev.touches.length === 1) {
                buttons = button = 1 /* Primary */;
                onPointerDown(ev.touches[0]);
            }
            else if (ev.touches.length === 2) {
                buttons = 2 /* Secondary */ & 4 /* Auxilary */;
                button = 2 /* Secondary */;
                onPointerDown(getCenterTouch(ev));
                var touchDistance = getTouchDistance(ev);
                lastTouchDistance = touchDistance;
                pinch.next({
                    distance: touchDistance,
                    fraction: 1,
                    delta: 0,
                    isStart: true,
                    buttons: buttons,
                    button: button,
                    modifiers: getModifierKeys()
                });
            }
            else if (ev.touches.length === 3) {
                buttons = button = 8 /* Forth */;
                onPointerDown(getCenterTouch(ev));
            }
        }
        function onTouchEnd(ev) {
            endDrag();
        }
        function onTouchMove(ev) {
            button = 0 /* None */;
            if (noPinchZoom) {
                ev.preventDefault();
                ev.stopPropagation();
                if (ev.originalEvent) {
                    ev.originalEvent.preventDefault();
                    ev.originalEvent.stopPropagation();
                }
            }
            if (ev.touches.length === 1) {
                buttons = 1 /* Primary */;
                onPointerMove(ev.touches[0]);
            }
            else if (ev.touches.length === 2) {
                var touchDistance = getTouchDistance(ev);
                var touchDelta = lastTouchDistance - touchDistance;
                if (Math.abs(touchDelta) < 4) {
                    buttons = 2 /* Secondary */;
                    onPointerMove(getCenterTouch(ev));
                }
                else {
                    buttons = 4 /* Auxilary */;
                    updateModifierKeys(ev);
                    pinch.next({
                        delta: touchDelta,
                        fraction: lastTouchDistance / touchDistance,
                        distance: touchDistance,
                        isStart: false,
                        buttons: buttons,
                        button: button,
                        modifiers: getModifierKeys()
                    });
                }
                lastTouchDistance = touchDistance;
            }
            else if (ev.touches.length === 3) {
                buttons = 8 /* Forth */;
                onPointerMove(getCenterTouch(ev));
            }
        }
        function onMouseDown(ev) {
            updateModifierKeys(ev);
            buttons = getButtons(ev);
            button = getButton(ev);
            if (noMiddleClickScroll && buttons === 4 /* Auxilary */) {
                ev.preventDefault;
            }
            onPointerDown(ev);
        }
        function onMouseMove(ev) {
            updateModifierKeys(ev);
            buttons = getButtons(ev);
            button = 0 /* None */;
            onPointerMove(ev);
        }
        function onMouseUp(ev) {
            updateModifierKeys(ev);
            buttons = getButtons(ev);
            button = getButton(ev);
            onPointerUp(ev);
            endDrag();
        }
        function endDrag() {
            interactionEnd.next();
        }
        function onPointerDown(ev) {
            eventOffset(pointerStart, ev);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].copy(pointerDown, pointerStart);
            if (insideBounds(pointerStart)) {
                dragging = 1 /* Started */;
            }
        }
        function onPointerUp(ev) {
            dragging = 0 /* Stopped */;
            eventOffset(pointerEnd, ev);
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].distance(pointerEnd, pointerDown) < 4) {
                var pageX = ev.pageX, pageY = ev.pageY;
                var x = pointerEnd[0], y = pointerEnd[1];
                click.next({ x: x, y: y, pageX: pageX, pageY: pageY, buttons: buttons, button: button, modifiers: getModifierKeys() });
            }
        }
        function onPointerMove(ev) {
            eventOffset(pointerEnd, ev);
            var pageX = ev.pageX, pageY = ev.pageY;
            var x = pointerEnd[0], y = pointerEnd[1];
            var inside = insideBounds(pointerEnd);
            move.next({ x: x, y: y, pageX: pageX, pageY: pageY, buttons: buttons, button: button, modifiers: getModifierKeys(), inside: inside });
            if (dragging === 0 /* Stopped */)
                return;
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].div(pointerDelta, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].sub(pointerDelta, pointerEnd, pointerStart), getClientSize(rectSize));
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].magnitude(pointerDelta) < _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["EPSILON"])
                return;
            var isStart = dragging === 1 /* Started */;
            var dx = pointerDelta[0], dy = pointerDelta[1];
            drag.next({ x: x, y: y, dx: dx, dy: dy, pageX: pageX, pageY: pageY, buttons: buttons, button: button, modifiers: getModifierKeys(), isStart: isStart });
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].copy(pointerStart, pointerEnd);
            dragging = 2 /* Moving */;
        }
        function onMouseWheel(ev) {
            if (noScroll) {
                ev.preventDefault();
            }
            var scale = 1;
            switch (ev.deltaMode) {
                case 0:
                    scale = 1;
                    break; // pixels
                case 1:
                    scale = 40;
                    break; // lines
                case 2:
                    scale = 800;
                    break; // pages
            }
            var dx = (ev.deltaX || 0) * scale;
            var dy = (ev.deltaY || 0) * scale;
            var dz = (ev.deltaZ || 0) * scale;
            buttons = button = 4 /* Auxilary */;
            if (dx || dy || dz) {
                wheel.next({ dx: dx, dy: dy, dz: dz, buttons: buttons, button: button, modifiers: getModifierKeys() });
            }
        }
        function onMouseEnter(ev) {
            isInside = true;
            enter.next();
        }
        function onMouseLeave(ev) {
            isInside = false;
            leave.next();
        }
        function onResize(ev) {
            resize.next();
        }
        function insideBounds(pos) {
            if (element instanceof Window || element instanceof Document || element === document.body) {
                return true;
            }
            else {
                var rect = element.getBoundingClientRect();
                return pos[0] >= 0 && pos[1] >= 0 && pos[0] < rect.width && pos[1] < rect.height;
            }
        }
        function getClientSize(out) {
            out[0] = element.clientWidth;
            out[1] = element.clientHeight;
            return out;
        }
        function eventOffset(out, ev) {
            var cx = ev.clientX || 0;
            var cy = ev.clientY || 0;
            var rect = element.getBoundingClientRect();
            out[0] = cx - rect.left;
            out[1] = cy - rect.top;
            return out;
        }
    }
    InputObserver.fromElement = fromElement;
})(InputObserver || (InputObserver = {}));
/* harmony default export */ __webpack_exports__["c"] = (InputObserver);
//# sourceMappingURL=input-observer.js.map

/***/ }),
/* 85 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return assignIfUndefined; });
/* unused harmony export shallowMerge2 */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return shallowEqual; });
/* unused harmony export shallowMerge */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return shallowMergeArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return deepClone; });
/* unused harmony export mapObjectMap */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return objectForEach; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var hasOwnProperty = Object.prototype.hasOwnProperty;
/** Assign to the object if a given property in update is undefined */
function assignIfUndefined(to, full) {
    for (var _i = 0, _a = Object.keys(full); _i < _a.length; _i++) {
        var k = _a[_i];
        if (!hasOwnProperty.call(full, k))
            continue;
        if (typeof to[k] === 'undefined') {
            to[k] = full[k];
        }
    }
    return to;
}
/** Create new object if any property in "update" changes in "source". */
function shallowMerge2(source, update) {
    // Adapted from LiteMol (https://github.com/dsehnal/LiteMol)
    var changed = false;
    for (var _i = 0, _a = Object.keys(update); _i < _a.length; _i++) {
        var k = _a[_i];
        if (!hasOwnProperty.call(update, k))
            continue;
        if (update[k] !== source[k]) {
            changed = true;
            break;
        }
    }
    if (!changed)
        return source;
    return Object.assign({}, source, update);
}
function shallowEqual(a, b) {
    if (!a) {
        if (!b)
            return true;
        return false;
    }
    if (!b)
        return false;
    var keys = Object.keys(a);
    if (Object.keys(b).length !== keys.length)
        return false;
    for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
        var k = keys_1[_i];
        if (!hasOwnProperty.call(a, k) || a[k] !== b[k])
            return false;
    }
    return true;
}
function shallowMerge(source) {
    var rest = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        rest[_i - 1] = arguments[_i];
    }
    return shallowMergeArray(source, rest);
}
function shallowMergeArray(source, rest) {
    // Adapted from LiteMol (https://github.com/dsehnal/LiteMol)
    var ret = source;
    for (var s = 0; s < rest.length; s++) {
        if (!rest[s])
            continue;
        ret = shallowMerge2(source, rest[s]);
        if (ret !== source) {
            for (var i = s + 1; i < rest.length; i++) {
                ret = Object.assign(ret, rest[i]);
            }
            break;
        }
    }
    return ret;
}
/** Simple deep clone for number, boolean, string, null, undefined, object, array */
function deepClone(source) {
    if (null === source || 'object' !== typeof source)
        return source;
    if (source instanceof Array) {
        var copy = [];
        for (var i = 0, len = source.length; i < len; i++) {
            copy[i] = deepClone(source[i]);
        }
        return copy;
    }
    // `instanceof Object` does not find `Object.create(null)`
    if (typeof source === 'object' && !('prototype' in source)) {
        var copy = {};
        for (var k in source) {
            if (hasOwnProperty.call(source, k))
                copy[k] = deepClone(source[k]);
        }
        return copy;
    }
    throw new Error("Can't clone, type \"" + typeof source + "\" unsupported");
}
function mapObjectMap(o, f) {
    var ret = {};
    for (var _i = 0, _a = Object.keys(o); _i < _a.length; _i++) {
        var k = _a[_i];
        ret[k] = f(o[k]);
    }
    return ret;
}
function objectForEach(o, f) {
    if (!o)
        return;
    for (var _i = 0, _a = Object.keys(o); _i < _a.length; _i++) {
        var k = _a[_i];
        f(o[k], k);
    }
}
//# sourceMappingURL=object.js.map

/***/ }),
/* 86 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export NullLocationValue */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LocationIterator; });
/* harmony import */ var _mol_model_location__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(144);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var NullLocationValue = {
    location: _mol_model_location__WEBPACK_IMPORTED_MODULE_0__[/* NullLocation */ "b"],
    index: 0,
    groupIndex: 0,
    instanceIndex: 0,
    isSecondary: false
};
function LocationIterator(groupCount, instanceCount, getLocation, isComplex, isSecondary) {
    if (isComplex === void 0) { isComplex = false; }
    if (isSecondary === void 0) { isSecondary = function () { return false; }; }
    var value = {
        location: _mol_model_location__WEBPACK_IMPORTED_MODULE_0__[/* NullLocation */ "b"],
        index: 0,
        groupIndex: 0,
        instanceIndex: 0,
        isSecondary: false
    };
    var hasNext = value.groupIndex < groupCount;
    var isNextNewInstance = false;
    var groupIndex = 0;
    var instanceIndex = 0;
    return {
        get hasNext() { return hasNext; },
        get isNextNewInstance() { return isNextNewInstance; },
        groupCount: groupCount,
        instanceCount: instanceCount,
        count: groupCount * instanceCount,
        isComplex: isComplex,
        move: function () {
            if (hasNext) {
                value.groupIndex = groupIndex;
                value.instanceIndex = instanceIndex;
                value.index = instanceIndex * groupCount + groupIndex;
                value.location = getLocation(groupIndex, instanceIndex);
                value.isSecondary = isSecondary(groupIndex, instanceIndex);
                ++groupIndex;
                if (groupIndex === groupCount) {
                    ++instanceIndex;
                    isNextNewInstance = true;
                    if (instanceIndex < instanceCount)
                        groupIndex = 0;
                }
                else {
                    isNextNewInstance = false;
                }
                hasNext = groupIndex < groupCount;
            }
            return value;
        },
        reset: function () {
            value.location = _mol_model_location__WEBPACK_IMPORTED_MODULE_0__[/* NullLocation */ "b"];
            value.index = 0;
            value.groupIndex = 0;
            value.instanceIndex = 0;
            value.isSecondary = false;
            hasNext = value.groupIndex < groupCount;
            isNextNewInstance = false;
            groupIndex = 0;
            instanceIndex = 0;
        },
        skipInstance: function () {
            if (hasNext && value.instanceIndex === instanceIndex) {
                ++instanceIndex;
                groupIndex = 0;
                hasNext = instanceIndex < instanceCount;
            }
        }
    };
}
//# sourceMappingURL=location-iterator.js.map

/***/ }),
/* 87 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Location; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var Location;
(function (Location) {
    function create(structure, unit, element) {
        return {
            kind: 'element-location',
            structure: structure,
            unit: unit,
            element: element || 0
        };
    }
    Location.create = create;
    function clone(l) {
        return create(l.structure, l.unit, l.element);
    }
    Location.clone = clone;
    function set(a, structure, unit, element) {
        if (structure)
            a.structure = structure;
        if (unit)
            a.unit = unit;
        if (element !== undefined)
            a.element = element;
        return a;
    }
    Location.set = set;
    function copy(out, a) {
        out.unit = a.unit;
        out.element = a.element;
        return out;
    }
    Location.copy = copy;
    function is(x) {
        return !!x && x.kind === 'element-location';
    }
    Location.is = is;
    function areEqual(a, b) {
        return a.unit === b.unit && a.element === b.element;
    }
    Location.areEqual = areEqual;
    var pA = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), pB = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
    function distance(a, b) {
        a.unit.conformation.position(a.element, pA);
        b.unit.conformation.position(b.element, pB);
        return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].distance(pA, pB);
    }
    Location.distance = distance;
    function residueIndex(l) {
        return l.unit.model.atomicHierarchy.residueAtomSegments.index[l.element];
    }
    Location.residueIndex = residueIndex;
    function chainIndex(l) {
        return l.unit.model.atomicHierarchy.chainAtomSegments.index[l.element];
    }
    Location.chainIndex = chainIndex;
})(Location || (Location = {}));
//# sourceMappingURL=location.js.map

/***/ }),
/* 88 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorLists", function() { return ColorLists; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorListNames", function() { return ColorListNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorListOptions", function() { return ColorListOptions; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorListOptionsScale", function() { return ColorListOptionsScale; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ColorListOptionsSet", function() { return ColorListOptionsSet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getColorListFromName", function() { return getColorListFromName; });
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(43);
/* harmony import */ var _string__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(41);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var ColorLists = {
    /**
     * Brewer Color Lists
     *
     * Copyright (c) 2002 Cynthia Brewer, Mark Harrower, and The Pennsylvania State University.
     * Licensed under the Apache License, Version 2.0 (the "License");
     */
    'orange-red': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Orange-Red', 'sequential', 'Orange-Red, sequential color scheme from ColorBrewer 2.0', [0xfff7ec, 0xfee8c8, 0xfdd49e, 0xfdbb84, 0xfc8d59, 0xef6548, 0xd7301f, 0xb30000, 0x7f0000]),
    'purple-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Purple-Blue', 'sequential', 'Purple-Blue, sequential color scheme from ColorBrewer 2.0', [0xfff7fb, 0xece7f2, 0xd0d1e6, 0xa6bddb, 0x74a9cf, 0x3690c0, 0x0570b0, 0x045a8d, 0x023858]),
    'blue-purple': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Blue-Purple', 'sequential', 'Blue-Purple, sequential color scheme from ColorBrewer 2.0', [0xf7fcfd, 0xe0ecf4, 0xbfd3e6, 0x9ebcda, 0x8c96c6, 0x8c6bb1, 0x88419d, 0x810f7c, 0x4d004b]),
    'oranges': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Oranges', 'sequential', '', [0xfff5eb, 0xfee6ce, 0xfdd0a2, 0xfdae6b, 0xfd8d3c, 0xf16913, 0xd94801, 0xa63603, 0x7f2704]),
    'blue-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Blue-Green', 'sequential', '', [0xf7fcfd, 0xe5f5f9, 0xccece6, 0x99d8c9, 0x66c2a4, 0x41ae76, 0x238b45, 0x006d2c, 0x00441b]),
    'yellow-orange-brown': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Yellow-Orange-Brown', 'sequential', '', [0xffffe5, 0xfff7bc, 0xfee391, 0xfec44f, 0xfe9929, 0xec7014, 0xcc4c02, 0x993404, 0x662506]),
    'yellow-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Yellow-Green', 'sequential', '', [0xffffe5, 0xf7fcb9, 0xd9f0a3, 0xaddd8e, 0x78c679, 0x41ab5d, 0x238443, 0x006837, 0x004529]),
    'reds': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Reds', 'sequential', '', [0xfff5f0, 0xfee0d2, 0xfcbba1, 0xfc9272, 0xfb6a4a, 0xef3b2c, 0xcb181d, 0xa50f15, 0x67000d]),
    'red-purple': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-Purple', 'sequential', '', [0xfff7f3, 0xfde0dd, 0xfcc5c0, 0xfa9fb5, 0xf768a1, 0xdd3497, 0xae017e, 0x7a0177, 0x49006a]),
    'greens': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Greens', 'sequential', '', [0xf7fcf5, 0xe5f5e0, 0xc7e9c0, 0xa1d99b, 0x74c476, 0x41ab5d, 0x238b45, 0x006d2c, 0x00441b]),
    'yellow-green-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Yellow-Green-Blue', 'sequential', '', [0xffffd9, 0xedf8b1, 0xc7e9b4, 0x7fcdbb, 0x41b6c4, 0x1d91c0, 0x225ea8, 0x253494, 0x081d58]),
    'purples': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Purples', 'sequential', '', [0xfcfbfd, 0xefedf5, 0xdadaeb, 0xbcbddc, 0x9e9ac8, 0x807dba, 0x6a51a3, 0x54278f, 0x3f007d]),
    'green-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Green-Blue', 'sequential', '', [0xf7fcf0, 0xe0f3db, 0xccebc5, 0xa8ddb5, 0x7bccc4, 0x4eb3d3, 0x2b8cbe, 0x0868ac, 0x084081]),
    'greys': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Greys', 'sequential', '', [0xffffff, 0xf0f0f0, 0xd9d9d9, 0xbdbdbd, 0x969696, 0x737373, 0x525252, 0x252525, 0x000000]),
    'yellow-orange-red': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Yellow-Orange-Red', 'sequential', '', [0xffffcc, 0xffeda0, 0xfed976, 0xfeb24c, 0xfd8d3c, 0xfc4e2a, 0xe31a1c, 0xbd0026, 0x800026]),
    'purple-red': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Purple-Red', 'sequential', '', [0xf7f4f9, 0xe7e1ef, 0xd4b9da, 0xc994c7, 0xdf65b0, 0xe7298a, 0xce1256, 0x980043, 0x67001f]),
    'blues': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Blues', 'sequential', '', [0xf7fbff, 0xdeebf7, 0xc6dbef, 0x9ecae1, 0x6baed6, 0x4292c6, 0x2171b5, 0x08519c, 0x08306b]),
    'purple-blue-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Purple-Blue-Green', 'sequential', '', [0xfff7fb, 0xece2f0, 0xd0d1e6, 0xa6bddb, 0x67a9cf, 0x3690c0, 0x02818a, 0x016c59, 0x014636]),
    'spectral': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Spectral', 'diverging', '', [0x9e0142, 0xd53e4f, 0xf46d43, 0xfdae61, 0xfee08b, 0xffffbf, 0xe6f598, 0xabdda4, 0x66c2a5, 0x3288bd, 0x5e4fa2]),
    'red-yellow-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-Yellow-Green', 'diverging', '', [0xa50026, 0xd73027, 0xf46d43, 0xfdae61, 0xfee08b, 0xffffbf, 0xd9ef8b, 0xa6d96a, 0x66bd63, 0x1a9850, 0x006837]),
    'red-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-Blue', 'diverging', '', [0x67001f, 0xb2182b, 0xd6604d, 0xf4a582, 0xfddbc7, 0xf7f7f7, 0xd1e5f0, 0x92c5de, 0x4393c3, 0x2166ac, 0x053061]),
    'pink-yellow-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Pink-Yellow-Green', 'diverging', '', [0x8e0152, 0xc51b7d, 0xde77ae, 0xf1b6da, 0xfde0ef, 0xf7f7f7, 0xe6f5d0, 0xb8e186, 0x7fbc41, 0x4d9221, 0x276419]),
    'purple-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Purple-Green', 'diverging', '', [0x40004b, 0x762a83, 0x9970ab, 0xc2a5cf, 0xe7d4e8, 0xf7f7f7, 0xd9f0d3, 0xa6dba0, 0x5aae61, 0x1b7837, 0x00441b]),
    'red-yellow-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-Yellow-Blue', 'diverging', 'Red-Yellow-Blue, diverging color scheme from ColorBrewer 2.0', [0xa50026, 0xd73027, 0xf46d43, 0xfdae61, 0xfee090, 0xffffbf, 0xe0f3f8, 0xabd9e9, 0x74add1, 0x4575b4, 0x313695]),
    'brown-white-green': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Brown-White-Green', 'diverging', '', [0x543005, 0x8c510a, 0xbf812d, 0xdfc27d, 0xf6e8c3, 0xf5f5f5, 0xc7eae5, 0x80cdc1, 0x35978f, 0x01665e, 0x003c30]),
    'red-grey': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-Grey', 'diverging', '', [0x67001f, 0xb2182b, 0xd6604d, 0xf4a582, 0xfddbc7, 0xffffff, 0xe0e0e0, 0xbababa, 0x878787, 0x4d4d4d, 0x1a1a1a]),
    'orange-purple': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Orange-Purple', 'diverging', '', [0x7f3b08, 0xb35806, 0xe08214, 0xfdb863, 0xfee0b6, 0xf7f7f7, 0xd8daeb, 0xb2abd2, 0x8073ac, 0x542788, 0x2d004b]),
    'set-2': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Set-2', 'qualitative', '', [0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3]),
    'accent': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Accent', 'qualitative', '', [0x7fc97f, 0xbeaed4, 0xfdc086, 0xffff99, 0x386cb0, 0xf0027f, 0xbf5b17, 0x666666]),
    'set-1': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Set-1', 'qualitative', '', [0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999]),
    'set-3': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Set-3', 'qualitative', '', [0x8dd3c7, 0xffffb3, 0xbebada, 0xfb8072, 0x80b1d3, 0xfdb462, 0xb3de69, 0xfccde5, 0xd9d9d9, 0xbc80bd, 0xccebc5, 0xffed6f]),
    'dark-2': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Dark-2', 'qualitative', '', [0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666]),
    'paired': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Paired', 'qualitative', '', [0xa6cee3, 0x1f78b4, 0xb2df8a, 0x33a02c, 0xfb9a99, 0xe31a1c, 0xfdbf6f, 0xff7f00, 0xcab2d6, 0x6a3d9a, 0xffff99, 0xb15928]),
    'pastel-2': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Pastel-2', 'qualitative', '', [0xb3e2cd, 0xfdcdac, 0xcbd5e8, 0xf4cae4, 0xe6f5c9, 0xfff2ae, 0xf1e2cc, 0xcccccc]),
    'pastel-1': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Pastel-1', 'qualitative', '', [0xfbb4ae, 0xb3cde3, 0xccebc5, 0xdecbe4, 0xfed9a6, 0xffffcc, 0xe5d8bd, 0xfddaec, 0xf2f2f2]),
    'many-distinct': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Many-Distinct', 'qualitative', '', [
        // dark-2
        0x1b9e77, 0xd95f02, 0x7570b3, 0xe7298a, 0x66a61e, 0xe6ab02, 0xa6761d, 0x666666,
        // set-1
        0xe41a1c, 0x377eb8, 0x4daf4a, 0x984ea3, 0xff7f00, 0xffff33, 0xa65628, 0xf781bf, 0x999999,
        // set-2
        0x66c2a5, 0xfc8d62, 0x8da0cb, 0xe78ac3, 0xa6d854, 0xffd92f, 0xe5c494, 0xb3b3b3
    ]),
    /**
     * Matplotlib colormaps, including various perceptually uniform shades, see https://bids.github.io/colormap/
     */
    'magma': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Magma', 'sequential', 'Perceptually uniform shades of black-red-white', [0x420f74, 0x4a1079, 0x52127c, 0x5a157e, 0x61187f, 0x691c80, 0x711f81, 0x792281, 0x812581, 0x892881, 0x912a80, 0x992d7f, 0xa12f7e, 0xa9327c, 0xb1357a, 0xb93778, 0xc23a75, 0xca3e72, 0xd1426e, 0xd9466a, 0xe04b66, 0xe65162, 0xec585f, 0xf0605d, 0xf4685b, 0xf7715b, 0xf97b5d, 0xfb8460, 0xfc8e63, 0xfd9768, 0xfda16e, 0xfeaa74, 0xfeb37b, 0xfebc82, 0xfec689, 0xfdcf92, 0xfdd89a, 0xfde1a3, 0xfceaac, 0xfcf3b5, 0xfbfcbf]),
    'inferno': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Inferno', 'sequential', 'Perceptually uniform shades of black-red-yellow', [0x480b6a, 0x500d6c, 0x58106d, 0x60136e, 0x68166e, 0x70196e, 0x781c6d, 0x801f6b, 0x88216a, 0x902468, 0x982765, 0xa02a62, 0xa72d5f, 0xaf315b, 0xb73456, 0xbe3852, 0xc53d4d, 0xcc4148, 0xd24742, 0xd94d3d, 0xde5337, 0xe45a31, 0xe8612b, 0xed6825, 0xf0701e, 0xf37918, 0xf68111, 0xf88a0b, 0xfa9306, 0xfb9d06, 0xfba60b, 0xfbb014, 0xfbb91e, 0xf9c32a, 0xf8cd37, 0xf5d745, 0xf3e056, 0xf1e968, 0xf1f27d, 0xf5f891, 0xfcfea4]),
    'plasma': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Plasma', 'sequential', 'Perceptually uniform shades of blue-red-yellow', [0x1b068c, 0x250591, 0x2f0495, 0x380499, 0x40039c, 0x49029f, 0x5101a2, 0x5901a4, 0x6100a6, 0x6800a7, 0x7000a8, 0x7801a8, 0x7f03a7, 0x8607a6, 0x8e0ca4, 0x9511a1, 0x9b179e, 0xa21c9a, 0xa82296, 0xae2791, 0xb42d8d, 0xb93388, 0xbe3883, 0xc33e7f, 0xc8447a, 0xcd4975, 0xd14f71, 0xd6556d, 0xda5a68, 0xde6064, 0xe26660, 0xe56c5b, 0xe97257, 0xec7853, 0xef7e4e, 0xf2854a, 0xf58b46, 0xf79241, 0xf9993d, 0xfaa039, 0xfca735, 0xfdaf31, 0xfdb62d, 0xfdbe29, 0xfdc626, 0xfcce25, 0xfad624, 0xf8df24, 0xf5e726, 0xf2f026, 0xeff821]),
    'viridis': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Viridis', 'sequential', 'Perceptually uniform shades of blue-green-yellow', [0x45085b, 0x470f62, 0x471669, 0x481d6f, 0x482374, 0x472a79, 0x46307d, 0x453681, 0x433c84, 0x414286, 0x3e4888, 0x3c4d8a, 0x3a538b, 0x37588c, 0x355d8c, 0x32628d, 0x30678d, 0x2e6c8e, 0x2c718e, 0x2a768e, 0x287a8e, 0x267f8e, 0x24848d, 0x23898d, 0x218d8c, 0x1f928c, 0x1e978a, 0x1e9b89, 0x1ea087, 0x20a585, 0x23a982, 0x28ae7f, 0x2eb27c, 0x35b778, 0x3dbb74, 0x45bf6f, 0x4fc369, 0x59c764, 0x64cb5d, 0x70ce56, 0x7cd24f, 0x88d547, 0x95d73f, 0xa2da37, 0xafdc2e, 0xbdde26, 0xcae01e, 0xd7e219, 0xe4e318, 0xf1e51c, 0xfde724]),
    'cividis': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Cividis', 'sequential', 'Perceptually uniform shades of blue-green-yellow, should look effectively identical to colorblind and non-colorblind users', [0x002c67, 0x003070, 0x083370, 0x16366f, 0x1f3a6e, 0x273d6d, 0x2e416c, 0x34446c, 0x39486c, 0x3f4b6b, 0x444f6b, 0x49526b, 0x4e566c, 0x52596c, 0x575d6d, 0x5b606e, 0x60646e, 0x64676f, 0x686b71, 0x6d6e72, 0x717273, 0x757575, 0x797977, 0x7e7d78, 0x838078, 0x878478, 0x8c8878, 0x918c77, 0x968f77, 0x9b9376, 0xa09775, 0xa59b73, 0xaa9f72, 0xafa370, 0xb4a76f, 0xb9ab6d, 0xbeb06a, 0xc4b468, 0xc9b865, 0xcebc62, 0xd4c15e, 0xd9c55a, 0xdfca56, 0xe4ce51, 0xead34c, 0xefd846, 0xf5dc3f, 0xfbe136, 0xfde737]),
    'twilight': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Twilight', 'sequential', 'Perceptually uniform shades of white-blue-black-red-white, cyclic', [0xdfd9e1, 0xd8d7dd, 0xced3d8, 0xc2cdd3, 0xb4c7ce, 0xa7c0ca, 0x9ab8c7, 0x8eb0c5, 0x83a8c3, 0x7a9fc2, 0x7297c0, 0x6b8ebf, 0x6684bd, 0x637bbb, 0x6171b9, 0x5f67b6, 0x5e5cb2, 0x5e51ad, 0x5d46a7, 0x5c3c9f, 0x5b3196, 0x58278b, 0x531e7d, 0x4d176e, 0x46135f, 0x3e1151, 0x381045, 0x32113b, 0x301336, 0x361138, 0x3e113c, 0x471240, 0x521445, 0x5e1749, 0x6a1a4d, 0x761e4f, 0x812350, 0x8b2a50, 0x95324f, 0x9d3a4f, 0xa5434f, 0xac4d50, 0xb25752, 0xb86155, 0xbc6c59, 0xc0775f, 0xc48267, 0xc78d70, 0xc9987b, 0xcca389, 0xceae97, 0xd2b8a6, 0xd6c1b5, 0xdacac4, 0xddd1d1, 0xe0d6db, 0xe1d8e1]),
    /**
     * https://ai.googleblog.com/2019/08/turbo-improved-rainbow-colormap-for.html
     */
    'turbo': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Turbo', 'sequential', 'Improved (smooth) rainbow colormap for visualization', [0x4a41b5, 0x4a58dd, 0x426ff2, 0x3987f9, 0x2f9df5, 0x28b2e9, 0x25c6d8, 0x27d7c4, 0x2ee5ae, 0x3bf098, 0x4df884, 0x62fd70, 0x7bfe5f, 0x95fb51, 0xaff444, 0xc8ea3a, 0xdedd32, 0xf0cc2c, 0xfeb927, 0xffa423, 0xff8e1f, 0xff761c, 0xf65f18, 0xe54813, 0xd0330e, 0xba2208, 0xa51403, 0x960d00]),
    /**
     * Other
     */
    'rainbow': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Rainbow', 'sequential', '', [0x3361E1, 0x35A845, 0xF9FF00, 0xEC8711, 0xBF2222]),
    'red-white-blue': Object(_color__WEBPACK_IMPORTED_MODULE_0__["ColorList"])('Red-White-Blue', 'diverging', '', [0xBF2222, 0xFFFFFF, 0x3361E1]),
};
var ColorListNames = Object.keys(ColorLists);
var ColorListOptions = ColorListNames.map(function (n) { return [n, ColorLists[n].label, Object(_string__WEBPACK_IMPORTED_MODULE_1__[/* capitalize */ "b"])(ColorLists[n].type)]; });
var ColorListOptionsScale = ColorListOptions.filter(function (v) { return ColorLists[v[0]].type === 'diverging' || ColorLists[v[0]].type === 'sequential'; });
var ColorListOptionsSet = ColorListOptions.filter(function (v) { return ColorLists[v[0]].type === 'qualitative'; });
function getColorListFromName(name) {
    if (name in ColorLists)
        return ColorLists[name];
    console.warn("unknown color list named '" + name + "'");
    return ColorLists['red-yellow-blue'];
}
//# sourceMappingURL=lists.js.map

/***/ }),
/* 89 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Theme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ThemeRegistry; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(196);
/* harmony import */ var _size__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(150);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _mol_util_object__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(85);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var Theme;
(function (Theme) {
    function create(ctx, data, props, theme) {
        theme = theme || createEmpty();
        var colorProps = props.colorTheme;
        var sizeProps = props.sizeTheme;
        theme.color = ctx.colorThemeRegistry.create(colorProps.name, data, colorProps.params);
        theme.size = ctx.sizeThemeRegistry.create(sizeProps.name, data, sizeProps.params);
        return theme;
    }
    Theme.create = create;
    function createEmpty() {
        return { color: _color__WEBPACK_IMPORTED_MODULE_1__[/* ColorTheme */ "a"].Empty, size: _size__WEBPACK_IMPORTED_MODULE_2__[/* SizeTheme */ "a"].Empty };
    }
    Theme.createEmpty = createEmpty;
    function ensureDependencies(ctx, theme, data, props) {
        var _a, _b;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, ((_a = theme.colorThemeRegistry.get(props.colorTheme.name).ensureCustomProperties) === null || _a === void 0 ? void 0 : _a.attach(ctx, data))];
                    case 1:
                        _c.sent();
                        return [4 /*yield*/, ((_b = theme.sizeThemeRegistry.get(props.sizeTheme.name).ensureCustomProperties) === null || _b === void 0 ? void 0 : _b.attach(ctx, data))];
                    case 2:
                        _c.sent();
                        return [2 /*return*/];
                }
            });
        });
    }
    Theme.ensureDependencies = ensureDependencies;
    function releaseDependencies(theme, data, props) {
        var _a, _b;
        (_a = theme.colorThemeRegistry.get(props.colorTheme.name).ensureCustomProperties) === null || _a === void 0 ? void 0 : _a.detach(data);
        (_b = theme.sizeThemeRegistry.get(props.sizeTheme.name).ensureCustomProperties) === null || _b === void 0 ? void 0 : _b.detach(data);
    }
    Theme.releaseDependencies = releaseDependencies;
})(Theme || (Theme = {}));
function getTypes(list) {
    return list.map(function (e) { return [e.name, e.provider.label, e.provider.category]; });
}
var ThemeRegistry = /** @class */ (function () {
    function ThemeRegistry(builtInThemes, emptyProvider) {
        var _this = this;
        this.emptyProvider = emptyProvider;
        this._list = [];
        this._map = new Map();
        this._name = new Map();
        Object(_mol_util_object__WEBPACK_IMPORTED_MODULE_4__[/* objectForEach */ "c"])(builtInThemes, function (p, k) {
            if (p.name !== k)
                throw new Error("Fix build in themes to have matching names. " + p.name + " " + k);
            _this.add(p);
        });
    }
    Object.defineProperty(ThemeRegistry.prototype, "default", {
        get: function () { return this._list[0]; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ThemeRegistry.prototype, "list", {
        get: function () { return this._list; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ThemeRegistry.prototype, "types", {
        get: function () { return getTypes(this._list); },
        enumerable: false,
        configurable: true
    });
    ThemeRegistry.prototype.sort = function () {
        this._list.sort(function (a, b) {
            if (a.provider.category === b.provider.category) {
                return a.provider.label < b.provider.label ? -1 : a.provider.label > b.provider.label ? 1 : 0;
            }
            return a.provider.category < b.provider.category ? -1 : 1;
        });
    };
    ThemeRegistry.prototype.add = function (provider) {
        if (this._map.has(provider.name)) {
            throw new Error(provider.name + " already registered.");
        }
        var name = provider.name;
        this._list.push({ name: name, provider: provider });
        this._map.set(name, provider);
        this._name.set(provider, name);
        this.sort();
    };
    ThemeRegistry.prototype.remove = function (provider) {
        this._list.splice(this._list.findIndex(function (e) { return e.name === provider.name; }), 1);
        var p = this._map.get(provider.name);
        if (p) {
            this._map.delete(provider.name);
            this._name.delete(p);
        }
    };
    ThemeRegistry.prototype.has = function (provider) {
        return this._map.has(provider.name);
    };
    ThemeRegistry.prototype.get = function (name) {
        return this._map.get(name) || this.emptyProvider;
    };
    ThemeRegistry.prototype.getName = function (provider) {
        if (!this._name.has(provider))
            throw new Error("'" + provider.label + "' is not a registered theme provider.");
        return this._name.get(provider);
    };
    ThemeRegistry.prototype.create = function (name, ctx, props) {
        if (props === void 0) { props = {}; }
        var provider = this.get(name);
        return provider.factory(ctx, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].getDefaultValues(provider.getParams(ctx))), props));
    };
    ThemeRegistry.prototype.getApplicableList = function (ctx) {
        return this._list.filter(function (e) { return e.provider.isApplicable(ctx); });
    };
    ThemeRegistry.prototype.getApplicableTypes = function (ctx) {
        return getTypes(this.getApplicableList(ctx));
    };
    return ThemeRegistry;
}());

//# sourceMappingURL=theme.js.map

/***/ }),
/* 90 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SetUtils; });
/* harmony import */ var _mol_data_util_array__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(338);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

// TODO use set@@iterator when targeting es6
var SetUtils;
(function (SetUtils) {
    function toArray(set) {
        return Object(_mol_data_util_array__WEBPACK_IMPORTED_MODULE_0__[/* iterableToArray */ "d"])(set.values());
    }
    SetUtils.toArray = toArray;
    /** Test if set a contains all elements of set b. */
    function isSuperset(setA, setB) {
        var flag = true;
        setB.forEach(function (elem) {
            if (!setA.has(elem))
                flag = false;
        });
        return flag;
    }
    SetUtils.isSuperset = isSuperset;
    /** Add all elements from `sets` to `out` */
    function add(out) {
        var sets = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            sets[_i - 1] = arguments[_i];
        }
        for (var i = 0; i < sets.length; i++) {
            sets[i].forEach(function (elem) { return out.add(elem); });
        }
        return out;
    }
    SetUtils.add = add;
    /** Create set containing elements of both set a and set b. */
    function union(setA, setB) {
        var union = new Set(setA);
        setB.forEach(function (elem) { return union.add(elem); });
        return union;
    }
    SetUtils.union = union;
    function unionMany() {
        var sets = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            sets[_i] = arguments[_i];
        }
        if (sets.length === 0)
            return new Set();
        if (sets.length === 1)
            new Set(sets[0]);
        var union = new Set(sets[0]);
        for (var i = 1, il = sets.length; i < il; i++) {
            sets[i].forEach(function (elem) { return union.add(elem); });
        }
        return union;
    }
    SetUtils.unionMany = unionMany;
    function unionManyArrays(arrays) {
        if (arrays.length === 0)
            return new Set();
        var union = new Set(arrays[0]);
        for (var i = 1; i < arrays.length; i++) {
            for (var _i = 0, _a = arrays[i]; _i < _a.length; _i++) {
                var elem = _a[_i];
                union.add(elem);
            }
        }
        return union;
    }
    SetUtils.unionManyArrays = unionManyArrays;
    /** Create set containing elements of set a that are also in set b. */
    function intersection(setA, setB) {
        var intersection = new Set();
        setB.forEach(function (elem) {
            if (setA.has(elem))
                intersection.add(elem);
        });
        return intersection;
    }
    SetUtils.intersection = intersection;
    function areIntersecting(setA, setB) {
        var flag = false;
        setB.forEach(function (elem) {
            if (setA.has(elem))
                flag = true;
        });
        return flag;
    }
    SetUtils.areIntersecting = areIntersecting;
    function intersectionSize(setA, setB) {
        var count = 0;
        setB.forEach(function (elem) {
            if (setA.has(elem))
                count += 1;
        });
        return count;
    }
    SetUtils.intersectionSize = intersectionSize;
    /** Create set containing elements of set a that are not in set b. */
    function difference(setA, setB) {
        var difference = new Set(setA);
        setB.forEach(function (elem) { return difference.delete(elem); });
        return difference;
    }
    SetUtils.difference = difference;
    /** Number of elements that are in set a but not in set b. */
    function differenceSize(setA, setB) {
        var count = setA.size;
        setA.forEach(function (elem) {
            if (setB.has(elem))
                count -= 1;
        });
        return count;
    }
    SetUtils.differenceSize = differenceSize;
    /** Test if set a and b contain the same elements. */
    function areEqual(setA, setB) {
        if (setA.size !== setB.size)
            return false;
        var flag = true;
        setB.forEach(function (elem) {
            if (!setA.has(elem))
                flag = false;
        });
        return flag;
    }
    SetUtils.areEqual = areEqual;
})(SetUtils || (SetUtils = {}));
//# sourceMappingURL=set.js.map

/***/ }),
/* 91 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export isWebGL */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return isWebGL2; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getInstancedArrays; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return getStandardDerivatives; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getElementIndexUint; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return getVertexArrayObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return getTextureFloat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return getTextureFloatLinear; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getBlendMinMax; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getFragDepth; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getColorBufferFloat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getDrawBuffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return getShaderTextureLod; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getDepthTexture; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function isWebGL(gl) {
    return typeof WebGLRenderingContext !== 'undefined' && gl instanceof WebGLRenderingContext;
}
function isWebGL2(gl) {
    return typeof WebGL2RenderingContext !== 'undefined' && gl instanceof WebGL2RenderingContext;
}
function getInstancedArrays(gl) {
    if (isWebGL2(gl)) {
        return {
            drawArraysInstanced: gl.drawArraysInstanced.bind(gl),
            drawElementsInstanced: gl.drawElementsInstanced.bind(gl),
            vertexAttribDivisor: gl.vertexAttribDivisor.bind(gl),
            VERTEX_ATTRIB_ARRAY_DIVISOR: gl.VERTEX_ATTRIB_ARRAY_DIVISOR
        };
    }
    else {
        var ext = gl.getExtension('ANGLE_instanced_arrays');
        if (ext === null)
            return null;
        return {
            drawArraysInstanced: ext.drawArraysInstancedANGLE.bind(ext),
            drawElementsInstanced: ext.drawElementsInstancedANGLE.bind(ext),
            vertexAttribDivisor: ext.vertexAttribDivisorANGLE.bind(ext),
            VERTEX_ATTRIB_ARRAY_DIVISOR: ext.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE
        };
    }
}
function getStandardDerivatives(gl) {
    if (isWebGL2(gl)) {
        return { FRAGMENT_SHADER_DERIVATIVE_HINT: gl.FRAGMENT_SHADER_DERIVATIVE_HINT };
    }
    else {
        var ext = gl.getExtension('OES_standard_derivatives');
        if (ext === null)
            return null;
        return { FRAGMENT_SHADER_DERIVATIVE_HINT: ext.FRAGMENT_SHADER_DERIVATIVE_HINT_OES };
    }
}
function getElementIndexUint(gl) {
    return isWebGL2(gl) ? {} : gl.getExtension('OES_element_index_uint');
}
function getVertexArrayObject(gl) {
    if (isWebGL2(gl)) {
        return {
            VERTEX_ARRAY_BINDING: gl.VERTEX_ARRAY_BINDING,
            bindVertexArray: gl.bindVertexArray.bind(gl),
            createVertexArray: gl.createVertexArray.bind(gl),
            deleteVertexArray: gl.deleteVertexArray.bind(gl),
            isVertexArray: gl.isVertexArray.bind(gl)
        };
    }
    else {
        var ext = gl.getExtension('OES_vertex_array_object');
        if (ext === null)
            return null;
        return {
            VERTEX_ARRAY_BINDING: ext.VERTEX_ARRAY_BINDING_OES,
            bindVertexArray: ext.bindVertexArrayOES.bind(ext),
            createVertexArray: ext.createVertexArrayOES.bind(ext),
            deleteVertexArray: ext.deleteVertexArrayOES.bind(ext),
            isVertexArray: ext.isVertexArrayOES.bind(ext)
        };
    }
}
function getTextureFloat(gl) {
    return isWebGL2(gl) ? {} : gl.getExtension('OES_texture_float');
}
function getTextureFloatLinear(gl) {
    return gl.getExtension('OES_texture_float_linear');
}
function getBlendMinMax(gl) {
    if (isWebGL2(gl)) {
        return { MIN: gl.MIN, MAX: gl.MAX };
    }
    else {
        var ext = gl.getExtension('EXT_blend_minmax');
        if (ext === null)
            return null;
        return { MIN: ext.MIN_EXT, MAX: ext.MAX_EXT };
    }
}
function getFragDepth(gl) {
    return isWebGL2(gl) ? {} : gl.getExtension('EXT_frag_depth');
}
function getColorBufferFloat(gl) {
    if (isWebGL2(gl)) {
        if (gl.getExtension('EXT_color_buffer_float') === null)
            return null;
        return { RGBA32F: gl.RGBA32F };
    }
    else {
        var ext = gl.getExtension('WEBGL_color_buffer_float');
        if (ext === null)
            return null;
        return { RGBA32F: ext.RGBA32F_EXT };
    }
}
function getDrawBuffers(gl) {
    if (isWebGL2(gl)) {
        return {
            drawBuffers: gl.drawBuffers.bind(gl),
            COLOR_ATTACHMENT0: gl.COLOR_ATTACHMENT0,
            COLOR_ATTACHMENT1: gl.COLOR_ATTACHMENT1,
            COLOR_ATTACHMENT2: gl.COLOR_ATTACHMENT2,
            COLOR_ATTACHMENT3: gl.COLOR_ATTACHMENT3,
            COLOR_ATTACHMENT4: gl.COLOR_ATTACHMENT4,
            COLOR_ATTACHMENT5: gl.COLOR_ATTACHMENT5,
            COLOR_ATTACHMENT6: gl.COLOR_ATTACHMENT6,
            COLOR_ATTACHMENT7: gl.COLOR_ATTACHMENT7,
            DRAW_BUFFER0: gl.DRAW_BUFFER0,
            DRAW_BUFFER1: gl.DRAW_BUFFER1,
            DRAW_BUFFER2: gl.DRAW_BUFFER2,
            DRAW_BUFFER3: gl.DRAW_BUFFER3,
            DRAW_BUFFER4: gl.DRAW_BUFFER4,
            DRAW_BUFFER5: gl.DRAW_BUFFER5,
            DRAW_BUFFER6: gl.DRAW_BUFFER6,
            DRAW_BUFFER7: gl.DRAW_BUFFER7,
            MAX_COLOR_ATTACHMENTS: gl.MAX_COLOR_ATTACHMENTS,
            MAX_DRAW_BUFFERS: gl.MAX_DRAW_BUFFERS,
        };
    }
    else {
        var ext = gl.getExtension('WEBGL_draw_buffers');
        if (ext === null)
            return null;
        return {
            drawBuffers: ext.drawBuffersWEBGL.bind(ext),
            COLOR_ATTACHMENT0: ext.COLOR_ATTACHMENT0_WEBGL,
            COLOR_ATTACHMENT1: ext.COLOR_ATTACHMENT1_WEBGL,
            COLOR_ATTACHMENT2: ext.COLOR_ATTACHMENT2_WEBGL,
            COLOR_ATTACHMENT3: ext.COLOR_ATTACHMENT3_WEBGL,
            COLOR_ATTACHMENT4: ext.COLOR_ATTACHMENT4_WEBGL,
            COLOR_ATTACHMENT5: ext.COLOR_ATTACHMENT5_WEBGL,
            COLOR_ATTACHMENT6: ext.COLOR_ATTACHMENT6_WEBGL,
            COLOR_ATTACHMENT7: ext.COLOR_ATTACHMENT7_WEBGL,
            DRAW_BUFFER0: ext.DRAW_BUFFER0_WEBGL,
            DRAW_BUFFER1: ext.DRAW_BUFFER1_WEBGL,
            DRAW_BUFFER2: ext.DRAW_BUFFER2_WEBGL,
            DRAW_BUFFER3: ext.DRAW_BUFFER3_WEBGL,
            DRAW_BUFFER4: ext.DRAW_BUFFER4_WEBGL,
            DRAW_BUFFER5: ext.DRAW_BUFFER5_WEBGL,
            DRAW_BUFFER6: ext.DRAW_BUFFER6_WEBGL,
            DRAW_BUFFER7: ext.DRAW_BUFFER7_WEBGL,
            MAX_COLOR_ATTACHMENTS: ext.MAX_COLOR_ATTACHMENTS_WEBGL,
            MAX_DRAW_BUFFERS: ext.MAX_DRAW_BUFFERS_WEBGL,
        };
    }
}
function getShaderTextureLod(gl) {
    return isWebGL2(gl) ? {} : gl.getExtension('EXT_shader_texture_lod');
}
function getDepthTexture(gl) {
    if (isWebGL2(gl)) {
        return {
            UNSIGNED_INT_24_8: gl.UNSIGNED_INT_24_8
        };
    }
    else {
        var ext = gl.getExtension('WEBGL_depth_texture');
        if (ext === null)
            return null;
        return {
            UNSIGNED_INT_24_8: ext.UNSIGNED_INT_24_8_WEBGL
        };
    }
}
//# sourceMappingURL=compat.js.map

/***/ }),
/* 92 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "f", function() { return /* binding */ ShaderCode; });
__webpack_require__.d(__webpack_exports__, "e", function() { return /* binding */ PointsShaderCode; });
__webpack_require__.d(__webpack_exports__, "g", function() { return /* binding */ SpheresShaderCode; });
__webpack_require__.d(__webpack_exports__, "h", function() { return /* binding */ TextShaderCode; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ LinesShaderCode; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ MeshShaderCode; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ DirectVolumeShaderCode; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ ImageShaderCode; });
__webpack_require__.d(__webpack_exports__, "i", function() { return /* binding */ addShaderDefines; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/id-factory.js
var id_factory = __webpack_require__(96);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/compat.js
var compat = __webpack_require__(91);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/apply-fog.glsl.js
/* harmony default export */ var apply_fog_glsl = ("\nfloat depth = length(vViewPosition);\nfloat fogFactor = smoothstep(uFogNear, uFogFar, depth);\nfloat fogAlpha = (1.0 - fogFactor) * gl_FragColor.a;\nif (uTransparentBackground == 0) {\n    gl_FragColor.rgb = mix(gl_FragColor.rgb, uFogColor, fogFactor);\n    if (gl_FragColor.a < 1.0)\n        gl_FragColor.a = fogAlpha;\n} else {\n    float fogAlpha = (1.0 - fogFactor) * gl_FragColor.a;\n    gl_FragColor.a = fogAlpha;\n}\n");
//# sourceMappingURL=apply-fog.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/apply-interior-color.glsl.js
/* harmony default export */ var apply_interior_color_glsl = ("\nif (interior) {\n    if (uInteriorColorFlag == 1) {\n        gl_FragColor.rgb = uInteriorColor;\n    } else {\n        gl_FragColor.rgb *= 1.0 - uInteriorDarkening;\n    }\n}\n");
//# sourceMappingURL=apply-interior-color.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/apply-light-color.glsl.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * adapted from three.js (https://github.com/mrdoob/three.js/)
 * which under the MIT License, Copyright © 2010-2019 three.js authors
 */
/* harmony default export */ var apply_light_color_glsl = ("\n// inputs\n// - vec4 material\n// - vec3 vViewPosition\n// - vec3 normal\n// - float uMetalness\n// - float uRoughness\n// - float uReflectivity\n// - float uLightIntensity\n// - float uAmbientIntensity\n\n// outputs\n// - sets gl_FragColor\n\nvec4 color = material;\n\nReflectedLight reflectedLight = ReflectedLight(vec3(0.0), vec3(0.0), vec3(0.0));\n\nPhysicalMaterial physicalMaterial;\nphysicalMaterial.diffuseColor = color.rgb * (1.0 - uMetalness);\nphysicalMaterial.specularRoughness = clamp(uRoughness, 0.04, 1.0);\nphysicalMaterial.specularColor = mix(vec3(0.16 * pow2(uReflectivity)), color.rgb, uMetalness);\n\nGeometricContext geometry;\ngeometry.position = -vViewPosition;\ngeometry.normal = normal;\ngeometry.viewDir = normalize(vViewPosition);\n\nIncidentLight directLight;\ndirectLight.direction = vec3(0.0, 0.0, -1.0);\ndirectLight.color = vec3(uLightIntensity);\n\nRE_Direct_Physical(directLight, geometry, physicalMaterial, reflectedLight);\n\nvec3 irradiance = vec3(uAmbientIntensity) * PI;\nRE_IndirectDiffuse_Physical(irradiance, geometry, physicalMaterial, reflectedLight);\n\nvec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular;\n\ngl_FragColor = vec4(outgoingLight, color.a);\n");
//# sourceMappingURL=apply-light-color.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/apply-marker-color.glsl.js
/* harmony default export */ var apply_marker_color_glsl = ("\nfloat marker = floor(vMarker * 255.0 + 0.5); // rounding required to work on some cards on win\nif (marker > 0.1) {\n    if (intMod(marker, 2.0) > 0.1) {\n        gl_FragColor.rgb = mix(uHighlightColor, gl_FragColor.rgb, 0.3);\n    } else {\n        gl_FragColor.rgb = mix(uSelectColor, gl_FragColor.rgb, 0.3);\n    }\n}\n");
//# sourceMappingURL=apply-marker-color.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-clipping-varying.glsl.js
/* harmony default export */ var assign_clipping_varying_glsl = ("\n#if dClipObjectCount != 0 && defined(dClipping)\n    vClipping = readFromTexture(tClipping, aInstance * float(uGroupCount) + group, uClippingTexDim).a;\n#endif\n");
//# sourceMappingURL=assign-clipping-varying.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-color-varying.glsl.js
/* harmony default export */ var assign_color_varying_glsl = ("\n#if defined(dRenderVariant_color)\n    #if defined(dColorType_attribute)\n        vColor.rgb = aColor;\n    #elif defined(dColorType_instance)\n        vColor.rgb = readFromTexture(tColor, aInstance, uColorTexDim).rgb;\n    #elif defined(dColorType_group)\n        vColor.rgb = readFromTexture(tColor, group, uColorTexDim).rgb;\n    #elif defined(dColorType_groupInstance)\n        vColor.rgb = readFromTexture(tColor, aInstance * float(uGroupCount) + group, uColorTexDim).rgb;\n    #endif\n\n    #ifdef dOverpaint\n        vOverpaint = readFromTexture(tOverpaint, aInstance * float(uGroupCount) + group, uOverpaintTexDim);\n    #endif\n\n    #ifdef dTransparency\n        vGroup = group;\n        vTransparency = readFromTexture(tTransparency, aInstance * float(uGroupCount) + group, uTransparencyTexDim).a;\n    #endif\n#elif defined(dRenderVariant_pick)\n    #if defined(dRenderVariant_pickObject)\n        vColor = vec4(encodeFloatRGB(float(uObjectId)), 1.0);\n    #elif defined(dRenderVariant_pickInstance)\n        vColor = vec4(encodeFloatRGB(aInstance), 1.0);\n    #elif defined(dRenderVariant_pickGroup)\n        vColor = vec4(encodeFloatRGB(group), 1.0);\n    #endif\n#endif\n");
//# sourceMappingURL=assign-color-varying.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-group.glsl.js
/* harmony default export */ var assign_group_glsl = ("\n#ifdef dGeoTexture\n    // aGroup is used as a vertex index here and the group id is retirieved from tPositionGroup\n    float group = readFromTexture(tPositionGroup, aGroup, uGeoTexDim).w;\n#else\n    float group = aGroup;\n#endif\n");
//# sourceMappingURL=assign-group.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-marker-varying.glsl.js
/* harmony default export */ var assign_marker_varying_glsl = ("\nvMarker = readFromTexture(tMarker, aInstance * float(uGroupCount) + group, uMarkerTexDim).a;\n");
//# sourceMappingURL=assign-marker-varying.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-material-color.glsl.js
/* harmony default export */ var assign_material_color_glsl = ("\n#if defined(dRenderVariant_color)\n    #if defined(dColorType_uniform)\n        vec4 material = vec4(uColor, uAlpha);\n    #elif defined(dColorType_varying)\n        vec4 material = vec4(vColor.rgb, uAlpha);\n    #endif\n\n    // mix material with overpaint\n    #if defined(dOverpaint)\n        material.rgb = mix(material.rgb, vOverpaint.rgb, vOverpaint.a);\n    #endif\n\n    // apply screendoor transparency\n    #if defined(dTransparency)\n        float ta = 1.0 - vTransparency;\n        float at = 0.0;\n\n        // shift by view-offset during multi-sample rendering to allow for blending\n        vec2 coord = gl_FragCoord.xy + uViewOffset * 0.25;\n\n        #if defined(dTransparencyVariant_single)\n            const mat4 thresholdMatrix = mat4(\n                1.0 / 17.0,  9.0 / 17.0,  3.0 / 17.0, 11.0 / 17.0,\n                13.0 / 17.0,  5.0 / 17.0, 15.0 / 17.0,  7.0 / 17.0,\n                4.0 / 17.0, 12.0 / 17.0,  2.0 / 17.0, 10.0 / 17.0,\n                16.0 / 17.0,  8.0 / 17.0, 14.0 / 17.0,  6.0 / 17.0\n            );\n            at = thresholdMatrix[int(intMod(coord.x, 4.0))][int(intMod(coord.y, 4.0))];\n        #elif defined(dTransparencyVariant_multi)\n            at = fract(dot(vec3(coord, vGroup + 0.5), vec3(2.0, 7.0, 23.0) / 17.0f));\n        #endif\n\n        if (ta < 0.99 && (ta < 0.01 || ta < at)) discard;\n    #endif\n#elif defined(dRenderVariant_pick)\n    vec4 material = vColor;\n#elif defined(dRenderVariant_depth)\n    #ifdef enabledFragDepth\n        vec4 material = packDepthToRGBA(gl_FragDepthEXT);\n    #else\n        vec4 material = packDepthToRGBA(gl_FragCoord.z);\n    #endif\n#endif\n");
//# sourceMappingURL=assign-material-color.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-position.glsl.js
/* harmony default export */ var assign_position_glsl = ("\nmat4 model = uModel * aTransform;\nmat4 modelView = uView * model;\n#ifdef dGeoTexture\n    vec3 position = readFromTexture(tPositionGroup, aGroup, uGeoTexDim).xyz;\n#else\n    vec3 position = aPosition;\n#endif\nvec4 position4 = vec4(position, 1.0);\nvModelPosition = (model * position4).xyz; // for clipping in frag shader\nvec4 mvPosition = modelView * position4;\nvViewPosition = mvPosition.xyz;\ngl_Position = uProjection * mvPosition;\n");
//# sourceMappingURL=assign-position.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/assign-size.glsl.js
/* harmony default export */ var assign_size_glsl = ("\n#if defined(dSizeType_uniform)\n    float size = uSize;\n#elif defined(dSizeType_attribute)\n    float size = aSize;\n#elif defined(dSizeType_instance)\n    float size = readFromTexture(tSize, aInstance, uSizeTexDim).a;\n#elif defined(dSizeType_group)\n    float size = readFromTexture(tSize, group, uSizeTexDim).a;\n#elif defined(dSizeType_groupInstance)\n    float size = readFromTexture(tSize, aInstance * float(uGroupCount) + group, uSizeTexDim).a;\n#endif\n\n#if defined(dSizeType_instance) || defined(dSizeType_group) || defined(dSizeType_groupInstance)\n    size = decodeFloatLog(size);\n#endif\n\nsize *= uSizeFactor;\n");
//# sourceMappingURL=assign-size.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/check-picking-alpha.glsl.js
/* harmony default export */ var check_picking_alpha_glsl = ("\nfloat depth = length(vViewPosition);\nfloat fogFactor = smoothstep(uFogNear, uFogFar, depth);\nfloat alpha = (1.0 - fogFactor) * uAlpha;\nif (uAlpha < uPickingAlphaThreshold || alpha < 0.1)\n    discard; // ignore so the element below can be picked\n");
//# sourceMappingURL=check-picking-alpha.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/clip-instance.glsl.js
/* harmony default export */ var clip_instance_glsl = ("\n#if defined(dClipVariant_instance) && dClipObjectCount != 0\n    int flag = 0;\n    #if defined(dClipping)\n        flag = int(floor(vClipping * 255.0 + 0.5));\n    #endif\n\n    vec4 mCenter = uModel * aTransform * vec4(uInvariantBoundingSphere.xyz, 1.0);\n    if (clipTest(vec4(mCenter.xyz, uInvariantBoundingSphere.w), flag))\n        // move out of [ -w, +w ] to 'discard' in vert shader\n        gl_Position.z = 2.0 * gl_Position.w;\n#endif\n");
//# sourceMappingURL=clip-instance.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/clip-pixel.glsl.js
/* harmony default export */ var clip_pixel_glsl = ("\n#if defined(dClipVariant_pixel) && dClipObjectCount != 0\n    #if defined(dClipping)\n        int clippingFlag = int(floor(vClipping * 255.0 + 0.5));\n    #else\n        int clippingFlag = 0;\n    #endif\n\n    if (clipTest(vec4(vModelPosition, 0.0), clippingFlag))\n        discard;\n#endif\n");
//# sourceMappingURL=clip-pixel.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/color-frag-params.glsl.js
/* harmony default export */ var color_frag_params_glsl = ("\n#if defined(dRenderVariant_color)\n    #if defined(dColorType_uniform)\n        uniform vec3 uColor;\n    #elif defined(dColorType_varying)\n        varying vec4 vColor;\n    #endif\n\n    #ifdef dOverpaint\n        varying vec4 vOverpaint;\n    #endif\n\n    #ifdef dTransparency\n        varying float vGroup;\n        varying float vTransparency;\n    #endif\n#elif defined(dRenderVariant_pick)\n    #if __VERSION__ != 300\n        varying vec4 vColor;\n    #else\n        flat in vec4 vColor;\n    #endif\n#endif\n");
//# sourceMappingURL=color-frag-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/color-vert-params.glsl.js
/* harmony default export */ var color_vert_params_glsl = ("\n#if defined(dRenderVariant_color)\n    #if defined(dColorType_uniform)\n        uniform vec3 uColor;\n    #elif defined(dColorType_attribute)\n        varying vec4 vColor;\n        attribute vec3 aColor;\n    #elif defined(dColorType_texture)\n        varying vec4 vColor;\n        uniform vec2 uColorTexDim;\n        uniform sampler2D tColor;\n    #endif\n\n    #ifdef dOverpaint\n        varying vec4 vOverpaint;\n        uniform vec2 uOverpaintTexDim;\n        uniform sampler2D tOverpaint;\n    #endif\n\n    #ifdef dTransparency\n        varying float vGroup;\n        varying float vTransparency;\n        uniform vec2 uTransparencyTexDim;\n        uniform sampler2D tTransparency;\n    #endif\n#elif defined(dRenderVariant_pick)\n    #if __VERSION__ != 300\n        varying vec4 vColor;\n    #else\n        flat out vec4 vColor;\n    #endif\n#endif\n");
//# sourceMappingURL=color-vert-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/common-clip.glsl.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Ludovic Autin <autin@scripps.edu>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var common_clip_glsl = ("\n#if dClipObjectCount != 0\n    vec3 quaternionTransform(vec4 q, vec3 v) {\n        vec3 t = 2.0 * cross(q.xyz, v);\n        return v + q.w * t + cross(q.xyz, t);\n    }\n\n    vec4 computePlane(vec3 normal, vec3 inPoint) {\n        return vec4(normalize(normal), -dot(normal, inPoint));\n    }\n\n    float planeSD(vec4 plane, vec3 center) {\n        return -dot(plane.xyz, center - plane.xyz * -plane.w);\n    }\n\n    float sphereSD(vec3 position, vec4 rotation, vec3 size, vec3 center) {\n        return (\n            length(quaternionTransform(vec4(-rotation.x, -rotation.y, -rotation.z, rotation.w), center - position) / size) - 1.0\n        ) * min(min(size.x, size.y), size.z);\n    }\n\n    float cubeSD(vec3 position, vec4 rotation, vec3 size, vec3 center) {\n        vec3 d = abs(quaternionTransform(vec4(-rotation.x, -rotation.y, -rotation.z, rotation.w), center - position)) - size;\n        return min(max(d.x, max(d.y, d.z)), 0.0) + length(max(d, 0.0));\n    }\n\n    float cylinderSD(vec3 position, vec4 rotation, vec3 size, vec3 center) {\n        vec3 t = quaternionTransform(vec4(-rotation.x, -rotation.y, -rotation.z, rotation.w), center - position);\n\n        vec2 d = abs(vec2(length(t.xz), t.y)) - size.xy;\n        return min(max(d.x, d.y), 0.0) + length(max(d, 0.0));\n    }\n\n    float infiniteConeSD(vec3 position, vec4 rotation, vec3 size, vec3 center) {\n        vec3 t = quaternionTransform(vec4(-rotation.x, -rotation.y, -rotation.z, rotation.w), center - position);\n\n        float q = length(t.xy);\n        return dot(size.xy, vec2(q, t.z));\n    }\n\n    float getSignedDistance(vec3 center, int type, vec3 position, vec4 rotation, vec3 scale) {\n        if (type == 1) {\n            vec3 normal = quaternionTransform(rotation, vec3(0.0, 1.0, 0.0));\n            vec4 plane = computePlane(normal, position);\n            return planeSD(plane, center);\n        } else if (type == 2) {\n            return sphereSD(position, rotation, scale * 0.5, center);\n        } else if (type == 3) {\n            return cubeSD(position, rotation, scale * 0.5, center);\n        } else if (type == 4) {\n            return cylinderSD(position, rotation, scale * 0.5, center);\n        } else if (type == 5) {\n            return infiniteConeSD(position, rotation, scale * 0.5, center);\n        } else {\n            return 0.1;\n        }\n    }\n\n    #if __VERSION__ != 300\n        // 8-bit\n        int bitwiseAnd(int a, int b) {\n            int d = 128;\n            int result = 0;\n            for (int i = 0; i < 8; ++i) {\n                if (d <= 0) break;\n                if (a >= d && b >= d) result += d;\n                if (a >= d) a -= d;\n                if (b >= d) b -= d;\n                d /= 2;\n            }\n            return result;\n        }\n\n        bool hasBit(int mask, int bit) {\n            return bitwiseAnd(mask, bit) == 0;\n        }\n    #else\n        bool hasBit(int mask, int bit) {\n            return (mask & bit) == 0;\n        }\n    #endif\n\n    // flag is a bit-flag for clip-objects to ignore (note, object ids start at 1 not 0)\n    bool clipTest(vec4 sphere, int flag) {\n        for (int i = 0; i < dClipObjectCount; ++i) {\n            if (flag == 0 || hasBit(flag, i + 1)) {\n                // TODO take sphere radius into account?\n                if (getSignedDistance(sphere.xyz, uClipObjectType[i], uClipObjectPosition[i], uClipObjectRotation[i], uClipObjectScale[i]) <= 0.0)\n                    return true;\n            }\n        }\n        return false;\n    }\n#endif\n");
//# sourceMappingURL=common-clip.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/common-frag-params.glsl.js
/* harmony default export */ var common_frag_params_glsl = ("\nuniform int uObjectId;\nuniform int uInstanceCount;\nuniform int uGroupCount;\n\n#if dClipObjectCount != 0\n    uniform int uClipObjectType[dClipObjectCount];\n    uniform vec3 uClipObjectPosition[dClipObjectCount];\n    uniform vec4 uClipObjectRotation[dClipObjectCount];\n    uniform vec3 uClipObjectScale[dClipObjectCount];\n\n    #if defined(dClipping)\n        #if __VERSION__ != 300\n            varying float vClipping;\n        #else\n            flat in float vClipping;\n        #endif\n    #endif\n#endif\n\nuniform vec3 uHighlightColor;\nuniform vec3 uSelectColor;\n#if __VERSION__ != 300\n    varying float vMarker;\n#else\n    flat in float vMarker;\n#endif\n\nvarying vec3 vModelPosition;\nvarying vec3 vViewPosition;\n\nuniform vec2 uViewOffset;\n\nuniform float uFogNear;\nuniform float uFogFar;\nuniform vec3 uFogColor;\n\nuniform float uAlpha;\nuniform float uPickingAlphaThreshold;\nuniform int uTransparentBackground;\n\nuniform float uInteriorDarkening;\nuniform int uInteriorColorFlag;\nuniform vec3 uInteriorColor;\nbool interior;\n");
//# sourceMappingURL=common-frag-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/common-vert-params.glsl.js
/* harmony default export */ var common_vert_params_glsl = ("\nuniform mat4 uProjection, uModel, uView;\nuniform vec3 uCameraPosition;\n\nuniform int uObjectId;\nuniform int uInstanceCount;\nuniform int uGroupCount;\nuniform vec4 uInvariantBoundingSphere;\n\n#if dClipObjectCount != 0\n    uniform int uClipObjectType[dClipObjectCount];\n    uniform vec3 uClipObjectPosition[dClipObjectCount];\n    uniform vec4 uClipObjectRotation[dClipObjectCount];\n    uniform vec3 uClipObjectScale[dClipObjectCount];\n\n    #if defined(dClipping)\n        uniform vec2 uClippingTexDim;\n        uniform sampler2D tClipping;\n        #if __VERSION__ != 300\n            varying float vClipping;\n        #else\n            flat out float vClipping;\n        #endif\n    #endif\n#endif\n\nuniform vec2 uMarkerTexDim;\nuniform sampler2D tMarker;\n#if __VERSION__ != 300\n    varying float vMarker;\n#else\n    flat out float vMarker;\n#endif\n\nvarying vec3 vModelPosition;\nvarying vec3 vViewPosition;\n");
//# sourceMappingURL=common-vert-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/common.glsl.js
/* harmony default export */ var common_glsl = ("\n// TODO find a better place for these convenience defines\n\n#if defined(dRenderVariant_pickObject) || defined(dRenderVariant_pickInstance) || defined(dRenderVariant_pickGroup)\n    #define dRenderVariant_pick\n#endif\n\n#if defined(dColorType_instance) || defined(dColorType_group) || defined(dColorType_groupInstance)\n    #define dColorType_texture\n#endif\n\n#if defined(dColorType_attribute) || defined(dColorType_texture)\n    #define dColorType_varying\n#endif\n\n//\n\n#define PI 3.14159265\n#define RECIPROCAL_PI 0.31830988618\n#define EPSILON 1e-6\n\n#define saturate(a) clamp(a, 0.0, 1.0)\n\nfloat intDiv(const in float a, const in float b) { return float(int(a) / int(b)); }\nfloat intMod(const in float a, const in float b) { return a - b * float(int(a) / int(b)); }\n\nfloat pow2(const in float x) { return x*x; }\n\nconst float maxFloat = 10000.0; // NOTE constant also set in TypeScript\nconst float floatLogFactor = 9.210440366976517; // log(maxFloat + 1.0);\nfloat encodeFloatLog(const in float value) { return log(value + 1.0) / floatLogFactor; }\nfloat decodeFloatLog(const in float value) { return exp(value * floatLogFactor) - 1.0; }\n\nvec3 encodeFloatRGB(in float value) {\n    value = clamp(value, 0.0, 16777216.0 - 1.0) + 1.0;\n    vec3 c = vec3(0.0);\n    c.b = mod(value, 256.0);\n    value = floor(value / 256.0);\n    c.g = mod(value, 256.0);\n    value = floor(value / 256.0);\n    c.r = mod(value, 256.0);\n    return c / 255.0;\n}\nfloat decodeFloatRGB(const in vec3 rgb) {\n    return (rgb.r * 256.0 * 256.0 * 255.0 + rgb.g * 256.0 * 255.0 + rgb.b * 255.0) - 1.0;\n}\n\nconst float PackUpscale = 256.0 / 255.0; // fraction -> 0..1 (including 1)\nconst float UnpackDownscale = 255.0 / 256.0; // 0..1 -> fraction (excluding 1)\nconst vec3 PackFactors = vec3(256.0 * 256.0 * 256.0, 256.0 * 256.0,  256.0);\nconst vec4 UnpackFactors = UnpackDownscale / vec4(PackFactors, 1.0);\nconst float ShiftRight8 = 1.0 / 256.0;\n\nvec4 packDepthToRGBA(const in float v) {\n\tvec4 r = vec4(fract(v * PackFactors), v);\n\tr.yzw -= r.xyz * ShiftRight8; // tidy overflow\n\treturn r * PackUpscale;\n}\nfloat unpackRGBAToDepth(const in vec4 v) {\n\treturn dot(v, UnpackFactors);\n}\n\n#if __VERSION__ != 300\n    // transpose\n\n    float transpose(const in float m) {\n        return m;\n    }\n\n    mat2 transpose2(const in mat2 m) {\n        return mat2(\n            m[0][0], m[1][0],\n            m[0][1], m[1][1]\n        );\n    }\n\n    mat3 transpose3(const in mat3 m) {\n        return mat3(\n            m[0][0], m[1][0], m[2][0],\n            m[0][1], m[1][1], m[2][1],\n            m[0][2], m[1][2], m[2][2]\n        );\n    }\n\n    mat4 transpose4(const in mat4 m) {\n        return mat4(\n            m[0][0], m[1][0], m[2][0], m[3][0],\n            m[0][1], m[1][1], m[2][1], m[3][1],\n            m[0][2], m[1][2], m[2][2], m[3][2],\n            m[0][3], m[1][3], m[2][3], m[3][3]\n        );\n    }\n\n    // inverse\n\n    float inverse(const in float m) {\n        return 1.0 / m;\n    }\n\n    mat2 inverse2(const in mat2 m) {\n        return mat2(m[1][1],-m[0][1],\n                -m[1][0], m[0][0]) / (m[0][0]*m[1][1] - m[0][1]*m[1][0]);\n    }\n\n    mat3 inverse3(const in mat3 m) {\n        float a00 = m[0][0], a01 = m[0][1], a02 = m[0][2];\n        float a10 = m[1][0], a11 = m[1][1], a12 = m[1][2];\n        float a20 = m[2][0], a21 = m[2][1], a22 = m[2][2];\n\n        float b01 = a22 * a11 - a12 * a21;\n        float b11 = -a22 * a10 + a12 * a20;\n        float b21 = a21 * a10 - a11 * a20;\n\n        float det = a00 * b01 + a01 * b11 + a02 * b21;\n\n        return mat3(b01, (-a22 * a01 + a02 * a21), (a12 * a01 - a02 * a11),\n                    b11, (a22 * a00 - a02 * a20), (-a12 * a00 + a02 * a10),\n                    b21, (-a21 * a00 + a01 * a20), (a11 * a00 - a01 * a10)) / det;\n    }\n\n    mat4 inverse4(const in mat4 m) {\n        float\n            a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],\n            a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],\n            a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],\n            a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],\n\n            b00 = a00 * a11 - a01 * a10,\n            b01 = a00 * a12 - a02 * a10,\n            b02 = a00 * a13 - a03 * a10,\n            b03 = a01 * a12 - a02 * a11,\n            b04 = a01 * a13 - a03 * a11,\n            b05 = a02 * a13 - a03 * a12,\n            b06 = a20 * a31 - a21 * a30,\n            b07 = a20 * a32 - a22 * a30,\n            b08 = a20 * a33 - a23 * a30,\n            b09 = a21 * a32 - a22 * a31,\n            b10 = a21 * a33 - a23 * a31,\n            b11 = a22 * a33 - a23 * a32,\n\n            det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;\n\n        return mat4(\n            a11 * b11 - a12 * b10 + a13 * b09,\n            a02 * b10 - a01 * b11 - a03 * b09,\n            a31 * b05 - a32 * b04 + a33 * b03,\n            a22 * b04 - a21 * b05 - a23 * b03,\n            a12 * b08 - a10 * b11 - a13 * b07,\n            a00 * b11 - a02 * b08 + a03 * b07,\n            a32 * b02 - a30 * b05 - a33 * b01,\n            a20 * b05 - a22 * b02 + a23 * b01,\n            a10 * b10 - a11 * b08 + a13 * b06,\n            a01 * b08 - a00 * b10 - a03 * b06,\n            a30 * b04 - a31 * b02 + a33 * b00,\n            a21 * b02 - a20 * b04 - a23 * b00,\n            a11 * b07 - a10 * b09 - a12 * b06,\n            a00 * b09 - a01 * b07 + a02 * b06,\n            a31 * b01 - a30 * b03 - a32 * b00,\n            a20 * b03 - a21 * b01 + a22 * b00) / det;\n    }\n#else\n    #define transpose2(m) transpose(m)\n    #define transpose3(m) transpose(m)\n    #define transpose4(m) transpose(m)\n\n    #define inverse2(m) inverse(m)\n    #define inverse3(m) inverse(m)\n    #define inverse4(m) inverse(m)\n#endif\n");
//# sourceMappingURL=common.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/light-frag-params.glsl.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * adapted from three.js (https://github.com/mrdoob/three.js/)
 * which under the MIT License, Copyright © 2010-2019 three.js authors
 */
/* harmony default export */ var light_frag_params_glsl = ("\nuniform float uLightIntensity;\nuniform float uAmbientIntensity;\nuniform float uReflectivity;\nuniform float uMetalness;\nuniform float uRoughness;\n\nstruct PhysicalMaterial {\n\tvec3 diffuseColor;\n\tfloat specularRoughness;\n\tvec3 specularColor;\n};\n\nstruct IncidentLight {\n\tvec3 color;\n\tvec3 direction;\n};\n\nstruct ReflectedLight {\n\tvec3 directDiffuse;\n\tvec3 directSpecular;\n\tvec3 indirectDiffuse;\n};\n\nstruct GeometricContext {\n\tvec3 position;\n\tvec3 normal;\n\tvec3 viewDir;\n};\n\nvec3 F_Schlick(const in vec3 specularColor, const in float dotLH) {\n\t// Original approximation by Christophe Schlick '94\n\t// float fresnel = pow( 1.0 - dotLH, 5.0 );\n\t// Optimized variant (presented by Epic at SIGGRAPH '13)\n\t// https://cdn2.unrealengine.com/Resources/files/2013SiggraphPresentationsNotes-26915738.pdf\n\tfloat fresnel = exp2((-5.55473 * dotLH - 6.98316) * dotLH);\n\treturn (1.0 - specularColor) * fresnel + specularColor;\n}\n\n// Moving Frostbite to Physically Based Rendering 3.0 - page 12, listing 2\n// https://seblagarde.files.wordpress.com/2015/07/course_notes_moving_frostbite_to_pbr_v32.pdf\nfloat G_GGX_SmithCorrelated(const in float alpha, const in float dotNL, const in float dotNV) {\n\tfloat a2 = pow2(alpha);\n\t// dotNL and dotNV are explicitly swapped. This is not a mistake.\n\tfloat gv = dotNL * sqrt(a2 + (1.0 - a2) * pow2(dotNV));\n\tfloat gl = dotNV * sqrt(a2 + (1.0 - a2) * pow2(dotNL));\n\treturn 0.5 / max(gv + gl, EPSILON);\n}\n\n// Microfacet Models for Refraction through Rough Surfaces - equation (33)\n// http://graphicrants.blogspot.com/2013/08/specular-brdf-reference.html\n// alpha is \"roughness squared\" in Disney\u2019s reparameterization\nfloat D_GGX(const in float alpha, const in float dotNH) {\n\tfloat a2 = pow2(alpha);\n\tfloat denom = pow2(dotNH) * (a2 - 1.0) + 1.0; // avoid alpha = 0 with dotNH = 1\n\treturn RECIPROCAL_PI * a2 / pow2(denom);\n}\n\nvec3 BRDF_Diffuse_Lambert(const in vec3 diffuseColor) {\n\treturn RECIPROCAL_PI * diffuseColor;\n}\n\n// GGX Distribution, Schlick Fresnel, GGX-Smith Visibility\nvec3 BRDF_Specular_GGX(const in IncidentLight incidentLight, const in GeometricContext geometry, const in vec3 specularColor, const in float roughness) {\n\tfloat alpha = pow2(roughness); // UE4's roughness\n\tvec3 halfDir = normalize(incidentLight.direction + geometry.viewDir);\n\n\tfloat dotNL = saturate(dot(geometry.normal, incidentLight.direction));\n\tfloat dotNV = saturate(dot(geometry.normal, geometry.viewDir));\n\tfloat dotNH = saturate(dot(geometry.normal, halfDir));\n\tfloat dotLH = saturate(dot(incidentLight.direction, halfDir));\n\n\tvec3 F = F_Schlick(specularColor, dotLH);\n\tfloat G = G_GGX_SmithCorrelated(alpha, dotNL, dotNV);\n\tfloat D = D_GGX(alpha, dotNH);\n\treturn F * (G * D);\n}\n\n// ref: https://www.unrealengine.com/blog/physically-based-shading-on-mobile - environmentBRDF for GGX on mobile\nvec3 BRDF_Specular_GGX_Environment(const in GeometricContext geometry, const in vec3 specularColor, const in float roughness) {\n\tfloat dotNV = saturate(dot(geometry.normal, geometry.viewDir));\n\tconst vec4 c0 = vec4(-1, -0.0275, -0.572, 0.022);\n\tconst vec4 c1 = vec4(1, 0.0425, 1.04, -0.04);\n\tvec4 r = roughness * c0 + c1;\n\tfloat a004 = min(r.x * r.x, exp2(-9.28 * dotNV)) * r.x + r.y;\n\tvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\n\treturn specularColor * AB.x + AB.y;\n}\n\nvoid RE_Direct_Physical(const in IncidentLight directLight, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\tfloat dotNL = saturate(dot(geometry.normal, directLight.direction));\n    vec3 irradiance = dotNL * directLight.color;\n\tirradiance *= PI; // punctual light\n\n\treflectedLight.directSpecular += irradiance * BRDF_Specular_GGX(directLight, geometry, material.specularColor, material.specularRoughness);\n\treflectedLight.directDiffuse += irradiance * BRDF_Diffuse_Lambert(material.diffuseColor);\n}\n\nvoid RE_IndirectDiffuse_Physical(const in vec3 irradiance, const in GeometricContext geometry, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) {\n\treflectedLight.indirectDiffuse += irradiance * BRDF_Diffuse_Lambert(material.diffuseColor);\n}\n");
//# sourceMappingURL=light-frag-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/matrix-scale.glsl.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var matrix_scale_glsl = ("\nfloat matrixScale(in mat4 m){\n    vec4 r = m[0];\n    return sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2]);\n}\n");
//# sourceMappingURL=matrix-scale.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/normal-frag-params.glsl.js
/* harmony default export */ var normal_frag_params_glsl = ("\nvarying vec3 vNormal;\n");
//# sourceMappingURL=normal-frag-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/read-from-texture.glsl.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var read_from_texture_glsl = ("\nvec4 readFromTexture (const in sampler2D tex, const in float i, const in vec2 dim) {\n    float x = intMod(i, dim.x);\n    float y = floor(intDiv(i, dim.x));\n    vec2 uv = (vec2(x, y) + 0.5) / dim;\n    return texture2D(tex, uv);\n}\n");
//# sourceMappingURL=read-from-texture.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/size-vert-params.glsl.js
/* harmony default export */ var size_vert_params_glsl = ("\n#if defined(dSizeType_uniform)\n    uniform float uSize;\n#elif defined(dSizeType_attribute)\n    attribute float aSize;\n#elif defined(dSizeType_instance) || defined(dSizeType_group) || defined(dSizeType_groupInstance)\n    uniform vec2 uSizeTexDim;\n    uniform sampler2D tSize;\n#endif\n\nuniform float uSizeFactor;\n");
//# sourceMappingURL=size-vert-params.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/chunks/texture3d-from-2d-nearest.glsl.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */
/* harmony default export */ var texture3d_from_2d_nearest_glsl = ("\nvec4 texture3dFrom2dNearest(sampler2D tex, vec3 pos, vec3 gridDim, vec2 texDim) {\n    float zSlice = floor(pos.z * gridDim.z + 0.5); // round to nearest z-slice\n    float column = intMod(zSlice * gridDim.x, texDim.x) / gridDim.x;\n    float row = floor(intDiv(zSlice * gridDim.x, texDim.x));\n    vec2 coord = (vec2(column * gridDim.x, row * gridDim.y) + (pos.xy * gridDim.xy)) / texDim;\n    return texture2D(tex, coord);\n}\n");
//# sourceMappingURL=texture3d-from-2d-nearest.glsl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/points.vert.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var points_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_vert_params\n#include color_vert_params\n#include size_vert_params\n#include common_clip\n\nuniform float uPixelRatio;\nuniform float uViewportHeight;\n\nattribute vec3 aPosition;\nattribute mat4 aTransform;\nattribute float aInstance;\nattribute float aGroup;\n\nvoid main(){\n    #include assign_group\n    #include assign_color_varying\n    #include assign_marker_varying\n    #include assign_clipping_varying\n    #include assign_position\n    #include assign_size\n\n    #ifdef dPointSizeAttenuation\n        gl_PointSize = size * uPixelRatio * ((uViewportHeight / 2.0) / -mvPosition.z) * 5.0;\n    #else\n        gl_PointSize = size * uPixelRatio;\n    #endif\n\n    gl_Position = uProjection * mvPosition;\n\n    #include clip_instance\n}\n");
//# sourceMappingURL=points.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/points.frag.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var points_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_frag_params\n#include color_frag_params\n#include common_clip\n\n#ifdef dPointFilledCircle\n    uniform float uPointEdgeBleach;\n#endif\n\nconst vec2 center = vec2(0.5);\nconst float radius = 0.5;\n\nvoid main(){\n    #include clip_pixel\n    #include assign_material_color\n\n    #if defined(dRenderVariant_pick)\n        #include check_picking_alpha\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_depth)\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_color)\n        gl_FragColor = material;\n\n        #ifdef dPointFilledCircle\n            float dist = distance(gl_PointCoord, center);\n            float alpha = 1.0 - smoothstep(radius - uPointEdgeBleach, radius, dist);\n            if (alpha < 0.0001) discard;\n            gl_FragColor.a *= alpha;\n        #endif\n\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=points.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/spheres.vert.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var spheres_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_vert_params\n#include color_vert_params\n#include size_vert_params\n#include common_clip\n\nuniform mat4 uModelView;\nuniform mat4 uInvProjection;\n\nattribute vec3 aPosition;\nattribute vec2 aMapping;\nattribute mat4 aTransform;\nattribute float aInstance;\nattribute float aGroup;\n\nvarying float vRadius;\nvarying float vRadiusSq;\nvarying vec3 vPoint;\nvarying vec3 vPointViewPosition;\n\n#include matrix_scale\n\nconst mat4 D = mat4(\n    1.0, 0.0, 0.0, 0.0,\n    0.0, 1.0, 0.0, 0.0,\n    0.0, 0.0, 1.0, 0.0,\n    0.0, 0.0, 0.0, -1.0\n);\n\n/**\n * Compute point size and center using the technique described in:\n * \"GPU-Based Ray-Casting of Quadratic Surfaces\" http://dl.acm.org/citation.cfm?id=2386396\n * by Christian Sigg, Tim Weyrich, Mario Botsch, Markus Gross.\n */\nvoid quadraticProjection(const in float radius, const in vec3 position){\n    vec2 xbc, ybc;\n\n    mat4 T = mat4(\n        radius, 0.0, 0.0, 0.0,\n        0.0, radius, 0.0, 0.0,\n        0.0, 0.0, radius, 0.0,\n        position.x, position.y, position.z, 1.0\n    );\n\n    mat4 R = transpose4(uProjection * uModelView * aTransform * T);\n    float A = dot(R[3], D * R[3]);\n    float B = -2.0 * dot(R[0], D * R[3]);\n    float C = dot(R[0], D * R[0]);\n    xbc[0] = (-B - sqrt(B * B - 4.0 * A * C)) / (2.0 * A);\n    xbc[1] = (-B + sqrt(B * B - 4.0 * A * C)) / (2.0 * A);\n    float sx = abs(xbc[0] - xbc[1]) * 0.5;\n\n    A = dot(R[3], D * R[3]);\n    B = -2.0 * dot(R[1], D * R[3]);\n    C = dot(R[1], D * R[1]);\n    ybc[0] = (-B - sqrt(B * B - 4.0 * A * C)) / (2.0 * A);\n    ybc[1] = (-B + sqrt(B * B - 4.0 * A * C)) / (2.0 * A);\n    float sy = abs(ybc[0] - ybc[1]) * 0.5;\n\n    gl_Position.xy = vec2(0.5 * (xbc.x + xbc.y), 0.5 * (ybc.x + ybc.y));\n    gl_Position.xy -= aMapping * vec2(sx, sy);\n    gl_Position.xy *= gl_Position.w;\n}\n\n\nvoid main(void){\n    #include assign_group\n    #include assign_color_varying\n    #include assign_marker_varying\n    #include assign_clipping_varying\n    #include assign_size\n\n    vRadius = size * matrixScale(uModelView);\n\n    vec4 position4 = vec4(aPosition, 1.0);\n    vec4 mvPosition = uModelView * aTransform * position4;\n    mvPosition.z -= vRadius; // avoid clipping, added again in fragment shader\n\n    gl_Position = uProjection * vec4(mvPosition.xyz, 1.0);\n    quadraticProjection(size, aPosition);\n\n    vRadiusSq = vRadius * vRadius;\n    vec4 vPoint4 = uInvProjection * gl_Position;\n    vPoint = vPoint4.xyz / vPoint4.w;\n    vPointViewPosition = -mvPosition.xyz / mvPosition.w;\n\n    vModelPosition = (uModel * aTransform * position4).xyz; // for clipping in frag shader\n\n    #include clip_instance\n}\n");
//# sourceMappingURL=spheres.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/spheres.frag.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var spheres_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_frag_params\n#include color_frag_params\n#include light_frag_params\n#include common_clip\n\nuniform mat4 uProjection;\n\nuniform float uClipNear;\nuniform float uIsOrtho;\n\nvarying float vRadius;\nvarying float vRadiusSq;\nvarying vec3 vPoint;\nvarying vec3 vPointViewPosition;\n\nvec3 cameraPos;\nvec3 cameraNormal;\n\n// Calculate depth based on the given camera position.\nfloat calcDepth(const in vec3 cameraPos){\n    vec2 clipZW = cameraPos.z * uProjection[2].zw + uProjection[3].zw;\n    return 0.5 + 0.5 * clipZW.x / clipZW.y;\n}\n\nfloat calcClip(const in vec3 cameraPos) {\n    return dot(vec4(cameraPos, 1.0), vec4(0.0, 0.0, 1.0, uClipNear - 0.5));\n}\n\nbool Impostor(out vec3 cameraPos, out vec3 cameraNormal){\n    vec3 cameraSpherePos = -vPointViewPosition;\n    cameraSpherePos.z += vRadius;\n\n    vec3 rayOrigin = mix(vec3(0.0, 0.0, 0.0), vPoint, uIsOrtho);\n    vec3 rayDirection = mix(normalize(vPoint), vec3(0.0, 0.0, 1.0), uIsOrtho);\n    vec3 cameraSphereDir = mix(cameraSpherePos, rayOrigin - cameraSpherePos, uIsOrtho);\n\n    float B = dot(rayDirection, cameraSphereDir);\n    float det = B * B + vRadiusSq - dot(cameraSphereDir, cameraSphereDir);\n\n    if (det < 0.0){\n        discard;\n        return false;\n    }\n\n    float sqrtDet = sqrt(det);\n    float posT = mix(B + sqrtDet, B + sqrtDet, uIsOrtho);\n    float negT = mix(B - sqrtDet, sqrtDet - B, uIsOrtho);\n\n    cameraPos = rayDirection * negT + rayOrigin;\n\n\n    if (calcDepth(cameraPos) <= 0.0) {\n        cameraPos = rayDirection * posT + rayOrigin;\n        interior = true;\n    } else {\n        interior = false;\n    }\n\n    cameraNormal = normalize(cameraPos - cameraSpherePos);\n    cameraNormal *= float(!interior) * 2.0 - 1.0;\n\n    return !interior;\n}\n\nvoid main(void){\n    #include clip_pixel\n\n    bool flag = Impostor(cameraPos, cameraNormal);\n    #ifndef dDoubleSided\n        if (interior)\n            discard;\n    #endif\n\n    // FIXME not compatible with custom clipping plane\n    // Set the depth based on the new cameraPos.\n    gl_FragDepthEXT = calcDepth(cameraPos);\n    if (!flag && gl_FragDepthEXT >= 0.0) {\n        gl_FragDepthEXT = 0.0 + (0.0000001 / vRadius);\n    }\n\n    // bugfix (mac only?)\n    if (gl_FragDepthEXT < 0.0)\n        discard;\n    if (gl_FragDepthEXT > 1.0)\n        discard;\n\n    #include assign_material_color\n\n    #if defined(dRenderVariant_pick)\n        #include check_picking_alpha\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_depth)\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_color)\n        #ifdef dIgnoreLight\n            gl_FragColor = material;\n        #else\n            vec3 normal = -cameraNormal;\n            vec3 vViewPosition = cameraPos;\n            #include apply_light_color\n        #endif\n\n        #include apply_interior_color\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=spheres.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/text.vert.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var text_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_vert_params\n#include color_vert_params\n#include size_vert_params\n#include common_clip\n\nuniform mat4 uModelView;\n\nattribute vec3 aPosition;\nattribute vec2 aMapping;\nattribute float aDepth;\nattribute vec2 aTexCoord;\nattribute mat4 aTransform;\nattribute float aInstance;\nattribute float aGroup;\n\nuniform float uOffsetX;\nuniform float uOffsetY;\nuniform float uOffsetZ;\n\n// uniform bool ortho;\nuniform float uPixelRatio;\nuniform float uViewportHeight;\n\nvarying vec2 vTexCoord;\n\n#include matrix_scale\n\nvoid main(void){\n    #include assign_group\n    #include assign_color_varying\n    #include assign_marker_varying\n    #include assign_clipping_varying\n    #include assign_size\n\n    vTexCoord = aTexCoord;\n\n    float scale = matrixScale(uModelView);\n\n    float offsetX = uOffsetX * scale;\n    float offsetY = uOffsetY * scale;\n    float offsetZ = (uOffsetZ + aDepth * 0.95) * scale;\n\n    vec4 position4 = vec4(aPosition, 1.0);\n    vec4 mvPosition = uModelView * aTransform * position4;\n\n    vModelPosition = (uModel * aTransform * position4).xyz; // for clipping in frag shader\n\n    // TODO\n    // #ifdef FIXED_SIZE\n    //     if (ortho) {\n    //         scale /= pixelRatio * ((uViewportHeight / 2.0) / -uCameraPosition.z) * 0.1;\n    //     } else {\n    //         scale /= pixelRatio * ((uViewportHeight / 2.0) / -mvPosition.z) * 0.1;\n    //     }\n    // #endif\n\n    vec4 mvCorner = vec4(mvPosition.xyz, 1.0);\n\n    if (vTexCoord.x == 10.0) { // indicates background plane\n        // move a bit to the back, taking distance to camera into account to avoid z-fighting\n        offsetZ -= 0.001 * distance(uCameraPosition, (uProjection * mvCorner).xyz);\n    }\n\n    mvCorner.xy += aMapping * size * scale;\n    mvCorner.x += offsetX;\n    mvCorner.y += offsetY;\n\n    // TODO\n    // if(ortho){\n    //     mvCorner.xyz += normalize(-uCameraPosition) * offsetZ;\n    // } else {\n    //     mvCorner.xyz += normalize(-mvCorner.xyz) * offsetZ;\n    // }\n    mvCorner.xyz += normalize(-mvCorner.xyz) * offsetZ;\n\n    gl_Position = uProjection * mvCorner;\n\n    vViewPosition = -mvCorner.xyz;\n\n    #include clip_instance\n}\n");
//# sourceMappingURL=text.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/text.frag.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var text_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_frag_params\n#include color_frag_params\n#include common_clip\n\nuniform sampler2D tFont;\n\nuniform vec3 uBorderColor;\nuniform float uBorderWidth;\nuniform vec3 uBackgroundColor;\nuniform float uBackgroundOpacity;\n\nvarying vec2 vTexCoord;\n\nconst float smoothness = 32.0;\nconst float gamma = 2.2;\n\nvoid main2(){\n    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n}\n\nvoid main(){\n    #include clip_pixel\n    #include assign_material_color\n\n    if (vTexCoord.x > 1.0) {\n        gl_FragColor = vec4(uBackgroundColor, uBackgroundOpacity);\n    } else {\n        // retrieve signed distance\n        float sdf = texture2D(tFont, vTexCoord).a + uBorderWidth;\n\n        // perform adaptive anti-aliasing of the edges\n        float w = clamp(smoothness * (abs(dFdx(vTexCoord.x)) + abs(dFdy(vTexCoord.y))), 0.0, 0.5);\n        float a = smoothstep(0.5 - w, 0.5 + w, sdf);\n\n        // gamma correction for linear attenuation\n        a = pow(a, 1.0 / gamma);\n\n        if (a < 0.5) discard;\n        material.a *= a;\n\n        // add border\n        float t = 0.5 + uBorderWidth;\n        if (uBorderWidth > 0.0 && sdf < t) {\n            material.xyz = mix(uBorderColor, material.xyz, smoothstep(t - w, t, sdf));\n        }\n\n        gl_FragColor = material;\n    }\n\n    #if defined(dRenderVariant_pick)\n        #include check_picking_alpha\n    #elif defined(dRenderVariant_depth)\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_color)\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=text.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/lines.vert.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * heavily based on code by WestLangley from https://github.com/WestLangley/three.js/blob/af28b2fb706ac109771ecad0a7447fad90ab3210/examples/js/lines/LineMaterial.js
 */
/* harmony default export */ var lines_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_vert_params\n#include color_vert_params\n#include size_vert_params\n#include common_clip\n\nuniform float uPixelRatio;\nuniform float uViewportHeight;\n\nattribute vec3 aPosition;\nattribute mat4 aTransform;\nattribute float aInstance;\nattribute float aGroup;\n\nattribute vec2 aMapping;\nattribute vec3 aStart;\nattribute vec3 aEnd;\n\nvoid trimSegment(const in vec4 start, inout vec4 end) {\n    // trim end segment so it terminates between the camera plane and the near plane\n    // conservative estimate of the near plane\n    float a = uProjection[2][2];  // 3nd entry in 3th column\n    float b = uProjection[3][2];  // 3nd entry in 4th column\n    float nearEstimate = -0.5 * b / a;\n    float alpha = (nearEstimate - start.z) / (end.z - start.z);\n    end.xyz = mix(start.xyz, end.xyz, alpha);\n}\n\nvoid main(){\n    #include assign_group\n    #include assign_color_varying\n    #include assign_marker_varying\n    #include assign_clipping_varying\n    #include assign_size\n\n    mat4 modelView = uView * uModel * aTransform;\n\n    // camera space\n    vec4 start = modelView * vec4(aStart, 1.0);\n    vec4 end = modelView * vec4(aEnd, 1.0);\n\n    // assign position\n    vec4 position4 = vec4((aMapping.y < 0.5) ? aStart : aEnd, 1.0);\n    vec4 mvPosition = modelView * position4;\n    vViewPosition = mvPosition.xyz;\n\n    vModelPosition = (uModel * aTransform * position4).xyz; // for clipping in frag shader\n\n    // special case for perspective projection, and segments that terminate either in, or behind, the camera plane\n    // clearly the gpu firmware has a way of addressing this issue when projecting into ndc space\n    // but we need to perform ndc-space calculations in the shader, so we must address this issue directly\n    // perhaps there is a more elegant solution -- WestLangley\n    bool perspective = (uProjection[2][3] == -1.0); // 4th entry in the 3rd column\n    if (perspective) {\n        if (start.z < 0.0 && end.z >= 0.0) {\n            trimSegment(start, end);\n        } else if (end.z < 0.0 && start.z >= 0.0) {\n            trimSegment(end, start);\n        }\n    }\n\n    // clip space\n    vec4 clipStart = uProjection * start;\n    vec4 clipEnd = uProjection * end;\n\n    // ndc space\n    vec2 ndcStart = clipStart.xy / clipStart.w;\n    vec2 ndcEnd = clipEnd.xy / clipEnd.w;\n\n    // direction\n    vec2 dir = ndcEnd - ndcStart;\n\n    // account for clip-space aspect ratio\n    dir.x *= uPixelRatio;\n    dir = normalize(dir);\n\n    // perpendicular to dir\n    vec2 offset = vec2(dir.y, - dir.x);\n\n    // undo aspect ratio adjustment\n    dir.x /= uPixelRatio;\n    offset.x /= uPixelRatio;\n\n    // sign flip\n    if (aMapping.x < 0.0) offset *= -1.0;\n\n    // calculate linewidth\n    float linewidth;\n    #ifdef dLineSizeAttenuation\n        linewidth = size * uPixelRatio * ((uViewportHeight / 2.0) / -start.z) * 5.0;\n    #else\n        linewidth = size * uPixelRatio;\n    #endif\n\n    // adjust for linewidth\n    offset *= linewidth;\n\n    // adjust for clip-space to screen-space conversion\n    offset /= uViewportHeight;\n\n    // select end\n    vec4 clip = (aMapping.y < 0.5) ? clipStart : clipEnd;\n\n    // back to clip space\n    offset *= clip.w;\n    clip.xy += offset;\n    gl_Position = clip;\n\n    #include clip_instance\n}\n");
//# sourceMappingURL=lines.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/lines.frag.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var lines_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_frag_params\n#include color_frag_params\n#include common_clip\n\nvoid main(){\n    #include clip_pixel\n    #include assign_material_color\n\n    #if defined(dRenderVariant_pick)\n        #include check_picking_alpha\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_depth)\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_color)\n        gl_FragColor = material;\n\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=lines.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/mesh.vert.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var mesh_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_vert_params\n#include color_vert_params\n#include common_clip\n\n#ifdef dGeoTexture\n    uniform vec2 uGeoTexDim;\n    uniform sampler2D tPositionGroup;\n#else\n    attribute vec3 aPosition;\n#endif\nattribute mat4 aTransform;\nattribute float aInstance;\nattribute float aGroup;\n\n#ifdef dGeoTexture\n    uniform sampler2D tNormal;\n#else\n    attribute vec3 aNormal;\n#endif\nvarying vec3 vNormal;\n\nvoid main(){\n    #include assign_group\n    #include assign_color_varying\n    #include assign_marker_varying\n    #include assign_clipping_varying\n    #include assign_position\n    #include clip_instance\n\n    #ifdef dGeoTexture\n        vec3 normal = readFromTexture(tNormal, aGroup, uGeoTexDim).xyz;\n    #else\n        vec3 normal = aNormal;\n    #endif\n    mat3 normalMatrix = transpose3(inverse3(mat3(modelView)));\n    vec3 transformedNormal = normalize(normalMatrix * normalize(normal));\n    #if defined(dFlipSided) && !defined(dDoubleSided) // TODO checking dDoubleSided should not be required, ASR\n        transformedNormal = -transformedNormal;\n    #endif\n    vNormal = transformedNormal;\n}\n");
//# sourceMappingURL=mesh.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/mesh.frag.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var mesh_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_frag_params\n#include color_frag_params\n#include light_frag_params\n#include normal_frag_params\n#include common_clip\n\nvoid main() {\n    #include clip_pixel\n\n    // Workaround for buggy gl_FrontFacing (e.g. on some integrated Intel GPUs)\n    #if defined(enabledStandardDerivatives)\n        vec3 fdx = dFdx(vViewPosition);\n        vec3 fdy = dFdy(vViewPosition);\n        vec3 faceNormal = normalize(cross(fdx,fdy));\n        bool frontFacing = dot(vNormal, faceNormal) > 0.0;\n    #else\n        bool frontFacing = dot(vNormal, vViewPosition) < 0.0;\n    #endif\n\n    #if defined(dFlipSided)\n        interior = frontFacing;\n    #else\n        interior = !frontFacing;\n    #endif\n\n    #include assign_material_color\n\n    #if defined(dRenderVariant_pick)\n        #include check_picking_alpha\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_depth)\n        gl_FragColor = material;\n    #elif defined(dRenderVariant_color)\n        #ifdef dIgnoreLight\n            gl_FragColor = material;\n        #else\n            #if defined(dFlatShaded) && defined(enabledStandardDerivatives)\n                vec3 normal = -faceNormal;\n            #else\n                vec3 normal = -normalize(vNormal);\n                #ifdef dDoubleSided\n                    normal = normal * (float(frontFacing) * 2.0 - 1.0);\n                #endif\n            #endif\n            #include apply_light_color\n        #endif\n\n        #include apply_interior_color\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=mesh.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/direct-volume.vert.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */
/* harmony default export */ var direct_volume_vert = ("\nprecision highp float;\n\nattribute vec3 aPosition;\nattribute mat4 aTransform;\nattribute float aInstance;\n\nvarying vec3 unitCoord;\nvarying vec3 origPos;\nvarying float instance;\n\nuniform vec3 uBboxSize;\nuniform vec3 uBboxMin;\nuniform vec3 uBboxMax;\nuniform vec3 uGridDim;\nuniform mat4 uTransform;\n\nuniform mat4 uModelView;\nuniform mat4 uProjection;\n\nvoid main() {\n    unitCoord = aPosition + vec3(0.5);\n    vec4 mvPosition = uModelView * uTransform * vec4(unitCoord * uGridDim, 1.0);\n    origPos = unitCoord * uBboxSize + uBboxMin;\n    instance = aInstance;\n    gl_Position = uProjection * mvPosition;\n\n    // clamp z position to clip space\n    if(gl_Position.z > gl_Position.w) {\n        gl_Position.z = gl_Position.w - 0.0001;\n    } else if(gl_Position.z < -gl_Position.w) {\n        gl_Position.z = -gl_Position.w + 0.0001;\n    }\n}\n");
//# sourceMappingURL=direct-volume.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/direct-volume.frag.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */
/* harmony default export */ var direct_volume_frag = ("\nprecision highp float;\n\nvarying vec3 unitCoord;\nvarying vec3 origPos;\nvarying float instance;\n\nuniform mat4 uInvView;\nuniform float uIsoValue;\nuniform vec3 uGridDim;\nuniform sampler2D tTransferTex;\n\nuniform int uObjectId;\nuniform int uInstanceCount;\nuniform int uGroupCount;\n\nuniform vec3 uHighlightColor;\nuniform vec3 uSelectColor;\nuniform vec2 uMarkerTexDim;\nuniform sampler2D tMarker;\n\nuniform float uAlpha;\nuniform float uPickingAlphaThreshold;\n\n#if defined(dGridTexType_2d)\n    precision highp sampler2D;\n    uniform sampler2D tGridTex;\n    uniform vec3 uGridTexDim;\n#elif defined(dGridTexType_3d)\n    precision highp sampler3D;\n    uniform sampler3D tGridTex;\n#endif\n\n#if defined(dColorType_uniform)\n    uniform vec3 uColor;\n#elif defined(dColorType_varying)\n    uniform vec2 uColorTexDim;\n    uniform sampler2D tColor;\n#endif\n\n#include common\n#include light_frag_params\n\n#include read_from_texture\n#include texture3d_from_2d_nearest\n#include texture3d_from_2d_linear\n\n#if defined(dGridTexType_2d)\n    vec4 textureVal(vec3 pos) {\n        return texture3dFrom2dLinear(tGridTex, pos, uGridDim, uGridTexDim.xy);\n    }\n    vec4 textureGroup(vec3 pos) {\n        vec3 nearestPos = floor(pos * uGridDim + 0.5) / uGridDim + 0.5 / uGridDim;\n        return texture3dFrom2dNearest(tGridTex, nearestPos, uGridDim, uGridTexDim.xy);\n    }\n#elif defined(dGridTexType_3d)\n    vec4 textureVal(vec3 pos) {\n        return texture(tGridTex, pos);\n    }\n    vec4 textureGroup(vec3 pos) {\n        return texelFetch(tGridTex, ivec3(pos * uGridDim), 0);\n    }\n#endif\n\nvec4 transferFunction(float value) {\n    return texture2D(tTransferTex, vec2(value, 0.0));\n}\n\nconst float gradOffset = 0.5;\n\nvec4 raymarch(vec3 startLoc, vec3 step, vec3 viewDir) {\n    vec3 scaleVol = vec3(1.0) / uGridDim;\n    vec3 pos = startLoc;\n    float prevValue = -1.0;\n    float value = 0.0;\n    vec4 src = vec4(0.0);\n    vec4 dst = vec4(0.0);\n\n    #if defined(dRenderMode_isosurface)\n        vec3 isoPos;\n        float tmp;\n\n        vec3 color = vec3(0.45, 0.55, 0.8);\n        vec3 gradient = vec3(1.0);\n        vec3 dx = vec3(gradOffset * scaleVol.x, 0.0, 0.0);\n        vec3 dy = vec3(0.0, gradOffset * scaleVol.y, 0.0);\n        vec3 dz = vec3(0.0, 0.0, gradOffset * scaleVol.z);\n    #endif\n\n    for(int i = 0; i < dMaxSteps; ++i){\n        value = textureVal(pos).a; // current voxel value\n        if(pos.x > 1.01 || pos.y > 1.01 || pos.z > 1.01 || pos.x < -0.01 || pos.y < -0.01 || pos.z < -0.01)\n            break;\n\n        #if defined(dRenderMode_volume)\n            src = transferFunction(value);\n            src.rgb *= src.a;\n            dst = (1.0 - dst.a) * src + dst; // standard blending\n        #endif\n\n        #if defined(dRenderMode_isosurface)\n            if(prevValue > 0.0 && ( // there was a prev Value\n                (prevValue < uIsoValue && value > uIsoValue) || // entering isosurface\n                (prevValue > uIsoValue && value < uIsoValue) // leaving isosurface\n            )) {\n                tmp = ((prevValue - uIsoValue) / ((prevValue - uIsoValue) - (value - uIsoValue)));\n                isoPos = mix(pos - step, pos, tmp);\n\n                #if defined(dRenderVariant_pick)\n                    if (uAlpha < uPickingAlphaThreshold)\n                        discard; // ignore so the element below can be picked\n                #endif\n\n                #if defined(dRenderVariant_pickObject)\n                    return vec4(encodeFloatRGB(float(uObjectId)), 1.0);\n                #elif defined(dRenderVariant_pickInstance)\n                    return vec4(encodeFloatRGB(instance), 1.0);\n                #elif defined(dRenderVariant_pickGroup)\n                    float group = floor(decodeFloatRGB(textureGroup(isoPos).rgb) + 0.5);\n                    return vec4(encodeFloatRGB(group), 1.0);\n                #elif defined(dRenderVariant_depth)\n                    return packDepthToRGBA(gl_FragCoord.z); // TODO calculate isosurface depth\n                #elif defined(dRenderVariant_color)\n                    // compute gradient by central differences\n                    gradient.x = textureVal(isoPos - dx).a - textureVal(isoPos + dx).a;\n                    gradient.y = textureVal(isoPos - dy).a - textureVal(isoPos + dy).a;\n                    gradient.z = textureVal(isoPos - dz).a - textureVal(isoPos + dz).a;\n                    gradient = normalize(gradient);\n                    float d = float(dot(gradient, viewDir) > 0.0);\n                    gradient = (2.0 * d - 1.0) * gradient;\n\n                    float group = floor(decodeFloatRGB(textureGroup(isoPos).rgb) + 0.5);\n\n                    #if defined(dColorType_instance)\n                        color = readFromTexture(tColor, instance, uColorTexDim).rgb;\n                    #elif defined(dColorType_group)\n                        color = readFromTexture(tColor, group, uColorTexDim).rgb;\n                    #elif defined(dColorType_groupInstance)\n                        color = readFromTexture(tColor, instance * float(uGroupCount) + group, uColorTexDim).rgb;\n                    #endif\n\n                    vec3 normal = normalize(gradient);\n                    vec3 vViewPosition = normalize(viewDir);\n                    vec4 material = vec4(color, uAlpha);\n                    #include apply_light_color\n\n                    float vMarker = readFromTexture(tMarker, instance * float(uGroupCount) + group, uMarkerTexDim).a;\n                    #include apply_marker_color\n\n                    src.rgb = gl_FragColor.rgb;\n                    src.a = gl_FragColor.a;\n\n                    // draw interior darker\n                    if( (prevValue - uIsoValue) > 0.0 ) {\n                        src.rgb *= 0.5;\n                    }\n\n                    src.rgb *= src.a;\n                    dst = (1.0 - dst.a) * src + dst; // standard blending\n                    if(dst.a >= 1.0) {\n                        break;\n                    }\n                #endif\n            }\n            prevValue = value;\n        #endif\n\n        pos += step;\n    }\n    return dst;\n}\n\nvoid main () {\n    vec3 cameraPos = uInvView[3].xyz / uInvView[3].w;\n\n    vec3 rayDir = normalize(origPos - cameraPos);\n    vec3 startLoc = unitCoord;\n    vec3 step = rayDir * (1.0 / uGridDim) * 0.1;\n\n    gl_FragColor = raymarch(startLoc, step, normalize(cameraPos));\n    if (length(gl_FragColor.rgb) < 0.00001) discard;\n    #if defined(dRenderMode_volume)\n        gl_FragColor.a *= uAlpha;\n    #endif\n}\n");
//# sourceMappingURL=direct-volume.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/image.vert.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var image_vert = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include common_vert_params\n\nattribute vec3 aPosition;\nattribute vec2 aUv;\nattribute mat4 aTransform;\nattribute float aInstance;\n\nvarying vec2 vUv;\nvarying float vInstance;\n\nvoid main() {\n    #include assign_position\n\n    vUv = aUv;\n    vInstance = aInstance;\n}\n");
//# sourceMappingURL=image.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/image.frag.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var image_frag = ("\nprecision highp float;\nprecision highp int;\n\n#include common\n#include read_from_texture\n#include common_frag_params\n\nuniform vec2 uImageTexDim;\nuniform sampler2D tImageTex;\nuniform sampler2D tGroupTex;\n\nuniform vec2 uMarkerTexDim;\nuniform sampler2D tMarker;\n\nvarying vec2 vUv;\nvarying float vInstance;\n\n#if defined(dInterpolation_catmulrom) || defined(dInterpolation_mitchell) || defined(dInterpolation_bspline)\n    #define dInterpolation_cubic\n#endif\n\n#if defined(dInterpolation_cubic)\n    #if defined(dInterpolation_catmulrom) || defined(dInterpolation_mitchell)\n        #if defined(dInterpolation_catmulrom)\n            const float B = 0.0;\n            const float C = 0.5;\n        #elif defined(dInterpolation_mitchell)\n            const float B = 0.333;\n            const float C = 0.333;\n        #endif\n\n        float cubicFilter(float x){\n            float f = x;\n            if (f < 0.0) {\n                f = -f;\n            }\n            if (f < 1.0) {\n                return ((12.0 - 9.0 * B - 6.0 * C) * (f * f * f) +\n                    (-18.0 + 12.0 * B + 6.0 * C) * (f * f) +\n                    (6.0 - 2.0 * B)) / 6.0;\n            }else if (f >= 1.0 && f < 2.0){\n                return ((-B - 6.0 * C) * ( f * f * f)\n                    + (6.0 * B + 30.0 * C) * (f * f) +\n                    (-(12.0 * B) - 48.0 * C) * f +\n                    8.0 * B + 24.0 * C) / 6.0;\n            }else{\n                return 0.0;\n            }\n        }\n    #elif defined(dInterpolation_bspline)\n        float cubicFilter(float x) {\n            float f = x;\n            if (f < 0.0) {\n                f = -f;\n            }\n            if (f >= 0.0 && f <= 1.0){\n                return (2.0 / 3.0) + (0.5) * (f * f * f) - (f * f);\n            } else if (f > 1.0 && f <= 2.0) {\n                return 1.0 / 6.0 * pow((2.0 - f), 3.0);\n            }\n            return 1.0;\n        }\n    #endif\n\n    vec4 biCubic(sampler2D tex, vec2 texCoord) {\n        vec2 texelSize = 1.0 / uImageTexDim;\n        texCoord -= texelSize / 2.0;\n        vec4 nSum = vec4(0.0);\n        float nDenom = 0.0;\n        vec2 cell = fract(texCoord * uImageTexDim);\n        for (float m = -1.0; m <= 2.0; ++m) {\n            for (float n = -1.0; n <= 2.0; ++n) {\n                vec4 vecData = texture2D(tex, texCoord + texelSize * vec2(m, n));\n                float c = cubicFilter(m - cell.x) * cubicFilter(-n + cell.y);\n                nSum += vecData * c;\n                nDenom += c;\n            }\n        }\n        return nSum / nDenom;\n    }\n#endif\n\nvoid main() {\n    #if defined(dInterpolation_cubic)\n        vec4 imageData = biCubic(tImageTex, vUv);\n    #else\n        vec4 imageData = texture2D(tImageTex, vUv);\n    #endif\n    imageData.a = clamp(imageData.a, 0.0, 1.0);\n    if (imageData.a > 0.9) imageData.a = 1.0;\n\n    #if defined(dRenderVariant_pick)\n        if (imageData.a < 0.3)\n            discard;\n\n        #if defined(dRenderVariant_pickObject)\n            gl_FragColor = vec4(encodeFloatRGB(float(uObjectId)), 1.0);\n        #elif defined(dRenderVariant_pickInstance)\n            gl_FragColor = vec4(encodeFloatRGB(vInstance), 1.0);\n        #elif defined(dRenderVariant_pickGroup)\n            float group = texture2D(tGroupTex, vUv).r;\n            gl_FragColor = vec4(encodeFloatRGB(group), 1.0);\n        #endif\n    #elif defined(dRenderVariant_depth)\n        if (imageData.a < 0.05)\n            discard;\n\n        #ifdef enabledFragDepth\n            gl_FragColor = packDepthToRGBA(gl_FragDepthEXT);\n        #else\n            gl_FragColor = packDepthToRGBA(gl_FragCoord.z);\n        #endif\n    #elif defined(dRenderVariant_color)\n        if (imageData.a < 0.05)\n            discard;\n\n        gl_FragColor = imageData;\n        gl_FragColor.a *= uAlpha;\n\n        float group = texture2D(tGroupTex, vUv).r;\n        float vMarker = readFromTexture(tMarker, vInstance * float(uGroupCount) + group, uMarkerTexDim).a;\n        #include apply_marker_color\n        #include apply_fog\n    #endif\n}\n");
//# sourceMappingURL=image.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var shaderCodeId = Object(id_factory["a" /* idFactory */])();



























var ShaderChunks = {
    apply_fog: apply_fog_glsl,
    apply_interior_color: apply_interior_color_glsl,
    apply_light_color: apply_light_color_glsl,
    apply_marker_color: apply_marker_color_glsl,
    assign_clipping_varying: assign_clipping_varying_glsl,
    assign_color_varying: assign_color_varying_glsl,
    assign_group: assign_group_glsl,
    assign_marker_varying: assign_marker_varying_glsl,
    assign_material_color: assign_material_color_glsl,
    assign_position: assign_position_glsl,
    assign_size: assign_size_glsl,
    check_picking_alpha: check_picking_alpha_glsl,
    clip_instance: clip_instance_glsl,
    clip_pixel: clip_pixel_glsl,
    color_frag_params: color_frag_params_glsl,
    color_vert_params: color_vert_params_glsl,
    common_clip: common_clip_glsl,
    common_frag_params: common_frag_params_glsl,
    common_vert_params: common_vert_params_glsl,
    common: common_glsl,
    light_frag_params: light_frag_params_glsl,
    matrix_scale: matrix_scale_glsl,
    normal_frag_params: normal_frag_params_glsl,
    read_from_texture: read_from_texture_glsl,
    size_vert_params: size_vert_params_glsl,
    texture3d_from_2d_linear: texture3d_from_2d_nearest_glsl,
    texture3d_from_2d_nearest: texture3d_from_2d_nearest_glsl
};
var reInclude = /^(?!\/\/)\s*#include\s+(\S+)/gmi;
var reSingleLineComment = /[ \t]*\/\/.*\n/g;
var reMultiLineComment = /[ \t]*\/\*[\s\S]*?\*\//g;
var reMultipleLinebreaks = /\n{2,}/g;
function addIncludes(text) {
    return text
        .replace(reInclude, function (_, p1) {
        var chunk = ShaderChunks[p1];
        if (!chunk)
            throw new Error("empty chunk, '" + p1 + "'");
        return chunk;
    })
        .trim()
        .replace(reSingleLineComment, '\n')
        .replace(reMultiLineComment, '\n')
        .replace(reMultipleLinebreaks, '\n');
}
function ShaderCode(name, vert, frag, extensions) {
    if (extensions === void 0) { extensions = {}; }
    return { id: shaderCodeId(), name: name, vert: addIncludes(vert), frag: addIncludes(frag), extensions: extensions };
}


var PointsShaderCode = ShaderCode('points', points_vert, points_frag);


var SpheresShaderCode = ShaderCode('spheres', spheres_vert, spheres_frag, { fragDepth: true });


var TextShaderCode = ShaderCode('text', text_vert, text_frag, { standardDerivatives: true });


var LinesShaderCode = ShaderCode('lines', lines_vert, lines_frag);


var MeshShaderCode = ShaderCode('mesh', mesh_vert, mesh_frag, { standardDerivatives: true });


var DirectVolumeShaderCode = ShaderCode('direct-volume', direct_volume_vert, direct_volume_frag, { fragDepth: true });


var ImageShaderCode = ShaderCode('image', image_vert, image_frag, { fragDepth: true });
function getDefinesCode(defines) {
    if (defines === undefined)
        return '';
    var lines = [];
    for (var name_1 in defines) {
        var define = defines[name_1];
        var v = define.ref.value;
        if (v !== undefined) {
            if (typeof v === 'string') {
                lines.push("#define " + name_1 + "_" + v);
            }
            else if (typeof v === 'number') {
                lines.push("#define " + name_1 + " " + v);
            }
            else if (typeof v === 'boolean') {
                if (v)
                    lines.push("#define " + name_1);
            }
            else {
                throw new Error('unknown define type');
            }
        }
    }
    return lines.join('\n') + '\n';
}
function getGlsl100FragPrefix(extensions, shaderExtensions) {
    var prefix = [];
    if (shaderExtensions.standardDerivatives) {
        prefix.push('#extension GL_OES_standard_derivatives : enable');
        prefix.push('#define enabledStandardDerivatives');
    }
    if (shaderExtensions.fragDepth) {
        if (extensions.fragDepth) {
            prefix.push('#extension GL_EXT_frag_depth : enable');
            prefix.push('#define enabledFragDepth');
        }
        else {
            throw new Error("requested 'GL_EXT_frag_depth' extension is unavailable");
        }
    }
    if (shaderExtensions.drawBuffers) {
        if (extensions.drawBuffers) {
            prefix.push('#extension GL_EXT_draw_buffers : require');
            prefix.push('#define requiredDrawBuffers');
        }
        else {
            throw new Error("requested 'GL_EXT_draw_buffers' extension is unavailable");
        }
    }
    if (shaderExtensions.shaderTextureLod) {
        if (extensions.shaderTextureLod) {
            prefix.push('#extension GL_EXT_shader_texture_lod : enable');
            prefix.push('#define enabledShaderTextureLod');
        }
        else {
            throw new Error("requested 'GL_EXT_shader_texture_lod' extension is unavailable");
        }
    }
    return prefix.join('\n') + '\n';
}
var glsl300VertPrefix = "#version 300 es\n#define attribute in\n#define varying out\n#define texture2D texture\n";
var glsl300FragPrefixCommon = "\n#define varying in\n#define texture2D texture\n#define texture2DLodEXT textureLod\n\n#define gl_FragColor out_FragData0\n#define gl_FragDepthEXT gl_FragDepth\n\n#define requiredDrawBuffers\n";
function getGlsl300FragPrefix(gl, extensions, shaderExtensions) {
    var prefix = ['#version 300 es'];
    if (shaderExtensions.standardDerivatives) {
        prefix.push('#define enabledStandardDerivatives');
    }
    if (shaderExtensions.fragDepth) {
        prefix.push('#define enabledFragDepth');
    }
    if (extensions.drawBuffers) {
        var maxDrawBuffers = gl.getParameter(gl.MAX_DRAW_BUFFERS);
        for (var i = 0, il = maxDrawBuffers; i < il; ++i) {
            prefix.push("layout(location = " + i + ") out highp vec4 out_FragData" + i + ";");
        }
    }
    prefix.push(glsl300FragPrefixCommon);
    return prefix.join('\n') + '\n';
}
function transformGlsl300Frag(frag) {
    return frag.replace(/gl_FragData\[([0-9]+)\]/g, 'out_FragData$1');
}
function addShaderDefines(gl, extensions, defines, shaders) {
    var header = getDefinesCode(defines);
    var vertPrefix = Object(compat["m" /* isWebGL2 */])(gl) ? glsl300VertPrefix : '';
    var fragPrefix = Object(compat["m" /* isWebGL2 */])(gl)
        ? getGlsl300FragPrefix(gl, extensions, shaders.extensions)
        : getGlsl100FragPrefix(extensions, shaders.extensions);
    var frag = Object(compat["m" /* isWebGL2 */])(gl) ? transformGlsl300Frag(shaders.frag) : shaders.frag;
    return {
        id: shaderCodeId(),
        name: shaders.name,
        vert: "" + vertPrefix + header + shaders.vert,
        frag: "" + fragPrefix + header + frag,
        extensions: shaders.extensions
    };
}
//# sourceMappingURL=shader-code.js.map

/***/ }),
/* 93 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BasicSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createBasic; });
/* harmony import */ var _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
/* harmony import */ var _mol_io_reader_cif_schema_mmcif_extras__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(359);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var BasicSchema = {
    entry: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].entry,
    struct: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].struct,
    struct_asym: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].struct_asym,
    ihm_model_list: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].ihm_model_list,
    ihm_model_group: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].ihm_model_group,
    ihm_model_group_link: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].ihm_model_group_link,
    entity: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].entity,
    entity_poly: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].entity_poly,
    entity_poly_seq: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].entity_poly_seq,
    pdbx_entity_branch: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].pdbx_entity_branch,
    chem_comp: _mol_io_reader_cif_schema_mmcif_extras__WEBPACK_IMPORTED_MODULE_2__[/* mmCIF_chemComp_schema */ "a"],
    pdbx_chem_comp_identifier: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].pdbx_chem_comp_identifier,
    atom_site: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].atom_site,
    ihm_sphere_obj_site: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].ihm_sphere_obj_site,
    ihm_gaussian_obj_site: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].ihm_gaussian_obj_site,
    pdbx_unobs_or_zero_occ_residues: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].pdbx_unobs_or_zero_occ_residues,
    pdbx_molecule: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].pdbx_molecule,
};
function createBasic(data) {
    var basic = Object.create(null);
    for (var _i = 0, _a = Object.keys(BasicSchema); _i < _a.length; _i++) {
        var name_1 = _a[_i];
        if (name_1 in data) {
            basic[name_1] = data[name_1];
        }
        else {
            basic[name_1] = _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Table"].ofUndefinedColumns(BasicSchema[name_1], 0);
        }
    }
    return basic;
}
//# sourceMappingURL=schema.js.map

/***/ }),
/* 94 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return getUnitKindsParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return StructureParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return StructureMeshParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return StructureSpheresParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return StructurePointsParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StructureLinesParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return StructureTextParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructureDirectVolumeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return StructureTextureMeshParams; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(265);
/* harmony import */ var _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(74);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(39);
/* harmony import */ var _mol_geo_geometry_points_points__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(257);
/* harmony import */ var _mol_geo_geometry_spheres_spheres__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(258);
/* harmony import */ var _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(123);
/* harmony import */ var _mol_geo_geometry_texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(259);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2);
/* harmony import */ var _visual_util_common__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(51);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */










function getUnitKindsParam(defaultValue) {
    return _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].MultiSelect(defaultValue, _visual_util_common__WEBPACK_IMPORTED_MODULE_9__[/* UnitKindOptions */ "b"], { description: 'For which kinds of units/chains to show the representation visuals.' });
}
var StructureParams = {
    unitKinds: getUnitKindsParam(['atomic', 'spheres']),
};
var StructureMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__[/* Mesh */ "a"].Params);
var StructureSpheresParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_spheres_spheres__WEBPACK_IMPORTED_MODULE_5__[/* Spheres */ "a"].Params);
var StructurePointsParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_points_points__WEBPACK_IMPORTED_MODULE_4__[/* Points */ "a"].Params);
var StructureLinesParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_2__[/* Lines */ "a"].Params);
var StructureTextParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_6__[/* Text */ "a"].Params);
var StructureDirectVolumeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_1__[/* DirectVolume */ "a"].Params);
var StructureTextureMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_7__[/* TextureMesh */ "a"].Params);
//# sourceMappingURL=params.js.map

/***/ }),
/* 95 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PluginCommand; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PluginCommandManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



function PluginCommand() {
    var ret = (function (ctx, params) { return ctx.commands.dispatch(ret, params || {}); });
    ret.subscribe = function (ctx, action) { return ctx.commands.subscribe(ret, action); };
    ret.id = _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* UUID */ "c"].create22();
    return ret;
}
var PluginCommandManager = /** @class */ (function () {
    function PluginCommandManager() {
        this.subs = new Map();
        this.disposing = false;
    }
    PluginCommandManager.prototype.subscribe = function (cmd, action) {
        var _this = this;
        var actions = this.subs.get(cmd.id);
        if (!actions) {
            actions = [];
            this.subs.set(cmd.id, actions);
        }
        actions.push(action);
        return {
            unsubscribe: function () {
                var actions = _this.subs.get(cmd.id);
                if (!actions)
                    return;
                var idx = actions.indexOf(action);
                if (idx < 0)
                    return;
                for (var i = idx + 1; i < actions.length; i++) {
                    actions[i - 1] = actions[i];
                }
                actions.pop();
            }
        };
    };
    /** Resolves after all actions have completed */
    PluginCommandManager.prototype.dispatch = function (cmd, params) {
        var _this = this;
        return new Promise(function (resolve, reject) {
            if (_this.disposing) {
                reject('disposed');
                return;
            }
            var actions = _this.subs.get(cmd.id);
            if (!actions) {
                resolve();
                return;
            }
            _this.resolve({ cmd: cmd, params: params, resolve: resolve, reject: reject });
        });
    };
    PluginCommandManager.prototype.dispose = function () {
        this.subs.clear();
    };
    PluginCommandManager.prototype.resolve = function (instance) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var actions, _i, actions_1, a, e_1;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        actions = this.subs.get(instance.cmd.id);
                        if (!actions) {
                            instance.resolve();
                            return [2 /*return*/];
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 6, , 7]);
                        _i = 0, actions_1 = actions;
                        _a.label = 2;
                    case 2:
                        if (!(_i < actions_1.length)) return [3 /*break*/, 5];
                        a = actions_1[_i];
                        return [4 /*yield*/, a(instance.params)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5:
                        instance.resolve();
                        return [3 /*break*/, 7];
                    case 6:
                        e_1 = _a.sent();
                        instance.reject(e_1);
                        return [3 /*break*/, 7];
                    case 7: return [2 /*return*/];
                }
            });
        });
    };
    return PluginCommandManager;
}());
//# sourceMappingURL=command.js.map

/***/ }),
/* 96 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return idFactory; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/** Builds id function returning ids within [firstId, maxId) */
function idFactory(firstId, maxId) {
    if (firstId === void 0) { firstId = 0; }
    if (maxId === void 0) { maxId = Number.MAX_SAFE_INTEGER; }
    var _nextId = firstId;
    return function () {
        var ret = _nextId;
        _nextId = (_nextId + 1) % maxId;
        return ret;
    };
}
//# sourceMappingURL=id-factory.js.map

/***/ }),
/* 97 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return parseIntSkipLeadingWhitespace; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return parseInt; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return parseFloatSkipLeadingWhitespace; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return parseFloat; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getNumberType; });
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * based in part on https://github.com/dsehnal/CIFTools.js
 */
/**
 * Efficient integer and float parsers.
 *
 * For the purposes of parsing numbers from the mmCIF data representations,
 * up to 4 times faster than JS parseInt/parseFloat.
 */
function parseIntSkipLeadingWhitespace(str, start, end) {
    while (start < end && str.charCodeAt(start) === 32)
        start++;
    return parseInt(str, start, end);
}
function parseInt(str, start, end) {
    var _start = start, ret = 0, neg = 1;
    if (str.charCodeAt(_start) === 45 /* - */) {
        neg = -1;
        _start++;
    }
    for (; _start < end; _start++) {
        var c = str.charCodeAt(_start) - 48;
        if (c > 9 || c < 0)
            return (neg * ret) | 0;
        else
            ret = (10 * ret + c) | 0;
    }
    return neg * ret;
}
function parseScientific(main, str, start, end) {
    // handle + in '1e+1' separately.
    if (str.charCodeAt(start) === 43 /* + */)
        start++;
    return main * Math.pow(10.0, parseInt(str, start, end));
}
function parseFloatSkipLeadingWhitespace(str, start, end) {
    while (start < end && str.charCodeAt(start) === 32)
        start++;
    return parseFloat(str, start, end);
}
function parseFloat(str, start, end) {
    var _start = start, neg = 1.0, ret = 0.0, point = 0.0, div = 1.0;
    if (str.charCodeAt(_start) === 45) {
        neg = -1.0;
        ++_start;
    }
    while (_start < end) {
        var c = str.charCodeAt(_start) - 48;
        if (c >= 0 && c < 10) {
            ret = ret * 10 + c;
            ++_start;
        }
        else if (c === -2) { // .
            ++_start;
            while (_start < end) {
                c = str.charCodeAt(_start) - 48;
                if (c >= 0 && c < 10) {
                    point = 10.0 * point + c;
                    div = 10.0 * div;
                    ++_start;
                }
                else if (c === 53 || c === 21) { // 'e'/'E'
                    return parseScientific(neg * (ret + point / div), str, _start + 1, end);
                }
                else {
                    return neg * (ret + point / div);
                }
            }
            return neg * (ret + point / div);
        }
        else if (c === 53 || c === 21) { // 'e'/'E'
            return parseScientific(neg * ret, str, _start + 1, end);
        }
        else {
            break;
        }
    }
    return neg * ret;
}
function isInt(str, start, end) {
    if (str.charCodeAt(start) === 45 /* - */) {
        start++;
    }
    for (; start < end; start++) {
        var c = str.charCodeAt(start) - 48;
        if (c > 9 || c < 0)
            return false;
    }
    return true;
}
// TODO: check for "scientific integers?"
function getNumberTypeScientific(str, start, end) {
    // handle + in '1e+1' separately.
    if (str.charCodeAt(start) === 43 /* + */)
        start++;
    return isInt(str, start, end) ? 2 /* Scientific */ : 3 /* NaN */;
}
/** The whole range must match, otherwise returns NaN */
function getNumberType(str) {
    var start = 0, end = str.length;
    if (str.charCodeAt(start) === 45) { // -
        ++start;
    }
    // string is . or -.
    if (str.charCodeAt(start) === 46 && end - start === 1) {
        return 3 /* NaN */;
    }
    while (start < end) {
        var c = str.charCodeAt(start) - 48;
        if (c >= 0 && c < 10) {
            ++start;
        }
        else if (c === -2) { // .
            ++start;
            var hasDigit = false;
            while (start < end) {
                c = str.charCodeAt(start) - 48;
                if (c >= 0 && c < 10) {
                    hasDigit = true;
                    ++start;
                }
                else if (c === 53 || c === 21) { // 'e'/'E'
                    return getNumberTypeScientific(str, start + 1, end);
                }
                else {
                    return 3 /* NaN */;
                }
            }
            return hasDigit ? 1 /* Float */ : 0 /* Int */;
        }
        else if (c === 53 || c === 21) { // 'e'/'E'
            if (start === 0 || start === 1 && str.charCodeAt(0) === 45) {
                return 3 /* NaN */; // string starts with e/E or -e/-E
            }
            return getNumberTypeScientific(str, start + 1, end);
        }
        else {
            break;
        }
    }
    return start === end ? 0 /* Int */ : 3 /* NaN */;
}
//# sourceMappingURL=number-parser.js.map

/***/ }),
/* 98 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createRenderable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createComputeRenderable; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(96);
/* harmony import */ var _mol_math_interpolate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(78);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var getNextRenderableId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_1__[/* idFactory */ "a"])();
function createRenderable(renderItem, values, state) {
    return {
        id: getNextRenderableId(),
        materialId: renderItem.materialId,
        values: values,
        state: state,
        render: function (variant) {
            if (values.uAlpha && values.alpha) {
                _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].updateIfChanged(values.uAlpha, Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* clamp */ "a"])(values.alpha.ref.value * state.alphaFactor, 0, 1));
            }
            renderItem.render(variant);
        },
        getProgram: function (variant) { return renderItem.getProgram(variant); },
        update: function () { return renderItem.update(); },
        dispose: function () { return renderItem.destroy(); }
    };
}
function createComputeRenderable(renderItem, values) {
    return {
        id: getNextRenderableId(),
        values: values,
        render: function () { return renderItem.render('compute'); },
        update: function () { return renderItem.update(); },
        dispose: function () { return renderItem.destroy(); }
    };
}
//# sourceMappingURL=renderable.js.map

/***/ }),
/* 99 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getDrawMode */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createGraphicsRenderItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createComputeRenderItem; });
/* unused harmony export createRenderItem */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(281);
/* harmony import */ var _texture__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(362);
/* harmony import */ var _context__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(333);
/* harmony import */ var _renderable_schema__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(17);
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(96);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(5);
/* harmony import */ var _framebuffer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(261);
/* harmony import */ var _mol_util_debug__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(61);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var getNextRenderItemId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_5__[/* idFactory */ "a"])();
function getDrawMode(ctx, drawMode) {
    var gl = ctx.gl;
    switch (drawMode) {
        case 'points': return gl.POINTS;
        case 'lines': return gl.LINES;
        case 'line-strip': return gl.LINE_STRIP;
        case 'line-loop': return gl.LINE_LOOP;
        case 'triangles': return gl.TRIANGLES;
        case 'triangle-strip': return gl.TRIANGLE_STRIP;
        case 'triangle-fan': return gl.TRIANGLE_FAN;
    }
}
//
var GraphicsRenderVariant = { 'color': '', 'pickObject': '', 'pickInstance': '', 'pickGroup': '', 'depth': '' };
var GraphicsRenderVariants = Object.keys(GraphicsRenderVariant);
var ComputeRenderVariant = { 'compute': '' };
var ComputeRenderVariants = Object.keys(ComputeRenderVariant);
function createProgramVariant(ctx, variant, defineValues, shaderCode, schema) {
    defineValues = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, defineValues), { dRenderVariant: _mol_util__WEBPACK_IMPORTED_MODULE_6__[/* ValueCell */ "e"].create(variant) });
    schema = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, schema), { dRenderVariant: Object(_renderable_schema__WEBPACK_IMPORTED_MODULE_4__[/* DefineSpec */ "c"])('string') });
    return ctx.resources.program(defineValues, shaderCode, schema);
}
function createValueChanges() {
    return {
        attributes: false,
        defines: false,
        elements: false,
        textures: false,
    };
}
function resetValueChanges(valueChanges) {
    valueChanges.attributes = false;
    valueChanges.defines = false;
    valueChanges.elements = false;
    valueChanges.textures = false;
}
function createGraphicsRenderItem(ctx, drawMode, shaderCode, schema, values, materialId) {
    return createRenderItem(ctx, drawMode, shaderCode, schema, values, materialId, GraphicsRenderVariants);
}
function createComputeRenderItem(ctx, drawMode, shaderCode, schema, values, materialId) {
    if (materialId === void 0) { materialId = -1; }
    return createRenderItem(ctx, drawMode, shaderCode, schema, values, materialId, ComputeRenderVariants);
}
/**
 * Creates a render item
 *
 * - assumes that `values.drawCount` and `values.instanceCount` exist
 */
function createRenderItem(ctx, drawMode, shaderCode, schema, values, materialId, renderVariants) {
    var id = getNextRenderItemId();
    var stats = ctx.stats, state = ctx.state, resources = ctx.resources;
    var _a = ctx.extensions, instancedArrays = _a.instancedArrays, vertexArrayObject = _a.vertexArrayObject;
    var _b = Object(_renderable_schema__WEBPACK_IMPORTED_MODULE_4__[/* splitValues */ "l"])(schema, values), attributeValues = _b.attributeValues, defineValues = _b.defineValues, textureValues = _b.textureValues, uniformValues = _b.uniformValues, materialUniformValues = _b.materialUniformValues;
    var uniformValueEntries = Object.entries(uniformValues);
    var materialUniformValueEntries = Object.entries(materialUniformValues);
    var defineValueEntries = Object.entries(defineValues);
    var versions = Object(_renderable_schema__WEBPACK_IMPORTED_MODULE_4__[/* getValueVersions */ "k"])(values);
    var glDrawMode = getDrawMode(ctx, drawMode);
    var programs = {};
    for (var _i = 0, renderVariants_1 = renderVariants; _i < renderVariants_1.length; _i++) {
        var k = renderVariants_1[_i];
        programs[k] = createProgramVariant(ctx, k, defineValues, shaderCode, schema);
    }
    var textures = Object(_texture__WEBPACK_IMPORTED_MODULE_2__[/* createTextures */ "b"])(ctx, schema, textureValues);
    var attributeBuffers = Object(_buffer__WEBPACK_IMPORTED_MODULE_1__[/* createAttributeBuffers */ "b"])(ctx, schema, attributeValues);
    var elementsBuffer;
    var elements = values.elements;
    if (elements && elements.ref.value) {
        elementsBuffer = resources.elements(elements.ref.value);
    }
    var vertexArrays = {};
    for (var _c = 0, renderVariants_2 = renderVariants; _c < renderVariants_2.length; _c++) {
        var k = renderVariants_2[_c];
        vertexArrays[k] = vertexArrayObject ? resources.vertexArray(programs[k], attributeBuffers, elementsBuffer) : null;
    }
    var drawCount = values.drawCount.ref.value;
    var instanceCount = values.instanceCount.ref.value;
    stats.drawCount += drawCount;
    stats.instanceCount += instanceCount;
    stats.instancedDrawCount += instanceCount * drawCount;
    var valueChanges = createValueChanges();
    var destroyed = false;
    var currentProgramId = -1;
    return {
        id: id,
        materialId: materialId,
        getProgram: function (variant) { return programs[variant]; },
        render: function (variant) {
            if (drawCount === 0 || instanceCount === 0 || ctx.isContextLost)
                return;
            var program = programs[variant];
            if (program.id === currentProgramId && state.currentRenderItemId === id) {
                program.setUniforms(uniformValueEntries);
                program.bindTextures(textures);
            }
            else {
                var vertexArray = vertexArrays[variant];
                if (program.id !== state.currentProgramId || program.id !== currentProgramId ||
                    materialId === -1 || materialId !== state.currentMaterialId) {
                    // console.log('program.id changed or materialId changed/-1', materialId)
                    if (program.id !== state.currentProgramId)
                        program.use();
                    program.setUniforms(materialUniformValueEntries);
                    state.currentMaterialId = materialId;
                    currentProgramId = program.id;
                }
                program.setUniforms(uniformValueEntries);
                program.bindTextures(textures);
                if (vertexArray) {
                    vertexArray.bind();
                    // need to bind elements buffer explicitly since it is not always recorded in the VAO
                    if (elementsBuffer)
                        elementsBuffer.bind();
                }
                else {
                    if (elementsBuffer)
                        elementsBuffer.bind();
                    program.bindAttributes(attributeBuffers);
                }
                state.currentRenderItemId = id;
            }
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_8__[/* isDebugMode */ "a"]) {
                Object(_framebuffer__WEBPACK_IMPORTED_MODULE_7__[/* checkFramebufferStatus */ "a"])(ctx.gl);
            }
            if (elementsBuffer) {
                instancedArrays.drawElementsInstanced(glDrawMode, drawCount, elementsBuffer._dataType, 0, instanceCount);
            }
            else {
                instancedArrays.drawArraysInstanced(glDrawMode, 0, drawCount, instanceCount);
            }
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_8__[/* isDebugMode */ "a"]) {
                try {
                    Object(_context__WEBPACK_IMPORTED_MODULE_3__[/* checkError */ "a"])(ctx.gl);
                }
                catch (e) {
                    throw new Error("Error rendering item id " + id + ": '" + e + "'");
                }
            }
        },
        update: function () {
            resetValueChanges(valueChanges);
            for (var i = 0, il = defineValueEntries.length; i < il; ++i) {
                var _a = defineValueEntries[i], k = _a[0], value = _a[1];
                if (value.ref.version !== versions[k]) {
                    // console.log('define version changed', k)
                    valueChanges.defines = true;
                    versions[k] = value.ref.version;
                }
            }
            if (valueChanges.defines) {
                // console.log('some defines changed, need to rebuild programs')
                for (var _i = 0, renderVariants_3 = renderVariants; _i < renderVariants_3.length; _i++) {
                    var k = renderVariants_3[_i];
                    programs[k].destroy();
                    programs[k] = createProgramVariant(ctx, k, defineValues, shaderCode, schema);
                }
            }
            if (values.drawCount.ref.version !== versions.drawCount) {
                // console.log('drawCount version changed')
                stats.drawCount += values.drawCount.ref.value - drawCount;
                stats.instancedDrawCount += instanceCount * values.drawCount.ref.value - instanceCount * drawCount;
                drawCount = values.drawCount.ref.value;
                versions.drawCount = values.drawCount.ref.version;
            }
            if (values.instanceCount.ref.version !== versions.instanceCount) {
                // console.log('instanceCount version changed')
                stats.instanceCount += values.instanceCount.ref.value - instanceCount;
                stats.instancedDrawCount += values.instanceCount.ref.value * drawCount - instanceCount * drawCount;
                instanceCount = values.instanceCount.ref.value;
                versions.instanceCount = values.instanceCount.ref.version;
            }
            for (var i = 0, il = attributeBuffers.length; i < il; ++i) {
                var _b = attributeBuffers[i], k = _b[0], buffer = _b[1];
                var value = attributeValues[k];
                if (value.ref.version !== versions[k]) {
                    if (buffer.length >= value.ref.value.length) {
                        // console.log('attribute array large enough to update', buffer.id, k, value.ref.id, value.ref.version)
                        buffer.updateData(value.ref.value);
                    }
                    else {
                        // console.log('attribute array too small, need to create new attribute', buffer.id, k, value.ref.id, value.ref.version)
                        buffer.destroy();
                        var _c = schema[k], itemSize = _c.itemSize, divisor = _c.divisor;
                        attributeBuffers[i][1] = resources.attribute(value.ref.value, itemSize, divisor);
                        valueChanges.attributes = true;
                    }
                    versions[k] = value.ref.version;
                }
            }
            if (elementsBuffer && values.elements.ref.version !== versions.elements) {
                if (elementsBuffer.length >= values.elements.ref.value.length) {
                    // console.log('elements array large enough to update', values.elements.ref.id, values.elements.ref.version)
                    elementsBuffer.updateData(values.elements.ref.value);
                }
                else {
                    // console.log('elements array to small, need to create new elements', values.elements.ref.id, values.elements.ref.version)
                    elementsBuffer.destroy();
                    elementsBuffer = resources.elements(values.elements.ref.value);
                    valueChanges.elements = true;
                }
                versions.elements = values.elements.ref.version;
            }
            if (valueChanges.attributes || valueChanges.defines || valueChanges.elements) {
                // console.log('program/defines or buffers changed, update vaos')
                for (var _d = 0, renderVariants_4 = renderVariants; _d < renderVariants_4.length; _d++) {
                    var k = renderVariants_4[_d];
                    var vertexArray = vertexArrays[k];
                    if (vertexArray)
                        vertexArray.destroy();
                    vertexArrays[k] = vertexArrayObject ? resources.vertexArray(programs[k], attributeBuffers, elementsBuffer) : null;
                }
            }
            for (var i = 0, il = textures.length; i < il; ++i) {
                var _e = textures[i], k = _e[0], texture = _e[1];
                var value = textureValues[k];
                if (value.ref.version !== versions[k]) {
                    // update of textures with kind 'texture' is done externally
                    if (schema[k].kind !== 'texture') {
                        // console.log('texture version changed, uploading image', k)
                        texture.load(value.ref.value);
                        versions[k] = value.ref.version;
                        valueChanges.textures = true;
                    }
                    else {
                        textures[i][1] = value.ref.value;
                    }
                }
            }
            return valueChanges;
        },
        destroy: function () {
            if (!destroyed) {
                for (var _i = 0, renderVariants_5 = renderVariants; _i < renderVariants_5.length; _i++) {
                    var k = renderVariants_5[_i];
                    programs[k].destroy();
                    var vertexArray = vertexArrays[k];
                    if (vertexArray)
                        vertexArray.destroy();
                }
                textures.forEach(function (_a) {
                    var k = _a[0], texture = _a[1];
                    // lifetime of textures with kind 'texture' is defined externally
                    if (schema[k].kind !== 'texture') {
                        texture.destroy();
                    }
                });
                attributeBuffers.forEach(function (_a) {
                    var _ = _a[0], buffer = _a[1];
                    return buffer.destroy();
                });
                if (elementsBuffer)
                    elementsBuffer.destroy();
                destroyed = true;
            }
        }
    };
}
//# sourceMappingURL=render-item.js.map

/***/ }),
/* 100 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isArray; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArray = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })();
//# sourceMappingURL=isArray.js.map


/***/ }),
/* 101 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginConfigItem", function() { return PluginConfigItem; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginConfig", function() { return PluginConfig; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginConfigManager", function() { return PluginConfigManager; });
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var PluginConfigItem = /** @class */ (function () {
    function PluginConfigItem(key, defaultValue) {
        this.key = key;
        this.defaultValue = defaultValue;
    }
    PluginConfigItem.prototype.toString = function () { return this.key; };
    PluginConfigItem.prototype.valueOf = function () { return this.key; };
    return PluginConfigItem;
}());

function item(key, defaultValue) { return new PluginConfigItem(key, defaultValue); }
var PluginConfig = {
    item: item,
    General: {
        IsBusyTimeoutMs: item('plugin-config.is-busy-timeout', 750)
    },
    State: {
        DefaultServer: item('plugin-state.server', 'https://webchem.ncbr.muni.cz/molstar-state'),
        CurrentServer: item('plugin-state.server', 'https://webchem.ncbr.muni.cz/molstar-state')
    },
    VolumeStreaming: {
        DefaultServer: item('volume-streaming.server', 'https://ds.litemol.org'),
        CanStream: item('volume-streaming.can-stream', function (s, plugin) {
            return s.models.length === 1 && _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Model"].probablyHasDensityMap(s.models[0]);
        }),
        EmdbHeaderServer: item('volume-streaming.emdb-header-server', 'https://ftp.wwpdb.org/pub/emdb/structures'),
    },
    Viewport: {
        ShowExpand: item('viewer.show-expand-button', true),
        ShowSelectionMode: item('viewer.show-selection-model-button', true),
        ShowAnimation: item('viewer.show-animation-button', true),
    },
    Download: {
        DefaultPdbProvider: item('download.default-pdb-provider', 'pdbe'),
        DefaultEmdbProvider: item('download.default-emdb-provider', 'pdbe'),
    },
    Structure: {
        SizeThresholds: item('structure.size-thresholds', _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Structure"].DefaultSizeThresholds),
        DefaultRepresentationPresetParams: item('structure.default-representation-preset-params', {})
    }
};
var PluginConfigManager = /** @class */ (function () {
    function PluginConfigManager(initial) {
        var _this = this;
        this._config = new Map();
        if (!initial)
            return;
        initial.forEach(function (_a) {
            var k = _a[0], v = _a[1];
            return _this._config.set(k, v);
        });
    }
    PluginConfigManager.prototype.get = function (key) {
        if (!this._config.has(key))
            return key.defaultValue;
        return this._config.get(key);
    };
    PluginConfigManager.prototype.set = function (key, value) {
        this._config.set(key, value);
    };
    PluginConfigManager.prototype.delete = function (key) {
        this._config.delete(key);
    };
    return PluginConfigManager;
}());

//# sourceMappingURL=config.js.map

/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {

/**
 * Copyright (c) 2014-present, Facebook, Inc.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

(function (global, factory) {
   true ? module.exports = factory() :
  undefined;
}(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice;

  function createClass(ctor, superClass) {
    if (superClass) {
      ctor.prototype = Object.create(superClass.prototype);
    }
    ctor.prototype.constructor = ctor;
  }

  function Iterable(value) {
      return isIterable(value) ? value : Seq(value);
    }


  createClass(KeyedIterable, Iterable);
    function KeyedIterable(value) {
      return isKeyed(value) ? value : KeyedSeq(value);
    }


  createClass(IndexedIterable, Iterable);
    function IndexedIterable(value) {
      return isIndexed(value) ? value : IndexedSeq(value);
    }


  createClass(SetIterable, Iterable);
    function SetIterable(value) {
      return isIterable(value) && !isAssociative(value) ? value : SetSeq(value);
    }



  function isIterable(maybeIterable) {
    return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]);
  }

  function isKeyed(maybeKeyed) {
    return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]);
  }

  function isIndexed(maybeIndexed) {
    return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]);
  }

  function isAssociative(maybeAssociative) {
    return isKeyed(maybeAssociative) || isIndexed(maybeAssociative);
  }

  function isOrdered(maybeOrdered) {
    return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]);
  }

  Iterable.isIterable = isIterable;
  Iterable.isKeyed = isKeyed;
  Iterable.isIndexed = isIndexed;
  Iterable.isAssociative = isAssociative;
  Iterable.isOrdered = isOrdered;

  Iterable.Keyed = KeyedIterable;
  Iterable.Indexed = IndexedIterable;
  Iterable.Set = SetIterable;


  var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';

  // Used for setting prototype methods that IE8 chokes on.
  var DELETE = 'delete';

  // Constants describing the size of trie nodes.
  var SHIFT = 5; // Resulted in best performance after ______?
  var SIZE = 1 << SHIFT;
  var MASK = SIZE - 1;

  // A consistent shared value representing "not set" which equals nothing other
  // than itself, and nothing that could be provided externally.
  var NOT_SET = {};

  // Boolean references, Rough equivalent of `bool &`.
  var CHANGE_LENGTH = { value: false };
  var DID_ALTER = { value: false };

  function MakeRef(ref) {
    ref.value = false;
    return ref;
  }

  function SetRef(ref) {
    ref && (ref.value = true);
  }

  // A function which returns a value representing an "owner" for transient writes
  // to tries. The return value will only ever equal itself, and will not equal
  // the return of any subsequent call of this function.
  function OwnerID() {}

  // http://jsperf.com/copy-array-inline
  function arrCopy(arr, offset) {
    offset = offset || 0;
    var len = Math.max(0, arr.length - offset);
    var newArr = new Array(len);
    for (var ii = 0; ii < len; ii++) {
      newArr[ii] = arr[ii + offset];
    }
    return newArr;
  }

  function ensureSize(iter) {
    if (iter.size === undefined) {
      iter.size = iter.__iterate(returnTrue);
    }
    return iter.size;
  }

  function wrapIndex(iter, index) {
    // This implements "is array index" which the ECMAString spec defines as:
    //
    //     A String property name P is an array index if and only if
    //     ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal
    //     to 2^32−1.
    //
    // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects
    if (typeof index !== 'number') {
      var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32
      if ('' + uint32Index !== index || uint32Index === 4294967295) {
        return NaN;
      }
      index = uint32Index;
    }
    return index < 0 ? ensureSize(iter) + index : index;
  }

  function returnTrue() {
    return true;
  }

  function wholeSlice(begin, end, size) {
    return (begin === 0 || (size !== undefined && begin <= -size)) &&
      (end === undefined || (size !== undefined && end >= size));
  }

  function resolveBegin(begin, size) {
    return resolveIndex(begin, size, 0);
  }

  function resolveEnd(end, size) {
    return resolveIndex(end, size, size);
  }

  function resolveIndex(index, size, defaultIndex) {
    return index === undefined ?
      defaultIndex :
      index < 0 ?
        Math.max(0, size + index) :
        size === undefined ?
          index :
          Math.min(size, index);
  }

  /* global Symbol */

  var ITERATE_KEYS = 0;
  var ITERATE_VALUES = 1;
  var ITERATE_ENTRIES = 2;

  var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator;
  var FAUX_ITERATOR_SYMBOL = '@@iterator';

  var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL;


  function Iterator(next) {
      this.next = next;
    }

    Iterator.prototype.toString = function() {
      return '[Iterator]';
    };


  Iterator.KEYS = ITERATE_KEYS;
  Iterator.VALUES = ITERATE_VALUES;
  Iterator.ENTRIES = ITERATE_ENTRIES;

  Iterator.prototype.inspect =
  Iterator.prototype.toSource = function () { return this.toString(); }
  Iterator.prototype[ITERATOR_SYMBOL] = function () {
    return this;
  };


  function iteratorValue(type, k, v, iteratorResult) {
    var value = type === 0 ? k : type === 1 ? v : [k, v];
    iteratorResult ? (iteratorResult.value = value) : (iteratorResult = {
      value: value, done: false
    });
    return iteratorResult;
  }

  function iteratorDone() {
    return { value: undefined, done: true };
  }

  function hasIterator(maybeIterable) {
    return !!getIteratorFn(maybeIterable);
  }

  function isIterator(maybeIterator) {
    return maybeIterator && typeof maybeIterator.next === 'function';
  }

  function getIterator(iterable) {
    var iteratorFn = getIteratorFn(iterable);
    return iteratorFn && iteratorFn.call(iterable);
  }

  function getIteratorFn(iterable) {
    var iteratorFn = iterable && (
      (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) ||
      iterable[FAUX_ITERATOR_SYMBOL]
    );
    if (typeof iteratorFn === 'function') {
      return iteratorFn;
    }
  }

  function isArrayLike(value) {
    return value && typeof value.length === 'number';
  }

  createClass(Seq, Iterable);
    function Seq(value) {
      return value === null || value === undefined ? emptySequence() :
        isIterable(value) ? value.toSeq() : seqFromValue(value);
    }

    Seq.of = function(/*...values*/) {
      return Seq(arguments);
    };

    Seq.prototype.toSeq = function() {
      return this;
    };

    Seq.prototype.toString = function() {
      return this.__toString('Seq {', '}');
    };

    Seq.prototype.cacheResult = function() {
      if (!this._cache && this.__iterateUncached) {
        this._cache = this.entrySeq().toArray();
        this.size = this._cache.length;
      }
      return this;
    };

    // abstract __iterateUncached(fn, reverse)

    Seq.prototype.__iterate = function(fn, reverse) {
      return seqIterate(this, fn, reverse, true);
    };

    // abstract __iteratorUncached(type, reverse)

    Seq.prototype.__iterator = function(type, reverse) {
      return seqIterator(this, type, reverse, true);
    };



  createClass(KeyedSeq, Seq);
    function KeyedSeq(value) {
      return value === null || value === undefined ?
        emptySequence().toKeyedSeq() :
        isIterable(value) ?
          (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) :
          keyedSeqFromValue(value);
    }

    KeyedSeq.prototype.toKeyedSeq = function() {
      return this;
    };



  createClass(IndexedSeq, Seq);
    function IndexedSeq(value) {
      return value === null || value === undefined ? emptySequence() :
        !isIterable(value) ? indexedSeqFromValue(value) :
        isKeyed(value) ? value.entrySeq() : value.toIndexedSeq();
    }

    IndexedSeq.of = function(/*...values*/) {
      return IndexedSeq(arguments);
    };

    IndexedSeq.prototype.toIndexedSeq = function() {
      return this;
    };

    IndexedSeq.prototype.toString = function() {
      return this.__toString('Seq [', ']');
    };

    IndexedSeq.prototype.__iterate = function(fn, reverse) {
      return seqIterate(this, fn, reverse, false);
    };

    IndexedSeq.prototype.__iterator = function(type, reverse) {
      return seqIterator(this, type, reverse, false);
    };



  createClass(SetSeq, Seq);
    function SetSeq(value) {
      return (
        value === null || value === undefined ? emptySequence() :
        !isIterable(value) ? indexedSeqFromValue(value) :
        isKeyed(value) ? value.entrySeq() : value
      ).toSetSeq();
    }

    SetSeq.of = function(/*...values*/) {
      return SetSeq(arguments);
    };

    SetSeq.prototype.toSetSeq = function() {
      return this;
    };



  Seq.isSeq = isSeq;
  Seq.Keyed = KeyedSeq;
  Seq.Set = SetSeq;
  Seq.Indexed = IndexedSeq;

  var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@';

  Seq.prototype[IS_SEQ_SENTINEL] = true;



  createClass(ArraySeq, IndexedSeq);
    function ArraySeq(array) {
      this._array = array;
      this.size = array.length;
    }

    ArraySeq.prototype.get = function(index, notSetValue) {
      return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue;
    };

    ArraySeq.prototype.__iterate = function(fn, reverse) {
      var array = this._array;
      var maxIndex = array.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    ArraySeq.prototype.__iterator = function(type, reverse) {
      var array = this._array;
      var maxIndex = array.length - 1;
      var ii = 0;
      return new Iterator(function()
        {return ii > maxIndex ?
          iteratorDone() :
          iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])}
      );
    };



  createClass(ObjectSeq, KeyedSeq);
    function ObjectSeq(object) {
      var keys = Object.keys(object);
      this._object = object;
      this._keys = keys;
      this.size = keys.length;
    }

    ObjectSeq.prototype.get = function(key, notSetValue) {
      if (notSetValue !== undefined && !this.has(key)) {
        return notSetValue;
      }
      return this._object[key];
    };

    ObjectSeq.prototype.has = function(key) {
      return this._object.hasOwnProperty(key);
    };

    ObjectSeq.prototype.__iterate = function(fn, reverse) {
      var object = this._object;
      var keys = this._keys;
      var maxIndex = keys.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        var key = keys[reverse ? maxIndex - ii : ii];
        if (fn(object[key], key, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    ObjectSeq.prototype.__iterator = function(type, reverse) {
      var object = this._object;
      var keys = this._keys;
      var maxIndex = keys.length - 1;
      var ii = 0;
      return new Iterator(function()  {
        var key = keys[reverse ? maxIndex - ii : ii];
        return ii++ > maxIndex ?
          iteratorDone() :
          iteratorValue(type, key, object[key]);
      });
    };

  ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true;


  createClass(IterableSeq, IndexedSeq);
    function IterableSeq(iterable) {
      this._iterable = iterable;
      this.size = iterable.length || iterable.size;
    }

    IterableSeq.prototype.__iterateUncached = function(fn, reverse) {
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterable = this._iterable;
      var iterator = getIterator(iterable);
      var iterations = 0;
      if (isIterator(iterator)) {
        var step;
        while (!(step = iterator.next()).done) {
          if (fn(step.value, iterations++, this) === false) {
            break;
          }
        }
      }
      return iterations;
    };

    IterableSeq.prototype.__iteratorUncached = function(type, reverse) {
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterable = this._iterable;
      var iterator = getIterator(iterable);
      if (!isIterator(iterator)) {
        return new Iterator(iteratorDone);
      }
      var iterations = 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step : iteratorValue(type, iterations++, step.value);
      });
    };



  createClass(IteratorSeq, IndexedSeq);
    function IteratorSeq(iterator) {
      this._iterator = iterator;
      this._iteratorCache = [];
    }

    IteratorSeq.prototype.__iterateUncached = function(fn, reverse) {
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterator = this._iterator;
      var cache = this._iteratorCache;
      var iterations = 0;
      while (iterations < cache.length) {
        if (fn(cache[iterations], iterations++, this) === false) {
          return iterations;
        }
      }
      var step;
      while (!(step = iterator.next()).done) {
        var val = step.value;
        cache[iterations] = val;
        if (fn(val, iterations++, this) === false) {
          break;
        }
      }
      return iterations;
    };

    IteratorSeq.prototype.__iteratorUncached = function(type, reverse) {
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = this._iterator;
      var cache = this._iteratorCache;
      var iterations = 0;
      return new Iterator(function()  {
        if (iterations >= cache.length) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          cache[iterations] = step.value;
        }
        return iteratorValue(type, iterations, cache[iterations++]);
      });
    };




  // # pragma Helper functions

  function isSeq(maybeSeq) {
    return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]);
  }

  var EMPTY_SEQ;

  function emptySequence() {
    return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([]));
  }

  function keyedSeqFromValue(value) {
    var seq =
      Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() :
      isIterator(value) ? new IteratorSeq(value).fromEntrySeq() :
      hasIterator(value) ? new IterableSeq(value).fromEntrySeq() :
      typeof value === 'object' ? new ObjectSeq(value) :
      undefined;
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of [k, v] entries, '+
        'or keyed object: ' + value
      );
    }
    return seq;
  }

  function indexedSeqFromValue(value) {
    var seq = maybeIndexedSeqFromValue(value);
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of values: ' + value
      );
    }
    return seq;
  }

  function seqFromValue(value) {
    var seq = maybeIndexedSeqFromValue(value) ||
      (typeof value === 'object' && new ObjectSeq(value));
    if (!seq) {
      throw new TypeError(
        'Expected Array or iterable object of values, or keyed object: ' + value
      );
    }
    return seq;
  }

  function maybeIndexedSeqFromValue(value) {
    return (
      isArrayLike(value) ? new ArraySeq(value) :
      isIterator(value) ? new IteratorSeq(value) :
      hasIterator(value) ? new IterableSeq(value) :
      undefined
    );
  }

  function seqIterate(seq, fn, reverse, useKeys) {
    var cache = seq._cache;
    if (cache) {
      var maxIndex = cache.length - 1;
      for (var ii = 0; ii <= maxIndex; ii++) {
        var entry = cache[reverse ? maxIndex - ii : ii];
        if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) {
          return ii + 1;
        }
      }
      return ii;
    }
    return seq.__iterateUncached(fn, reverse);
  }

  function seqIterator(seq, type, reverse, useKeys) {
    var cache = seq._cache;
    if (cache) {
      var maxIndex = cache.length - 1;
      var ii = 0;
      return new Iterator(function()  {
        var entry = cache[reverse ? maxIndex - ii : ii];
        return ii++ > maxIndex ?
          iteratorDone() :
          iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]);
      });
    }
    return seq.__iteratorUncached(type, reverse);
  }

  function fromJS(json, converter) {
    return converter ?
      fromJSWith(converter, json, '', {'': json}) :
      fromJSDefault(json);
  }

  function fromJSWith(converter, json, key, parentJSON) {
    if (Array.isArray(json)) {
      return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k)  {return fromJSWith(converter, v, k, json)}));
    }
    if (isPlainObj(json)) {
      return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k)  {return fromJSWith(converter, v, k, json)}));
    }
    return json;
  }

  function fromJSDefault(json) {
    if (Array.isArray(json)) {
      return IndexedSeq(json).map(fromJSDefault).toList();
    }
    if (isPlainObj(json)) {
      return KeyedSeq(json).map(fromJSDefault).toMap();
    }
    return json;
  }

  function isPlainObj(value) {
    return value && (value.constructor === Object || value.constructor === undefined);
  }

  /**
   * An extension of the "same-value" algorithm as [described for use by ES6 Map
   * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality)
   *
   * NaN is considered the same as NaN, however -0 and 0 are considered the same
   * value, which is different from the algorithm described by
   * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
   *
   * This is extended further to allow Objects to describe the values they
   * represent, by way of `valueOf` or `equals` (and `hashCode`).
   *
   * Note: because of this extension, the key equality of Immutable.Map and the
   * value equality of Immutable.Set will differ from ES6 Map and Set.
   *
   * ### Defining custom values
   *
   * The easiest way to describe the value an object represents is by implementing
   * `valueOf`. For example, `Date` represents a value by returning a unix
   * timestamp for `valueOf`:
   *
   *     var date1 = new Date(1234567890000); // Fri Feb 13 2009 ...
   *     var date2 = new Date(1234567890000);
   *     date1.valueOf(); // 1234567890000
   *     assert( date1 !== date2 );
   *     assert( Immutable.is( date1, date2 ) );
   *
   * Note: overriding `valueOf` may have other implications if you use this object
   * where JavaScript expects a primitive, such as implicit string coercion.
   *
   * For more complex types, especially collections, implementing `valueOf` may
   * not be performant. An alternative is to implement `equals` and `hashCode`.
   *
   * `equals` takes another object, presumably of similar type, and returns true
   * if the it is equal. Equality is symmetrical, so the same result should be
   * returned if this and the argument are flipped.
   *
   *     assert( a.equals(b) === b.equals(a) );
   *
   * `hashCode` returns a 32bit integer number representing the object which will
   * be used to determine how to store the value object in a Map or Set. You must
   * provide both or neither methods, one must not exist without the other.
   *
   * Also, an important relationship between these methods must be upheld: if two
   * values are equal, they *must* return the same hashCode. If the values are not
   * equal, they might have the same hashCode; this is called a hash collision,
   * and while undesirable for performance reasons, it is acceptable.
   *
   *     if (a.equals(b)) {
   *       assert( a.hashCode() === b.hashCode() );
   *     }
   *
   * All Immutable collections implement `equals` and `hashCode`.
   *
   */
  function is(valueA, valueB) {
    if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
      return true;
    }
    if (!valueA || !valueB) {
      return false;
    }
    if (typeof valueA.valueOf === 'function' &&
        typeof valueB.valueOf === 'function') {
      valueA = valueA.valueOf();
      valueB = valueB.valueOf();
      if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) {
        return true;
      }
      if (!valueA || !valueB) {
        return false;
      }
    }
    if (typeof valueA.equals === 'function' &&
        typeof valueB.equals === 'function' &&
        valueA.equals(valueB)) {
      return true;
    }
    return false;
  }

  function deepEqual(a, b) {
    if (a === b) {
      return true;
    }

    if (
      !isIterable(b) ||
      a.size !== undefined && b.size !== undefined && a.size !== b.size ||
      a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash ||
      isKeyed(a) !== isKeyed(b) ||
      isIndexed(a) !== isIndexed(b) ||
      isOrdered(a) !== isOrdered(b)
    ) {
      return false;
    }

    if (a.size === 0 && b.size === 0) {
      return true;
    }

    var notAssociative = !isAssociative(a);

    if (isOrdered(a)) {
      var entries = a.entries();
      return b.every(function(v, k)  {
        var entry = entries.next().value;
        return entry && is(entry[1], v) && (notAssociative || is(entry[0], k));
      }) && entries.next().done;
    }

    var flipped = false;

    if (a.size === undefined) {
      if (b.size === undefined) {
        if (typeof a.cacheResult === 'function') {
          a.cacheResult();
        }
      } else {
        flipped = true;
        var _ = a;
        a = b;
        b = _;
      }
    }

    var allEqual = true;
    var bSize = b.__iterate(function(v, k)  {
      if (notAssociative ? !a.has(v) :
          flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) {
        allEqual = false;
        return false;
      }
    });

    return allEqual && a.size === bSize;
  }

  createClass(Repeat, IndexedSeq);

    function Repeat(value, times) {
      if (!(this instanceof Repeat)) {
        return new Repeat(value, times);
      }
      this._value = value;
      this.size = times === undefined ? Infinity : Math.max(0, times);
      if (this.size === 0) {
        if (EMPTY_REPEAT) {
          return EMPTY_REPEAT;
        }
        EMPTY_REPEAT = this;
      }
    }

    Repeat.prototype.toString = function() {
      if (this.size === 0) {
        return 'Repeat []';
      }
      return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]';
    };

    Repeat.prototype.get = function(index, notSetValue) {
      return this.has(index) ? this._value : notSetValue;
    };

    Repeat.prototype.includes = function(searchValue) {
      return is(this._value, searchValue);
    };

    Repeat.prototype.slice = function(begin, end) {
      var size = this.size;
      return wholeSlice(begin, end, size) ? this :
        new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size));
    };

    Repeat.prototype.reverse = function() {
      return this;
    };

    Repeat.prototype.indexOf = function(searchValue) {
      if (is(this._value, searchValue)) {
        return 0;
      }
      return -1;
    };

    Repeat.prototype.lastIndexOf = function(searchValue) {
      if (is(this._value, searchValue)) {
        return this.size;
      }
      return -1;
    };

    Repeat.prototype.__iterate = function(fn, reverse) {
      for (var ii = 0; ii < this.size; ii++) {
        if (fn(this._value, ii, this) === false) {
          return ii + 1;
        }
      }
      return ii;
    };

    Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this;
      var ii = 0;
      return new Iterator(function()
        {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()}
      );
    };

    Repeat.prototype.equals = function(other) {
      return other instanceof Repeat ?
        is(this._value, other._value) :
        deepEqual(other);
    };


  var EMPTY_REPEAT;

  function invariant(condition, error) {
    if (!condition) throw new Error(error);
  }

  createClass(Range, IndexedSeq);

    function Range(start, end, step) {
      if (!(this instanceof Range)) {
        return new Range(start, end, step);
      }
      invariant(step !== 0, 'Cannot step a Range by 0');
      start = start || 0;
      if (end === undefined) {
        end = Infinity;
      }
      step = step === undefined ? 1 : Math.abs(step);
      if (end < start) {
        step = -step;
      }
      this._start = start;
      this._end = end;
      this._step = step;
      this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1);
      if (this.size === 0) {
        if (EMPTY_RANGE) {
          return EMPTY_RANGE;
        }
        EMPTY_RANGE = this;
      }
    }

    Range.prototype.toString = function() {
      if (this.size === 0) {
        return 'Range []';
      }
      return 'Range [ ' +
        this._start + '...' + this._end +
        (this._step !== 1 ? ' by ' + this._step : '') +
      ' ]';
    };

    Range.prototype.get = function(index, notSetValue) {
      return this.has(index) ?
        this._start + wrapIndex(this, index) * this._step :
        notSetValue;
    };

    Range.prototype.includes = function(searchValue) {
      var possibleIndex = (searchValue - this._start) / this._step;
      return possibleIndex >= 0 &&
        possibleIndex < this.size &&
        possibleIndex === Math.floor(possibleIndex);
    };

    Range.prototype.slice = function(begin, end) {
      if (wholeSlice(begin, end, this.size)) {
        return this;
      }
      begin = resolveBegin(begin, this.size);
      end = resolveEnd(end, this.size);
      if (end <= begin) {
        return new Range(0, 0);
      }
      return new Range(this.get(begin, this._end), this.get(end, this._end), this._step);
    };

    Range.prototype.indexOf = function(searchValue) {
      var offsetValue = searchValue - this._start;
      if (offsetValue % this._step === 0) {
        var index = offsetValue / this._step;
        if (index >= 0 && index < this.size) {
          return index
        }
      }
      return -1;
    };

    Range.prototype.lastIndexOf = function(searchValue) {
      return this.indexOf(searchValue);
    };

    Range.prototype.__iterate = function(fn, reverse) {
      var maxIndex = this.size - 1;
      var step = this._step;
      var value = reverse ? this._start + maxIndex * step : this._start;
      for (var ii = 0; ii <= maxIndex; ii++) {
        if (fn(value, ii, this) === false) {
          return ii + 1;
        }
        value += reverse ? -step : step;
      }
      return ii;
    };

    Range.prototype.__iterator = function(type, reverse) {
      var maxIndex = this.size - 1;
      var step = this._step;
      var value = reverse ? this._start + maxIndex * step : this._start;
      var ii = 0;
      return new Iterator(function()  {
        var v = value;
        value += reverse ? -step : step;
        return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v);
      });
    };

    Range.prototype.equals = function(other) {
      return other instanceof Range ?
        this._start === other._start &&
        this._end === other._end &&
        this._step === other._step :
        deepEqual(this, other);
    };


  var EMPTY_RANGE;

  createClass(Collection, Iterable);
    function Collection() {
      throw TypeError('Abstract');
    }


  createClass(KeyedCollection, Collection);function KeyedCollection() {}

  createClass(IndexedCollection, Collection);function IndexedCollection() {}

  createClass(SetCollection, Collection);function SetCollection() {}


  Collection.Keyed = KeyedCollection;
  Collection.Indexed = IndexedCollection;
  Collection.Set = SetCollection;

  var imul =
    typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ?
    Math.imul :
    function imul(a, b) {
      a = a | 0; // int
      b = b | 0; // int
      var c = a & 0xffff;
      var d = b & 0xffff;
      // Shift by 0 fixes the sign on the high part.
      return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int
    };

  // v8 has an optimization for storing 31-bit signed numbers.
  // Values which have either 00 or 11 as the high order bits qualify.
  // This function drops the highest order bit in a signed number, maintaining
  // the sign bit.
  function smi(i32) {
    return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF);
  }

  function hash(o) {
    if (o === false || o === null || o === undefined) {
      return 0;
    }
    if (typeof o.valueOf === 'function') {
      o = o.valueOf();
      if (o === false || o === null || o === undefined) {
        return 0;
      }
    }
    if (o === true) {
      return 1;
    }
    var type = typeof o;
    if (type === 'number') {
      if (o !== o || o === Infinity) {
        return 0;
      }
      var h = o | 0;
      if (h !== o) {
        h ^= o * 0xFFFFFFFF;
      }
      while (o > 0xFFFFFFFF) {
        o /= 0xFFFFFFFF;
        h ^= o;
      }
      return smi(h);
    }
    if (type === 'string') {
      return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o);
    }
    if (typeof o.hashCode === 'function') {
      return o.hashCode();
    }
    if (type === 'object') {
      return hashJSObj(o);
    }
    if (typeof o.toString === 'function') {
      return hashString(o.toString());
    }
    throw new Error('Value type ' + type + ' cannot be hashed.');
  }

  function cachedHashString(string) {
    var hash = stringHashCache[string];
    if (hash === undefined) {
      hash = hashString(string);
      if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) {
        STRING_HASH_CACHE_SIZE = 0;
        stringHashCache = {};
      }
      STRING_HASH_CACHE_SIZE++;
      stringHashCache[string] = hash;
    }
    return hash;
  }

  // http://jsperf.com/hashing-strings
  function hashString(string) {
    // This is the hash from JVM
    // The hash code for a string is computed as
    // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1],
    // where s[i] is the ith character of the string and n is the length of
    // the string. We "mod" the result to make it between 0 (inclusive) and 2^31
    // (exclusive) by dropping high bits.
    var hash = 0;
    for (var ii = 0; ii < string.length; ii++) {
      hash = 31 * hash + string.charCodeAt(ii) | 0;
    }
    return smi(hash);
  }

  function hashJSObj(obj) {
    var hash;
    if (usingWeakMap) {
      hash = weakMap.get(obj);
      if (hash !== undefined) {
        return hash;
      }
    }

    hash = obj[UID_HASH_KEY];
    if (hash !== undefined) {
      return hash;
    }

    if (!canDefineProperty) {
      hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY];
      if (hash !== undefined) {
        return hash;
      }

      hash = getIENodeHash(obj);
      if (hash !== undefined) {
        return hash;
      }
    }

    hash = ++objHashUID;
    if (objHashUID & 0x40000000) {
      objHashUID = 0;
    }

    if (usingWeakMap) {
      weakMap.set(obj, hash);
    } else if (isExtensible !== undefined && isExtensible(obj) === false) {
      throw new Error('Non-extensible objects are not allowed as keys.');
    } else if (canDefineProperty) {
      Object.defineProperty(obj, UID_HASH_KEY, {
        'enumerable': false,
        'configurable': false,
        'writable': false,
        'value': hash
      });
    } else if (obj.propertyIsEnumerable !== undefined &&
               obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) {
      // Since we can't define a non-enumerable property on the object
      // we'll hijack one of the less-used non-enumerable properties to
      // save our hash on it. Since this is a function it will not show up in
      // `JSON.stringify` which is what we want.
      obj.propertyIsEnumerable = function() {
        return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments);
      };
      obj.propertyIsEnumerable[UID_HASH_KEY] = hash;
    } else if (obj.nodeType !== undefined) {
      // At this point we couldn't get the IE `uniqueID` to use as a hash
      // and we couldn't use a non-enumerable property to exploit the
      // dontEnum bug so we simply add the `UID_HASH_KEY` on the node
      // itself.
      obj[UID_HASH_KEY] = hash;
    } else {
      throw new Error('Unable to set a non-enumerable property on object.');
    }

    return hash;
  }

  // Get references to ES5 object methods.
  var isExtensible = Object.isExtensible;

  // True if Object.defineProperty works as expected. IE8 fails this test.
  var canDefineProperty = (function() {
    try {
      Object.defineProperty({}, '@', {});
      return true;
    } catch (e) {
      return false;
    }
  }());

  // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it
  // and avoid memory leaks from the IE cloneNode bug.
  function getIENodeHash(node) {
    if (node && node.nodeType > 0) {
      switch (node.nodeType) {
        case 1: // Element
          return node.uniqueID;
        case 9: // Document
          return node.documentElement && node.documentElement.uniqueID;
      }
    }
  }

  // If possible, use a WeakMap.
  var usingWeakMap = typeof WeakMap === 'function';
  var weakMap;
  if (usingWeakMap) {
    weakMap = new WeakMap();
  }

  var objHashUID = 0;

  var UID_HASH_KEY = '__immutablehash__';
  if (typeof Symbol === 'function') {
    UID_HASH_KEY = Symbol(UID_HASH_KEY);
  }

  var STRING_HASH_CACHE_MIN_STRLEN = 16;
  var STRING_HASH_CACHE_MAX_SIZE = 255;
  var STRING_HASH_CACHE_SIZE = 0;
  var stringHashCache = {};

  function assertNotInfinite(size) {
    invariant(
      size !== Infinity,
      'Cannot perform this action with an infinite size.'
    );
  }

  createClass(Map, KeyedCollection);

    // @pragma Construction

    function Map(value) {
      return value === null || value === undefined ? emptyMap() :
        isMap(value) && !isOrdered(value) ? value :
        emptyMap().withMutations(function(map ) {
          var iter = KeyedIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v, k)  {return map.set(k, v)});
        });
    }

    Map.of = function() {var keyValues = SLICE$0.call(arguments, 0);
      return emptyMap().withMutations(function(map ) {
        for (var i = 0; i < keyValues.length; i += 2) {
          if (i + 1 >= keyValues.length) {
            throw new Error('Missing value for key: ' + keyValues[i]);
          }
          map.set(keyValues[i], keyValues[i + 1]);
        }
      });
    };

    Map.prototype.toString = function() {
      return this.__toString('Map {', '}');
    };

    // @pragma Access

    Map.prototype.get = function(k, notSetValue) {
      return this._root ?
        this._root.get(0, undefined, k, notSetValue) :
        notSetValue;
    };

    // @pragma Modification

    Map.prototype.set = function(k, v) {
      return updateMap(this, k, v);
    };

    Map.prototype.setIn = function(keyPath, v) {
      return this.updateIn(keyPath, NOT_SET, function()  {return v});
    };

    Map.prototype.remove = function(k) {
      return updateMap(this, k, NOT_SET);
    };

    Map.prototype.deleteIn = function(keyPath) {
      return this.updateIn(keyPath, function()  {return NOT_SET});
    };

    Map.prototype.update = function(k, notSetValue, updater) {
      return arguments.length === 1 ?
        k(this) :
        this.updateIn([k], notSetValue, updater);
    };

    Map.prototype.updateIn = function(keyPath, notSetValue, updater) {
      if (!updater) {
        updater = notSetValue;
        notSetValue = undefined;
      }
      var updatedValue = updateInDeepMap(
        this,
        forceIterator(keyPath),
        notSetValue,
        updater
      );
      return updatedValue === NOT_SET ? undefined : updatedValue;
    };

    Map.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._root = null;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyMap();
    };

    // @pragma Composition

    Map.prototype.merge = function(/*...iters*/) {
      return mergeIntoMapWith(this, undefined, arguments);
    };

    Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoMapWith(this, merger, iters);
    };

    Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
      return this.updateIn(
        keyPath,
        emptyMap(),
        function(m ) {return typeof m.merge === 'function' ?
          m.merge.apply(m, iters) :
          iters[iters.length - 1]}
      );
    };

    Map.prototype.mergeDeep = function(/*...iters*/) {
      return mergeIntoMapWith(this, deepMerger, arguments);
    };

    Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoMapWith(this, deepMergerWith(merger), iters);
    };

    Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1);
      return this.updateIn(
        keyPath,
        emptyMap(),
        function(m ) {return typeof m.mergeDeep === 'function' ?
          m.mergeDeep.apply(m, iters) :
          iters[iters.length - 1]}
      );
    };

    Map.prototype.sort = function(comparator) {
      // Late binding
      return OrderedMap(sortFactory(this, comparator));
    };

    Map.prototype.sortBy = function(mapper, comparator) {
      // Late binding
      return OrderedMap(sortFactory(this, comparator, mapper));
    };

    // @pragma Mutability

    Map.prototype.withMutations = function(fn) {
      var mutable = this.asMutable();
      fn(mutable);
      return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this;
    };

    Map.prototype.asMutable = function() {
      return this.__ownerID ? this : this.__ensureOwner(new OwnerID());
    };

    Map.prototype.asImmutable = function() {
      return this.__ensureOwner();
    };

    Map.prototype.wasAltered = function() {
      return this.__altered;
    };

    Map.prototype.__iterator = function(type, reverse) {
      return new MapIterator(this, type, reverse);
    };

    Map.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      this._root && this._root.iterate(function(entry ) {
        iterations++;
        return fn(entry[1], entry[0], this$0);
      }, reverse);
      return iterations;
    };

    Map.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        this.__altered = false;
        return this;
      }
      return makeMap(this.size, this._root, ownerID, this.__hash);
    };


  function isMap(maybeMap) {
    return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]);
  }

  Map.isMap = isMap;

  var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@';

  var MapPrototype = Map.prototype;
  MapPrototype[IS_MAP_SENTINEL] = true;
  MapPrototype[DELETE] = MapPrototype.remove;
  MapPrototype.removeIn = MapPrototype.deleteIn;


  // #pragma Trie Nodes



    function ArrayMapNode(ownerID, entries) {
      this.ownerID = ownerID;
      this.entries = entries;
    }

    ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      var entries = this.entries;
      for (var ii = 0, len = entries.length; ii < len; ii++) {
        if (is(key, entries[ii][0])) {
          return entries[ii][1];
        }
      }
      return notSetValue;
    };

    ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      var removed = value === NOT_SET;

      var entries = this.entries;
      var idx = 0;
      for (var len = entries.length; idx < len; idx++) {
        if (is(key, entries[idx][0])) {
          break;
        }
      }
      var exists = idx < len;

      if (exists ? entries[idx][1] === value : removed) {
        return this;
      }

      SetRef(didAlter);
      (removed || !exists) && SetRef(didChangeSize);

      if (removed && entries.length === 1) {
        return; // undefined
      }

      if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) {
        return createNodes(ownerID, entries, key, value);
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newEntries = isEditable ? entries : arrCopy(entries);

      if (exists) {
        if (removed) {
          idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
        } else {
          newEntries[idx] = [key, value];
        }
      } else {
        newEntries.push([key, value]);
      }

      if (isEditable) {
        this.entries = newEntries;
        return this;
      }

      return new ArrayMapNode(ownerID, newEntries);
    };




    function BitmapIndexedNode(ownerID, bitmap, nodes) {
      this.ownerID = ownerID;
      this.bitmap = bitmap;
      this.nodes = nodes;
    }

    BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK));
      var bitmap = this.bitmap;
      return (bitmap & bit) === 0 ? notSetValue :
        this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue);
    };

    BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var bit = 1 << keyHashFrag;
      var bitmap = this.bitmap;
      var exists = (bitmap & bit) !== 0;

      if (!exists && value === NOT_SET) {
        return this;
      }

      var idx = popCount(bitmap & (bit - 1));
      var nodes = this.nodes;
      var node = exists ? nodes[idx] : undefined;
      var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);

      if (newNode === node) {
        return this;
      }

      if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) {
        return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode);
      }

      if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) {
        return nodes[idx ^ 1];
      }

      if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) {
        return newNode;
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit;
      var newNodes = exists ? newNode ?
        setIn(nodes, idx, newNode, isEditable) :
        spliceOut(nodes, idx, isEditable) :
        spliceIn(nodes, idx, newNode, isEditable);

      if (isEditable) {
        this.bitmap = newBitmap;
        this.nodes = newNodes;
        return this;
      }

      return new BitmapIndexedNode(ownerID, newBitmap, newNodes);
    };




    function HashArrayMapNode(ownerID, count, nodes) {
      this.ownerID = ownerID;
      this.count = count;
      this.nodes = nodes;
    }

    HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var node = this.nodes[idx];
      return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue;
    };

    HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }
      var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;
      var removed = value === NOT_SET;
      var nodes = this.nodes;
      var node = nodes[idx];

      if (removed && !node) {
        return this;
      }

      var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter);
      if (newNode === node) {
        return this;
      }

      var newCount = this.count;
      if (!node) {
        newCount++;
      } else if (!newNode) {
        newCount--;
        if (newCount < MIN_HASH_ARRAY_MAP_SIZE) {
          return packNodes(ownerID, nodes, newCount, idx);
        }
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newNodes = setIn(nodes, idx, newNode, isEditable);

      if (isEditable) {
        this.count = newCount;
        this.nodes = newNodes;
        return this;
      }

      return new HashArrayMapNode(ownerID, newCount, newNodes);
    };




    function HashCollisionNode(ownerID, keyHash, entries) {
      this.ownerID = ownerID;
      this.keyHash = keyHash;
      this.entries = entries;
    }

    HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      var entries = this.entries;
      for (var ii = 0, len = entries.length; ii < len; ii++) {
        if (is(key, entries[ii][0])) {
          return entries[ii][1];
        }
      }
      return notSetValue;
    };

    HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      if (keyHash === undefined) {
        keyHash = hash(key);
      }

      var removed = value === NOT_SET;

      if (keyHash !== this.keyHash) {
        if (removed) {
          return this;
        }
        SetRef(didAlter);
        SetRef(didChangeSize);
        return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]);
      }

      var entries = this.entries;
      var idx = 0;
      for (var len = entries.length; idx < len; idx++) {
        if (is(key, entries[idx][0])) {
          break;
        }
      }
      var exists = idx < len;

      if (exists ? entries[idx][1] === value : removed) {
        return this;
      }

      SetRef(didAlter);
      (removed || !exists) && SetRef(didChangeSize);

      if (removed && len === 2) {
        return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]);
      }

      var isEditable = ownerID && ownerID === this.ownerID;
      var newEntries = isEditable ? entries : arrCopy(entries);

      if (exists) {
        if (removed) {
          idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop());
        } else {
          newEntries[idx] = [key, value];
        }
      } else {
        newEntries.push([key, value]);
      }

      if (isEditable) {
        this.entries = newEntries;
        return this;
      }

      return new HashCollisionNode(ownerID, this.keyHash, newEntries);
    };




    function ValueNode(ownerID, keyHash, entry) {
      this.ownerID = ownerID;
      this.keyHash = keyHash;
      this.entry = entry;
    }

    ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) {
      return is(key, this.entry[0]) ? this.entry[1] : notSetValue;
    };

    ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
      var removed = value === NOT_SET;
      var keyMatch = is(key, this.entry[0]);
      if (keyMatch ? value === this.entry[1] : removed) {
        return this;
      }

      SetRef(didAlter);

      if (removed) {
        SetRef(didChangeSize);
        return; // undefined
      }

      if (keyMatch) {
        if (ownerID && ownerID === this.ownerID) {
          this.entry[1] = value;
          return this;
        }
        return new ValueNode(ownerID, this.keyHash, [key, value]);
      }

      SetRef(didChangeSize);
      return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]);
    };



  // #pragma Iterators

  ArrayMapNode.prototype.iterate =
  HashCollisionNode.prototype.iterate = function (fn, reverse) {
    var entries = this.entries;
    for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) {
      if (fn(entries[reverse ? maxIndex - ii : ii]) === false) {
        return false;
      }
    }
  }

  BitmapIndexedNode.prototype.iterate =
  HashArrayMapNode.prototype.iterate = function (fn, reverse) {
    var nodes = this.nodes;
    for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) {
      var node = nodes[reverse ? maxIndex - ii : ii];
      if (node && node.iterate(fn, reverse) === false) {
        return false;
      }
    }
  }

  ValueNode.prototype.iterate = function (fn, reverse) {
    return fn(this.entry);
  }

  createClass(MapIterator, Iterator);

    function MapIterator(map, type, reverse) {
      this._type = type;
      this._reverse = reverse;
      this._stack = map._root && mapIteratorFrame(map._root);
    }

    MapIterator.prototype.next = function() {
      var type = this._type;
      var stack = this._stack;
      while (stack) {
        var node = stack.node;
        var index = stack.index++;
        var maxIndex;
        if (node.entry) {
          if (index === 0) {
            return mapIteratorValue(type, node.entry);
          }
        } else if (node.entries) {
          maxIndex = node.entries.length - 1;
          if (index <= maxIndex) {
            return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]);
          }
        } else {
          maxIndex = node.nodes.length - 1;
          if (index <= maxIndex) {
            var subNode = node.nodes[this._reverse ? maxIndex - index : index];
            if (subNode) {
              if (subNode.entry) {
                return mapIteratorValue(type, subNode.entry);
              }
              stack = this._stack = mapIteratorFrame(subNode, stack);
            }
            continue;
          }
        }
        stack = this._stack = this._stack.__prev;
      }
      return iteratorDone();
    };


  function mapIteratorValue(type, entry) {
    return iteratorValue(type, entry[0], entry[1]);
  }

  function mapIteratorFrame(node, prev) {
    return {
      node: node,
      index: 0,
      __prev: prev
    };
  }

  function makeMap(size, root, ownerID, hash) {
    var map = Object.create(MapPrototype);
    map.size = size;
    map._root = root;
    map.__ownerID = ownerID;
    map.__hash = hash;
    map.__altered = false;
    return map;
  }

  var EMPTY_MAP;
  function emptyMap() {
    return EMPTY_MAP || (EMPTY_MAP = makeMap(0));
  }

  function updateMap(map, k, v) {
    var newRoot;
    var newSize;
    if (!map._root) {
      if (v === NOT_SET) {
        return map;
      }
      newSize = 1;
      newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]);
    } else {
      var didChangeSize = MakeRef(CHANGE_LENGTH);
      var didAlter = MakeRef(DID_ALTER);
      newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter);
      if (!didAlter.value) {
        return map;
      }
      newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0);
    }
    if (map.__ownerID) {
      map.size = newSize;
      map._root = newRoot;
      map.__hash = undefined;
      map.__altered = true;
      return map;
    }
    return newRoot ? makeMap(newSize, newRoot) : emptyMap();
  }

  function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) {
    if (!node) {
      if (value === NOT_SET) {
        return node;
      }
      SetRef(didAlter);
      SetRef(didChangeSize);
      return new ValueNode(ownerID, keyHash, [key, value]);
    }
    return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter);
  }

  function isLeafNode(node) {
    return node.constructor === ValueNode || node.constructor === HashCollisionNode;
  }

  function mergeIntoNode(node, ownerID, shift, keyHash, entry) {
    if (node.keyHash === keyHash) {
      return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]);
    }

    var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK;
    var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK;

    var newNode;
    var nodes = idx1 === idx2 ?
      [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] :
      ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]);

    return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes);
  }

  function createNodes(ownerID, entries, key, value) {
    if (!ownerID) {
      ownerID = new OwnerID();
    }
    var node = new ValueNode(ownerID, hash(key), [key, value]);
    for (var ii = 0; ii < entries.length; ii++) {
      var entry = entries[ii];
      node = node.update(ownerID, 0, undefined, entry[0], entry[1]);
    }
    return node;
  }

  function packNodes(ownerID, nodes, count, excluding) {
    var bitmap = 0;
    var packedII = 0;
    var packedNodes = new Array(count);
    for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) {
      var node = nodes[ii];
      if (node !== undefined && ii !== excluding) {
        bitmap |= bit;
        packedNodes[packedII++] = node;
      }
    }
    return new BitmapIndexedNode(ownerID, bitmap, packedNodes);
  }

  function expandNodes(ownerID, nodes, bitmap, including, node) {
    var count = 0;
    var expandedNodes = new Array(SIZE);
    for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) {
      expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined;
    }
    expandedNodes[including] = node;
    return new HashArrayMapNode(ownerID, count + 1, expandedNodes);
  }

  function mergeIntoMapWith(map, merger, iterables) {
    var iters = [];
    for (var ii = 0; ii < iterables.length; ii++) {
      var value = iterables[ii];
      var iter = KeyedIterable(value);
      if (!isIterable(value)) {
        iter = iter.map(function(v ) {return fromJS(v)});
      }
      iters.push(iter);
    }
    return mergeIntoCollectionWith(map, merger, iters);
  }

  function deepMerger(existing, value, key) {
    return existing && existing.mergeDeep && isIterable(value) ?
      existing.mergeDeep(value) :
      is(existing, value) ? existing : value;
  }

  function deepMergerWith(merger) {
    return function(existing, value, key)  {
      if (existing && existing.mergeDeepWith && isIterable(value)) {
        return existing.mergeDeepWith(merger, value);
      }
      var nextValue = merger(existing, value, key);
      return is(existing, nextValue) ? existing : nextValue;
    };
  }

  function mergeIntoCollectionWith(collection, merger, iters) {
    iters = iters.filter(function(x ) {return x.size !== 0});
    if (iters.length === 0) {
      return collection;
    }
    if (collection.size === 0 && !collection.__ownerID && iters.length === 1) {
      return collection.constructor(iters[0]);
    }
    return collection.withMutations(function(collection ) {
      var mergeIntoMap = merger ?
        function(value, key)  {
          collection.update(key, NOT_SET, function(existing )
            {return existing === NOT_SET ? value : merger(existing, value, key)}
          );
        } :
        function(value, key)  {
          collection.set(key, value);
        }
      for (var ii = 0; ii < iters.length; ii++) {
        iters[ii].forEach(mergeIntoMap);
      }
    });
  }

  function updateInDeepMap(existing, keyPathIter, notSetValue, updater) {
    var isNotSet = existing === NOT_SET;
    var step = keyPathIter.next();
    if (step.done) {
      var existingValue = isNotSet ? notSetValue : existing;
      var newValue = updater(existingValue);
      return newValue === existingValue ? existing : newValue;
    }
    invariant(
      isNotSet || (existing && existing.set),
      'invalid keyPath'
    );
    var key = step.value;
    var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET);
    var nextUpdated = updateInDeepMap(
      nextExisting,
      keyPathIter,
      notSetValue,
      updater
    );
    return nextUpdated === nextExisting ? existing :
      nextUpdated === NOT_SET ? existing.remove(key) :
      (isNotSet ? emptyMap() : existing).set(key, nextUpdated);
  }

  function popCount(x) {
    x = x - ((x >> 1) & 0x55555555);
    x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
    x = (x + (x >> 4)) & 0x0f0f0f0f;
    x = x + (x >> 8);
    x = x + (x >> 16);
    return x & 0x7f;
  }

  function setIn(array, idx, val, canEdit) {
    var newArray = canEdit ? array : arrCopy(array);
    newArray[idx] = val;
    return newArray;
  }

  function spliceIn(array, idx, val, canEdit) {
    var newLen = array.length + 1;
    if (canEdit && idx + 1 === newLen) {
      array[idx] = val;
      return array;
    }
    var newArray = new Array(newLen);
    var after = 0;
    for (var ii = 0; ii < newLen; ii++) {
      if (ii === idx) {
        newArray[ii] = val;
        after = -1;
      } else {
        newArray[ii] = array[ii + after];
      }
    }
    return newArray;
  }

  function spliceOut(array, idx, canEdit) {
    var newLen = array.length - 1;
    if (canEdit && idx === newLen) {
      array.pop();
      return array;
    }
    var newArray = new Array(newLen);
    var after = 0;
    for (var ii = 0; ii < newLen; ii++) {
      if (ii === idx) {
        after = 1;
      }
      newArray[ii] = array[ii + after];
    }
    return newArray;
  }

  var MAX_ARRAY_MAP_SIZE = SIZE / 4;
  var MAX_BITMAP_INDEXED_SIZE = SIZE / 2;
  var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4;

  createClass(List, IndexedCollection);

    // @pragma Construction

    function List(value) {
      var empty = emptyList();
      if (value === null || value === undefined) {
        return empty;
      }
      if (isList(value)) {
        return value;
      }
      var iter = IndexedIterable(value);
      var size = iter.size;
      if (size === 0) {
        return empty;
      }
      assertNotInfinite(size);
      if (size > 0 && size < SIZE) {
        return makeList(0, size, SHIFT, null, new VNode(iter.toArray()));
      }
      return empty.withMutations(function(list ) {
        list.setSize(size);
        iter.forEach(function(v, i)  {return list.set(i, v)});
      });
    }

    List.of = function(/*...values*/) {
      return this(arguments);
    };

    List.prototype.toString = function() {
      return this.__toString('List [', ']');
    };

    // @pragma Access

    List.prototype.get = function(index, notSetValue) {
      index = wrapIndex(this, index);
      if (index >= 0 && index < this.size) {
        index += this._origin;
        var node = listNodeFor(this, index);
        return node && node.array[index & MASK];
      }
      return notSetValue;
    };

    // @pragma Modification

    List.prototype.set = function(index, value) {
      return updateList(this, index, value);
    };

    List.prototype.remove = function(index) {
      return !this.has(index) ? this :
        index === 0 ? this.shift() :
        index === this.size - 1 ? this.pop() :
        this.splice(index, 1);
    };

    List.prototype.insert = function(index, value) {
      return this.splice(index, 0, value);
    };

    List.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = this._origin = this._capacity = 0;
        this._level = SHIFT;
        this._root = this._tail = null;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyList();
    };

    List.prototype.push = function(/*...values*/) {
      var values = arguments;
      var oldSize = this.size;
      return this.withMutations(function(list ) {
        setListBounds(list, 0, oldSize + values.length);
        for (var ii = 0; ii < values.length; ii++) {
          list.set(oldSize + ii, values[ii]);
        }
      });
    };

    List.prototype.pop = function() {
      return setListBounds(this, 0, -1);
    };

    List.prototype.unshift = function(/*...values*/) {
      var values = arguments;
      return this.withMutations(function(list ) {
        setListBounds(list, -values.length);
        for (var ii = 0; ii < values.length; ii++) {
          list.set(ii, values[ii]);
        }
      });
    };

    List.prototype.shift = function() {
      return setListBounds(this, 1);
    };

    // @pragma Composition

    List.prototype.merge = function(/*...iters*/) {
      return mergeIntoListWith(this, undefined, arguments);
    };

    List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoListWith(this, merger, iters);
    };

    List.prototype.mergeDeep = function(/*...iters*/) {
      return mergeIntoListWith(this, deepMerger, arguments);
    };

    List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return mergeIntoListWith(this, deepMergerWith(merger), iters);
    };

    List.prototype.setSize = function(size) {
      return setListBounds(this, 0, size);
    };

    // @pragma Iteration

    List.prototype.slice = function(begin, end) {
      var size = this.size;
      if (wholeSlice(begin, end, size)) {
        return this;
      }
      return setListBounds(
        this,
        resolveBegin(begin, size),
        resolveEnd(end, size)
      );
    };

    List.prototype.__iterator = function(type, reverse) {
      var index = 0;
      var values = iterateList(this, reverse);
      return new Iterator(function()  {
        var value = values();
        return value === DONE ?
          iteratorDone() :
          iteratorValue(type, index++, value);
      });
    };

    List.prototype.__iterate = function(fn, reverse) {
      var index = 0;
      var values = iterateList(this, reverse);
      var value;
      while ((value = values()) !== DONE) {
        if (fn(value, index++, this) === false) {
          break;
        }
      }
      return index;
    };

    List.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        return this;
      }
      return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash);
    };


  function isList(maybeList) {
    return !!(maybeList && maybeList[IS_LIST_SENTINEL]);
  }

  List.isList = isList;

  var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@';

  var ListPrototype = List.prototype;
  ListPrototype[IS_LIST_SENTINEL] = true;
  ListPrototype[DELETE] = ListPrototype.remove;
  ListPrototype.setIn = MapPrototype.setIn;
  ListPrototype.deleteIn =
  ListPrototype.removeIn = MapPrototype.removeIn;
  ListPrototype.update = MapPrototype.update;
  ListPrototype.updateIn = MapPrototype.updateIn;
  ListPrototype.mergeIn = MapPrototype.mergeIn;
  ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  ListPrototype.withMutations = MapPrototype.withMutations;
  ListPrototype.asMutable = MapPrototype.asMutable;
  ListPrototype.asImmutable = MapPrototype.asImmutable;
  ListPrototype.wasAltered = MapPrototype.wasAltered;



    function VNode(array, ownerID) {
      this.array = array;
      this.ownerID = ownerID;
    }

    // TODO: seems like these methods are very similar

    VNode.prototype.removeBefore = function(ownerID, level, index) {
      if (index === level ? 1 << level :  false || this.array.length === 0) {
        return this;
      }
      var originIndex = (index >>> level) & MASK;
      if (originIndex >= this.array.length) {
        return new VNode([], ownerID);
      }
      var removingFirst = originIndex === 0;
      var newChild;
      if (level > 0) {
        var oldChild = this.array[originIndex];
        newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index);
        if (newChild === oldChild && removingFirst) {
          return this;
        }
      }
      if (removingFirst && !newChild) {
        return this;
      }
      var editable = editableVNode(this, ownerID);
      if (!removingFirst) {
        for (var ii = 0; ii < originIndex; ii++) {
          editable.array[ii] = undefined;
        }
      }
      if (newChild) {
        editable.array[originIndex] = newChild;
      }
      return editable;
    };

    VNode.prototype.removeAfter = function(ownerID, level, index) {
      if (index === (level ? 1 << level : 0) || this.array.length === 0) {
        return this;
      }
      var sizeIndex = ((index - 1) >>> level) & MASK;
      if (sizeIndex >= this.array.length) {
        return this;
      }

      var newChild;
      if (level > 0) {
        var oldChild = this.array[sizeIndex];
        newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index);
        if (newChild === oldChild && sizeIndex === this.array.length - 1) {
          return this;
        }
      }

      var editable = editableVNode(this, ownerID);
      editable.array.splice(sizeIndex + 1);
      if (newChild) {
        editable.array[sizeIndex] = newChild;
      }
      return editable;
    };



  var DONE = {};

  function iterateList(list, reverse) {
    var left = list._origin;
    var right = list._capacity;
    var tailPos = getTailOffset(right);
    var tail = list._tail;

    return iterateNodeOrLeaf(list._root, list._level, 0);

    function iterateNodeOrLeaf(node, level, offset) {
      return level === 0 ?
        iterateLeaf(node, offset) :
        iterateNode(node, level, offset);
    }

    function iterateLeaf(node, offset) {
      var array = offset === tailPos ? tail && tail.array : node && node.array;
      var from = offset > left ? 0 : left - offset;
      var to = right - offset;
      if (to > SIZE) {
        to = SIZE;
      }
      return function()  {
        if (from === to) {
          return DONE;
        }
        var idx = reverse ? --to : from++;
        return array && array[idx];
      };
    }

    function iterateNode(node, level, offset) {
      var values;
      var array = node && node.array;
      var from = offset > left ? 0 : (left - offset) >> level;
      var to = ((right - offset) >> level) + 1;
      if (to > SIZE) {
        to = SIZE;
      }
      return function()  {
        do {
          if (values) {
            var value = values();
            if (value !== DONE) {
              return value;
            }
            values = null;
          }
          if (from === to) {
            return DONE;
          }
          var idx = reverse ? --to : from++;
          values = iterateNodeOrLeaf(
            array && array[idx], level - SHIFT, offset + (idx << level)
          );
        } while (true);
      };
    }
  }

  function makeList(origin, capacity, level, root, tail, ownerID, hash) {
    var list = Object.create(ListPrototype);
    list.size = capacity - origin;
    list._origin = origin;
    list._capacity = capacity;
    list._level = level;
    list._root = root;
    list._tail = tail;
    list.__ownerID = ownerID;
    list.__hash = hash;
    list.__altered = false;
    return list;
  }

  var EMPTY_LIST;
  function emptyList() {
    return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT));
  }

  function updateList(list, index, value) {
    index = wrapIndex(list, index);

    if (index !== index) {
      return list;
    }

    if (index >= list.size || index < 0) {
      return list.withMutations(function(list ) {
        index < 0 ?
          setListBounds(list, index).set(0, value) :
          setListBounds(list, 0, index + 1).set(index, value)
      });
    }

    index += list._origin;

    var newTail = list._tail;
    var newRoot = list._root;
    var didAlter = MakeRef(DID_ALTER);
    if (index >= getTailOffset(list._capacity)) {
      newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter);
    } else {
      newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter);
    }

    if (!didAlter.value) {
      return list;
    }

    if (list.__ownerID) {
      list._root = newRoot;
      list._tail = newTail;
      list.__hash = undefined;
      list.__altered = true;
      return list;
    }
    return makeList(list._origin, list._capacity, list._level, newRoot, newTail);
  }

  function updateVNode(node, ownerID, level, index, value, didAlter) {
    var idx = (index >>> level) & MASK;
    var nodeHas = node && idx < node.array.length;
    if (!nodeHas && value === undefined) {
      return node;
    }

    var newNode;

    if (level > 0) {
      var lowerNode = node && node.array[idx];
      var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter);
      if (newLowerNode === lowerNode) {
        return node;
      }
      newNode = editableVNode(node, ownerID);
      newNode.array[idx] = newLowerNode;
      return newNode;
    }

    if (nodeHas && node.array[idx] === value) {
      return node;
    }

    SetRef(didAlter);

    newNode = editableVNode(node, ownerID);
    if (value === undefined && idx === newNode.array.length - 1) {
      newNode.array.pop();
    } else {
      newNode.array[idx] = value;
    }
    return newNode;
  }

  function editableVNode(node, ownerID) {
    if (ownerID && node && ownerID === node.ownerID) {
      return node;
    }
    return new VNode(node ? node.array.slice() : [], ownerID);
  }

  function listNodeFor(list, rawIndex) {
    if (rawIndex >= getTailOffset(list._capacity)) {
      return list._tail;
    }
    if (rawIndex < 1 << (list._level + SHIFT)) {
      var node = list._root;
      var level = list._level;
      while (node && level > 0) {
        node = node.array[(rawIndex >>> level) & MASK];
        level -= SHIFT;
      }
      return node;
    }
  }

  function setListBounds(list, begin, end) {
    // Sanitize begin & end using this shorthand for ToInt32(argument)
    // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
    if (begin !== undefined) {
      begin = begin | 0;
    }
    if (end !== undefined) {
      end = end | 0;
    }
    var owner = list.__ownerID || new OwnerID();
    var oldOrigin = list._origin;
    var oldCapacity = list._capacity;
    var newOrigin = oldOrigin + begin;
    var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end;
    if (newOrigin === oldOrigin && newCapacity === oldCapacity) {
      return list;
    }

    // If it's going to end after it starts, it's empty.
    if (newOrigin >= newCapacity) {
      return list.clear();
    }

    var newLevel = list._level;
    var newRoot = list._root;

    // New origin might need creating a higher root.
    var offsetShift = 0;
    while (newOrigin + offsetShift < 0) {
      newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner);
      newLevel += SHIFT;
      offsetShift += 1 << newLevel;
    }
    if (offsetShift) {
      newOrigin += offsetShift;
      oldOrigin += offsetShift;
      newCapacity += offsetShift;
      oldCapacity += offsetShift;
    }

    var oldTailOffset = getTailOffset(oldCapacity);
    var newTailOffset = getTailOffset(newCapacity);

    // New size might need creating a higher root.
    while (newTailOffset >= 1 << (newLevel + SHIFT)) {
      newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner);
      newLevel += SHIFT;
    }

    // Locate or create the new tail.
    var oldTail = list._tail;
    var newTail = newTailOffset < oldTailOffset ?
      listNodeFor(list, newCapacity - 1) :
      newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail;

    // Merge Tail into tree.
    if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) {
      newRoot = editableVNode(newRoot, owner);
      var node = newRoot;
      for (var level = newLevel; level > SHIFT; level -= SHIFT) {
        var idx = (oldTailOffset >>> level) & MASK;
        node = node.array[idx] = editableVNode(node.array[idx], owner);
      }
      node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail;
    }

    // If the size has been reduced, there's a chance the tail needs to be trimmed.
    if (newCapacity < oldCapacity) {
      newTail = newTail && newTail.removeAfter(owner, 0, newCapacity);
    }

    // If the new origin is within the tail, then we do not need a root.
    if (newOrigin >= newTailOffset) {
      newOrigin -= newTailOffset;
      newCapacity -= newTailOffset;
      newLevel = SHIFT;
      newRoot = null;
      newTail = newTail && newTail.removeBefore(owner, 0, newOrigin);

    // Otherwise, if the root has been trimmed, garbage collect.
    } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) {
      offsetShift = 0;

      // Identify the new top root node of the subtree of the old root.
      while (newRoot) {
        var beginIndex = (newOrigin >>> newLevel) & MASK;
        if (beginIndex !== (newTailOffset >>> newLevel) & MASK) {
          break;
        }
        if (beginIndex) {
          offsetShift += (1 << newLevel) * beginIndex;
        }
        newLevel -= SHIFT;
        newRoot = newRoot.array[beginIndex];
      }

      // Trim the new sides of the new root.
      if (newRoot && newOrigin > oldOrigin) {
        newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift);
      }
      if (newRoot && newTailOffset < oldTailOffset) {
        newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift);
      }
      if (offsetShift) {
        newOrigin -= offsetShift;
        newCapacity -= offsetShift;
      }
    }

    if (list.__ownerID) {
      list.size = newCapacity - newOrigin;
      list._origin = newOrigin;
      list._capacity = newCapacity;
      list._level = newLevel;
      list._root = newRoot;
      list._tail = newTail;
      list.__hash = undefined;
      list.__altered = true;
      return list;
    }
    return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail);
  }

  function mergeIntoListWith(list, merger, iterables) {
    var iters = [];
    var maxSize = 0;
    for (var ii = 0; ii < iterables.length; ii++) {
      var value = iterables[ii];
      var iter = IndexedIterable(value);
      if (iter.size > maxSize) {
        maxSize = iter.size;
      }
      if (!isIterable(value)) {
        iter = iter.map(function(v ) {return fromJS(v)});
      }
      iters.push(iter);
    }
    if (maxSize > list.size) {
      list = list.setSize(maxSize);
    }
    return mergeIntoCollectionWith(list, merger, iters);
  }

  function getTailOffset(size) {
    return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT);
  }

  createClass(OrderedMap, Map);

    // @pragma Construction

    function OrderedMap(value) {
      return value === null || value === undefined ? emptyOrderedMap() :
        isOrderedMap(value) ? value :
        emptyOrderedMap().withMutations(function(map ) {
          var iter = KeyedIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v, k)  {return map.set(k, v)});
        });
    }

    OrderedMap.of = function(/*...values*/) {
      return this(arguments);
    };

    OrderedMap.prototype.toString = function() {
      return this.__toString('OrderedMap {', '}');
    };

    // @pragma Access

    OrderedMap.prototype.get = function(k, notSetValue) {
      var index = this._map.get(k);
      return index !== undefined ? this._list.get(index)[1] : notSetValue;
    };

    // @pragma Modification

    OrderedMap.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._map.clear();
        this._list.clear();
        return this;
      }
      return emptyOrderedMap();
    };

    OrderedMap.prototype.set = function(k, v) {
      return updateOrderedMap(this, k, v);
    };

    OrderedMap.prototype.remove = function(k) {
      return updateOrderedMap(this, k, NOT_SET);
    };

    OrderedMap.prototype.wasAltered = function() {
      return this._map.wasAltered() || this._list.wasAltered();
    };

    OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._list.__iterate(
        function(entry ) {return entry && fn(entry[1], entry[0], this$0)},
        reverse
      );
    };

    OrderedMap.prototype.__iterator = function(type, reverse) {
      return this._list.fromEntrySeq().__iterator(type, reverse);
    };

    OrderedMap.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map.__ensureOwner(ownerID);
      var newList = this._list.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        this._list = newList;
        return this;
      }
      return makeOrderedMap(newMap, newList, ownerID, this.__hash);
    };


  function isOrderedMap(maybeOrderedMap) {
    return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap);
  }

  OrderedMap.isOrderedMap = isOrderedMap;

  OrderedMap.prototype[IS_ORDERED_SENTINEL] = true;
  OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove;



  function makeOrderedMap(map, list, ownerID, hash) {
    var omap = Object.create(OrderedMap.prototype);
    omap.size = map ? map.size : 0;
    omap._map = map;
    omap._list = list;
    omap.__ownerID = ownerID;
    omap.__hash = hash;
    return omap;
  }

  var EMPTY_ORDERED_MAP;
  function emptyOrderedMap() {
    return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList()));
  }

  function updateOrderedMap(omap, k, v) {
    var map = omap._map;
    var list = omap._list;
    var i = map.get(k);
    var has = i !== undefined;
    var newMap;
    var newList;
    if (v === NOT_SET) { // removed
      if (!has) {
        return omap;
      }
      if (list.size >= SIZE && list.size >= map.size * 2) {
        newList = list.filter(function(entry, idx)  {return entry !== undefined && i !== idx});
        newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap();
        if (omap.__ownerID) {
          newMap.__ownerID = newList.__ownerID = omap.__ownerID;
        }
      } else {
        newMap = map.remove(k);
        newList = i === list.size - 1 ? list.pop() : list.set(i, undefined);
      }
    } else {
      if (has) {
        if (v === list.get(i)[1]) {
          return omap;
        }
        newMap = map;
        newList = list.set(i, [k, v]);
      } else {
        newMap = map.set(k, list.size);
        newList = list.set(list.size, [k, v]);
      }
    }
    if (omap.__ownerID) {
      omap.size = newMap.size;
      omap._map = newMap;
      omap._list = newList;
      omap.__hash = undefined;
      return omap;
    }
    return makeOrderedMap(newMap, newList);
  }

  createClass(ToKeyedSequence, KeyedSeq);
    function ToKeyedSequence(indexed, useKeys) {
      this._iter = indexed;
      this._useKeys = useKeys;
      this.size = indexed.size;
    }

    ToKeyedSequence.prototype.get = function(key, notSetValue) {
      return this._iter.get(key, notSetValue);
    };

    ToKeyedSequence.prototype.has = function(key) {
      return this._iter.has(key);
    };

    ToKeyedSequence.prototype.valueSeq = function() {
      return this._iter.valueSeq();
    };

    ToKeyedSequence.prototype.reverse = function() {var this$0 = this;
      var reversedSequence = reverseFactory(this, true);
      if (!this._useKeys) {
        reversedSequence.valueSeq = function()  {return this$0._iter.toSeq().reverse()};
      }
      return reversedSequence;
    };

    ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this;
      var mappedSequence = mapFactory(this, mapper, context);
      if (!this._useKeys) {
        mappedSequence.valueSeq = function()  {return this$0._iter.toSeq().map(mapper, context)};
      }
      return mappedSequence;
    };

    ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var ii;
      return this._iter.__iterate(
        this._useKeys ?
          function(v, k)  {return fn(v, k, this$0)} :
          ((ii = reverse ? resolveSize(this) : 0),
            function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}),
        reverse
      );
    };

    ToKeyedSequence.prototype.__iterator = function(type, reverse) {
      if (this._useKeys) {
        return this._iter.__iterator(type, reverse);
      }
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      var ii = reverse ? resolveSize(this) : 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, reverse ? --ii : ii++, step.value, step);
      });
    };

  ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true;


  createClass(ToIndexedSequence, IndexedSeq);
    function ToIndexedSequence(iter) {
      this._iter = iter;
      this.size = iter.size;
    }

    ToIndexedSequence.prototype.includes = function(value) {
      return this._iter.includes(value);
    };

    ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse);
    };

    ToIndexedSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      var iterations = 0;
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, iterations++, step.value, step)
      });
    };



  createClass(ToSetSequence, SetSeq);
    function ToSetSequence(iter) {
      this._iter = iter;
      this.size = iter.size;
    }

    ToSetSequence.prototype.has = function(key) {
      return this._iter.includes(key);
    };

    ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse);
    };

    ToSetSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      return new Iterator(function()  {
        var step = iterator.next();
        return step.done ? step :
          iteratorValue(type, step.value, step.value, step);
      });
    };



  createClass(FromEntriesSequence, KeyedSeq);
    function FromEntriesSequence(entries) {
      this._iter = entries;
      this.size = entries.size;
    }

    FromEntriesSequence.prototype.entrySeq = function() {
      return this._iter.toSeq();
    };

    FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._iter.__iterate(function(entry ) {
        // Check if entry exists first so array access doesn't throw for holes
        // in the parent iteration.
        if (entry) {
          validateEntry(entry);
          var indexedIterable = isIterable(entry);
          return fn(
            indexedIterable ? entry.get(1) : entry[1],
            indexedIterable ? entry.get(0) : entry[0],
            this$0
          );
        }
      }, reverse);
    };

    FromEntriesSequence.prototype.__iterator = function(type, reverse) {
      var iterator = this._iter.__iterator(ITERATE_VALUES, reverse);
      return new Iterator(function()  {
        while (true) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          var entry = step.value;
          // Check if entry exists first so array access doesn't throw for holes
          // in the parent iteration.
          if (entry) {
            validateEntry(entry);
            var indexedIterable = isIterable(entry);
            return iteratorValue(
              type,
              indexedIterable ? entry.get(0) : entry[0],
              indexedIterable ? entry.get(1) : entry[1],
              step
            );
          }
        }
      });
    };


  ToIndexedSequence.prototype.cacheResult =
  ToKeyedSequence.prototype.cacheResult =
  ToSetSequence.prototype.cacheResult =
  FromEntriesSequence.prototype.cacheResult =
    cacheResultThrough;


  function flipFactory(iterable) {
    var flipSequence = makeSequence(iterable);
    flipSequence._iter = iterable;
    flipSequence.size = iterable.size;
    flipSequence.flip = function()  {return iterable};
    flipSequence.reverse = function () {
      var reversedSequence = iterable.reverse.apply(this); // super.reverse()
      reversedSequence.flip = function()  {return iterable.reverse()};
      return reversedSequence;
    };
    flipSequence.has = function(key ) {return iterable.includes(key)};
    flipSequence.includes = function(key ) {return iterable.has(key)};
    flipSequence.cacheResult = cacheResultThrough;
    flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(function(v, k)  {return fn(k, v, this$0) !== false}, reverse);
    }
    flipSequence.__iteratorUncached = function(type, reverse) {
      if (type === ITERATE_ENTRIES) {
        var iterator = iterable.__iterator(type, reverse);
        return new Iterator(function()  {
          var step = iterator.next();
          if (!step.done) {
            var k = step.value[0];
            step.value[0] = step.value[1];
            step.value[1] = k;
          }
          return step;
        });
      }
      return iterable.__iterator(
        type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES,
        reverse
      );
    }
    return flipSequence;
  }


  function mapFactory(iterable, mapper, context) {
    var mappedSequence = makeSequence(iterable);
    mappedSequence.size = iterable.size;
    mappedSequence.has = function(key ) {return iterable.has(key)};
    mappedSequence.get = function(key, notSetValue)  {
      var v = iterable.get(key, NOT_SET);
      return v === NOT_SET ?
        notSetValue :
        mapper.call(context, v, key, iterable);
    };
    mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(
        function(v, k, c)  {return fn(mapper.call(context, v, k, c), k, this$0) !== false},
        reverse
      );
    }
    mappedSequence.__iteratorUncached = function (type, reverse) {
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      return new Iterator(function()  {
        var step = iterator.next();
        if (step.done) {
          return step;
        }
        var entry = step.value;
        var key = entry[0];
        return iteratorValue(
          type,
          key,
          mapper.call(context, entry[1], key, iterable),
          step
        );
      });
    }
    return mappedSequence;
  }


  function reverseFactory(iterable, useKeys) {
    var reversedSequence = makeSequence(iterable);
    reversedSequence._iter = iterable;
    reversedSequence.size = iterable.size;
    reversedSequence.reverse = function()  {return iterable};
    if (iterable.flip) {
      reversedSequence.flip = function () {
        var flipSequence = flipFactory(iterable);
        flipSequence.reverse = function()  {return iterable.flip()};
        return flipSequence;
      };
    }
    reversedSequence.get = function(key, notSetValue)
      {return iterable.get(useKeys ? key : -1 - key, notSetValue)};
    reversedSequence.has = function(key )
      {return iterable.has(useKeys ? key : -1 - key)};
    reversedSequence.includes = function(value ) {return iterable.includes(value)};
    reversedSequence.cacheResult = cacheResultThrough;
    reversedSequence.__iterate = function (fn, reverse) {var this$0 = this;
      return iterable.__iterate(function(v, k)  {return fn(v, k, this$0)}, !reverse);
    };
    reversedSequence.__iterator =
      function(type, reverse)  {return iterable.__iterator(type, !reverse)};
    return reversedSequence;
  }


  function filterFactory(iterable, predicate, context, useKeys) {
    var filterSequence = makeSequence(iterable);
    if (useKeys) {
      filterSequence.has = function(key ) {
        var v = iterable.get(key, NOT_SET);
        return v !== NOT_SET && !!predicate.call(context, v, key, iterable);
      };
      filterSequence.get = function(key, notSetValue)  {
        var v = iterable.get(key, NOT_SET);
        return v !== NOT_SET && predicate.call(context, v, key, iterable) ?
          v : notSetValue;
      };
    }
    filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      var iterations = 0;
      iterable.__iterate(function(v, k, c)  {
        if (predicate.call(context, v, k, c)) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0);
        }
      }, reverse);
      return iterations;
    };
    filterSequence.__iteratorUncached = function (type, reverse) {
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var iterations = 0;
      return new Iterator(function()  {
        while (true) {
          var step = iterator.next();
          if (step.done) {
            return step;
          }
          var entry = step.value;
          var key = entry[0];
          var value = entry[1];
          if (predicate.call(context, value, key, iterable)) {
            return iteratorValue(type, useKeys ? key : iterations++, value, step);
          }
        }
      });
    }
    return filterSequence;
  }


  function countByFactory(iterable, grouper, context) {
    var groups = Map().asMutable();
    iterable.__iterate(function(v, k)  {
      groups.update(
        grouper.call(context, v, k, iterable),
        0,
        function(a ) {return a + 1}
      );
    });
    return groups.asImmutable();
  }


  function groupByFactory(iterable, grouper, context) {
    var isKeyedIter = isKeyed(iterable);
    var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable();
    iterable.__iterate(function(v, k)  {
      groups.update(
        grouper.call(context, v, k, iterable),
        function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)}
      );
    });
    var coerce = iterableClass(iterable);
    return groups.map(function(arr ) {return reify(iterable, coerce(arr))});
  }


  function sliceFactory(iterable, begin, end, useKeys) {
    var originalSize = iterable.size;

    // Sanitize begin & end using this shorthand for ToInt32(argument)
    // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32
    if (begin !== undefined) {
      begin = begin | 0;
    }
    if (end !== undefined) {
      if (end === Infinity) {
        end = originalSize;
      } else {
        end = end | 0;
      }
    }

    if (wholeSlice(begin, end, originalSize)) {
      return iterable;
    }

    var resolvedBegin = resolveBegin(begin, originalSize);
    var resolvedEnd = resolveEnd(end, originalSize);

    // begin or end will be NaN if they were provided as negative numbers and
    // this iterable's size is unknown. In that case, cache first so there is
    // a known size and these do not resolve to NaN.
    if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) {
      return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys);
    }

    // Note: resolvedEnd is undefined when the original sequence's length is
    // unknown and this slice did not supply an end and should contain all
    // elements after resolvedBegin.
    // In that case, resolvedSize will be NaN and sliceSize will remain undefined.
    var resolvedSize = resolvedEnd - resolvedBegin;
    var sliceSize;
    if (resolvedSize === resolvedSize) {
      sliceSize = resolvedSize < 0 ? 0 : resolvedSize;
    }

    var sliceSeq = makeSequence(iterable);

    // If iterable.size is undefined, the size of the realized sliceSeq is
    // unknown at this point unless the number of items to slice is 0
    sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined;

    if (!useKeys && isSeq(iterable) && sliceSize >= 0) {
      sliceSeq.get = function (index, notSetValue) {
        index = wrapIndex(this, index);
        return index >= 0 && index < sliceSize ?
          iterable.get(index + resolvedBegin, notSetValue) :
          notSetValue;
      }
    }

    sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this;
      if (sliceSize === 0) {
        return 0;
      }
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var skipped = 0;
      var isSkipping = true;
      var iterations = 0;
      iterable.__iterate(function(v, k)  {
        if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0) !== false &&
                 iterations !== sliceSize;
        }
      });
      return iterations;
    };

    sliceSeq.__iteratorUncached = function(type, reverse) {
      if (sliceSize !== 0 && reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      // Don't bother instantiating parent iterator if taking 0.
      var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse);
      var skipped = 0;
      var iterations = 0;
      return new Iterator(function()  {
        while (skipped++ < resolvedBegin) {
          iterator.next();
        }
        if (++iterations > sliceSize) {
          return iteratorDone();
        }
        var step = iterator.next();
        if (useKeys || type === ITERATE_VALUES) {
          return step;
        } else if (type === ITERATE_KEYS) {
          return iteratorValue(type, iterations - 1, undefined, step);
        } else {
          return iteratorValue(type, iterations - 1, step.value[1], step);
        }
      });
    }

    return sliceSeq;
  }


  function takeWhileFactory(iterable, predicate, context) {
    var takeSequence = makeSequence(iterable);
    takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var iterations = 0;
      iterable.__iterate(function(v, k, c)
        {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)}
      );
      return iterations;
    };
    takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var iterating = true;
      return new Iterator(function()  {
        if (!iterating) {
          return iteratorDone();
        }
        var step = iterator.next();
        if (step.done) {
          return step;
        }
        var entry = step.value;
        var k = entry[0];
        var v = entry[1];
        if (!predicate.call(context, v, k, this$0)) {
          iterating = false;
          return iteratorDone();
        }
        return type === ITERATE_ENTRIES ? step :
          iteratorValue(type, k, v, step);
      });
    };
    return takeSequence;
  }


  function skipWhileFactory(iterable, predicate, context, useKeys) {
    var skipSequence = makeSequence(iterable);
    skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterate(fn, reverse);
      }
      var isSkipping = true;
      var iterations = 0;
      iterable.__iterate(function(v, k, c)  {
        if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) {
          iterations++;
          return fn(v, useKeys ? k : iterations - 1, this$0);
        }
      });
      return iterations;
    };
    skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this;
      if (reverse) {
        return this.cacheResult().__iterator(type, reverse);
      }
      var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse);
      var skipping = true;
      var iterations = 0;
      return new Iterator(function()  {
        var step, k, v;
        do {
          step = iterator.next();
          if (step.done) {
            if (useKeys || type === ITERATE_VALUES) {
              return step;
            } else if (type === ITERATE_KEYS) {
              return iteratorValue(type, iterations++, undefined, step);
            } else {
              return iteratorValue(type, iterations++, step.value[1], step);
            }
          }
          var entry = step.value;
          k = entry[0];
          v = entry[1];
          skipping && (skipping = predicate.call(context, v, k, this$0));
        } while (skipping);
        return type === ITERATE_ENTRIES ? step :
          iteratorValue(type, k, v, step);
      });
    };
    return skipSequence;
  }


  function concatFactory(iterable, values) {
    var isKeyedIterable = isKeyed(iterable);
    var iters = [iterable].concat(values).map(function(v ) {
      if (!isIterable(v)) {
        v = isKeyedIterable ?
          keyedSeqFromValue(v) :
          indexedSeqFromValue(Array.isArray(v) ? v : [v]);
      } else if (isKeyedIterable) {
        v = KeyedIterable(v);
      }
      return v;
    }).filter(function(v ) {return v.size !== 0});

    if (iters.length === 0) {
      return iterable;
    }

    if (iters.length === 1) {
      var singleton = iters[0];
      if (singleton === iterable ||
          isKeyedIterable && isKeyed(singleton) ||
          isIndexed(iterable) && isIndexed(singleton)) {
        return singleton;
      }
    }

    var concatSeq = new ArraySeq(iters);
    if (isKeyedIterable) {
      concatSeq = concatSeq.toKeyedSeq();
    } else if (!isIndexed(iterable)) {
      concatSeq = concatSeq.toSetSeq();
    }
    concatSeq = concatSeq.flatten(true);
    concatSeq.size = iters.reduce(
      function(sum, seq)  {
        if (sum !== undefined) {
          var size = seq.size;
          if (size !== undefined) {
            return sum + size;
          }
        }
      },
      0
    );
    return concatSeq;
  }


  function flattenFactory(iterable, depth, useKeys) {
    var flatSequence = makeSequence(iterable);
    flatSequence.__iterateUncached = function(fn, reverse) {
      var iterations = 0;
      var stopped = false;
      function flatDeep(iter, currentDepth) {var this$0 = this;
        iter.__iterate(function(v, k)  {
          if ((!depth || currentDepth < depth) && isIterable(v)) {
            flatDeep(v, currentDepth + 1);
          } else if (fn(v, useKeys ? k : iterations++, this$0) === false) {
            stopped = true;
          }
          return !stopped;
        }, reverse);
      }
      flatDeep(iterable, 0);
      return iterations;
    }
    flatSequence.__iteratorUncached = function(type, reverse) {
      var iterator = iterable.__iterator(type, reverse);
      var stack = [];
      var iterations = 0;
      return new Iterator(function()  {
        while (iterator) {
          var step = iterator.next();
          if (step.done !== false) {
            iterator = stack.pop();
            continue;
          }
          var v = step.value;
          if (type === ITERATE_ENTRIES) {
            v = v[1];
          }
          if ((!depth || stack.length < depth) && isIterable(v)) {
            stack.push(iterator);
            iterator = v.__iterator(type, reverse);
          } else {
            return useKeys ? step : iteratorValue(type, iterations++, v, step);
          }
        }
        return iteratorDone();
      });
    }
    return flatSequence;
  }


  function flatMapFactory(iterable, mapper, context) {
    var coerce = iterableClass(iterable);
    return iterable.toSeq().map(
      function(v, k)  {return coerce(mapper.call(context, v, k, iterable))}
    ).flatten(true);
  }


  function interposeFactory(iterable, separator) {
    var interposedSequence = makeSequence(iterable);
    interposedSequence.size = iterable.size && iterable.size * 2 -1;
    interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this;
      var iterations = 0;
      iterable.__iterate(function(v, k)
        {return (!iterations || fn(separator, iterations++, this$0) !== false) &&
        fn(v, iterations++, this$0) !== false},
        reverse
      );
      return iterations;
    };
    interposedSequence.__iteratorUncached = function(type, reverse) {
      var iterator = iterable.__iterator(ITERATE_VALUES, reverse);
      var iterations = 0;
      var step;
      return new Iterator(function()  {
        if (!step || iterations % 2) {
          step = iterator.next();
          if (step.done) {
            return step;
          }
        }
        return iterations % 2 ?
          iteratorValue(type, iterations++, separator) :
          iteratorValue(type, iterations++, step.value, step);
      });
    };
    return interposedSequence;
  }


  function sortFactory(iterable, comparator, mapper) {
    if (!comparator) {
      comparator = defaultComparator;
    }
    var isKeyedIterable = isKeyed(iterable);
    var index = 0;
    var entries = iterable.toSeq().map(
      function(v, k)  {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]}
    ).toArray();
    entries.sort(function(a, b)  {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach(
      isKeyedIterable ?
      function(v, i)  { entries[i].length = 2; } :
      function(v, i)  { entries[i] = v[1]; }
    );
    return isKeyedIterable ? KeyedSeq(entries) :
      isIndexed(iterable) ? IndexedSeq(entries) :
      SetSeq(entries);
  }


  function maxFactory(iterable, comparator, mapper) {
    if (!comparator) {
      comparator = defaultComparator;
    }
    if (mapper) {
      var entry = iterable.toSeq()
        .map(function(v, k)  {return [v, mapper(v, k, iterable)]})
        .reduce(function(a, b)  {return maxCompare(comparator, a[1], b[1]) ? b : a});
      return entry && entry[0];
    } else {
      return iterable.reduce(function(a, b)  {return maxCompare(comparator, a, b) ? b : a});
    }
  }

  function maxCompare(comparator, a, b) {
    var comp = comparator(b, a);
    // b is considered the new max if the comparator declares them equal, but
    // they are not equal and b is in fact a nullish value.
    return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0;
  }


  function zipWithFactory(keyIter, zipper, iters) {
    var zipSequence = makeSequence(keyIter);
    zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min();
    // Note: this a generic base implementation of __iterate in terms of
    // __iterator which may be more generically useful in the future.
    zipSequence.__iterate = function(fn, reverse) {
      /* generic:
      var iterator = this.__iterator(ITERATE_ENTRIES, reverse);
      var step;
      var iterations = 0;
      while (!(step = iterator.next()).done) {
        iterations++;
        if (fn(step.value[1], step.value[0], this) === false) {
          break;
        }
      }
      return iterations;
      */
      // indexed:
      var iterator = this.__iterator(ITERATE_VALUES, reverse);
      var step;
      var iterations = 0;
      while (!(step = iterator.next()).done) {
        if (fn(step.value, iterations++, this) === false) {
          break;
        }
      }
      return iterations;
    };
    zipSequence.__iteratorUncached = function(type, reverse) {
      var iterators = iters.map(function(i )
        {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))}
      );
      var iterations = 0;
      var isDone = false;
      return new Iterator(function()  {
        var steps;
        if (!isDone) {
          steps = iterators.map(function(i ) {return i.next()});
          isDone = steps.some(function(s ) {return s.done});
        }
        if (isDone) {
          return iteratorDone();
        }
        return iteratorValue(
          type,
          iterations++,
          zipper.apply(null, steps.map(function(s ) {return s.value}))
        );
      });
    };
    return zipSequence
  }


  // #pragma Helper Functions

  function reify(iter, seq) {
    return isSeq(iter) ? seq : iter.constructor(seq);
  }

  function validateEntry(entry) {
    if (entry !== Object(entry)) {
      throw new TypeError('Expected [K, V] tuple: ' + entry);
    }
  }

  function resolveSize(iter) {
    assertNotInfinite(iter.size);
    return ensureSize(iter);
  }

  function iterableClass(iterable) {
    return isKeyed(iterable) ? KeyedIterable :
      isIndexed(iterable) ? IndexedIterable :
      SetIterable;
  }

  function makeSequence(iterable) {
    return Object.create(
      (
        isKeyed(iterable) ? KeyedSeq :
        isIndexed(iterable) ? IndexedSeq :
        SetSeq
      ).prototype
    );
  }

  function cacheResultThrough() {
    if (this._iter.cacheResult) {
      this._iter.cacheResult();
      this.size = this._iter.size;
      return this;
    } else {
      return Seq.prototype.cacheResult.call(this);
    }
  }

  function defaultComparator(a, b) {
    return a > b ? 1 : a < b ? -1 : 0;
  }

  function forceIterator(keyPath) {
    var iter = getIterator(keyPath);
    if (!iter) {
      // Array might not be iterable in this environment, so we need a fallback
      // to our wrapped type.
      if (!isArrayLike(keyPath)) {
        throw new TypeError('Expected iterable or array-like: ' + keyPath);
      }
      iter = getIterator(Iterable(keyPath));
    }
    return iter;
  }

  createClass(Record, KeyedCollection);

    function Record(defaultValues, name) {
      var hasInitialized;

      var RecordType = function Record(values) {
        if (values instanceof RecordType) {
          return values;
        }
        if (!(this instanceof RecordType)) {
          return new RecordType(values);
        }
        if (!hasInitialized) {
          hasInitialized = true;
          var keys = Object.keys(defaultValues);
          setProps(RecordTypePrototype, keys);
          RecordTypePrototype.size = keys.length;
          RecordTypePrototype._name = name;
          RecordTypePrototype._keys = keys;
          RecordTypePrototype._defaultValues = defaultValues;
        }
        this._map = Map(values);
      };

      var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype);
      RecordTypePrototype.constructor = RecordType;

      return RecordType;
    }

    Record.prototype.toString = function() {
      return this.__toString(recordName(this) + ' {', '}');
    };

    // @pragma Access

    Record.prototype.has = function(k) {
      return this._defaultValues.hasOwnProperty(k);
    };

    Record.prototype.get = function(k, notSetValue) {
      if (!this.has(k)) {
        return notSetValue;
      }
      var defaultVal = this._defaultValues[k];
      return this._map ? this._map.get(k, defaultVal) : defaultVal;
    };

    // @pragma Modification

    Record.prototype.clear = function() {
      if (this.__ownerID) {
        this._map && this._map.clear();
        return this;
      }
      var RecordType = this.constructor;
      return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap()));
    };

    Record.prototype.set = function(k, v) {
      if (!this.has(k)) {
        throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this));
      }
      if (this._map && !this._map.has(k)) {
        var defaultVal = this._defaultValues[k];
        if (v === defaultVal) {
          return this;
        }
      }
      var newMap = this._map && this._map.set(k, v);
      if (this.__ownerID || newMap === this._map) {
        return this;
      }
      return makeRecord(this, newMap);
    };

    Record.prototype.remove = function(k) {
      if (!this.has(k)) {
        return this;
      }
      var newMap = this._map && this._map.remove(k);
      if (this.__ownerID || newMap === this._map) {
        return this;
      }
      return makeRecord(this, newMap);
    };

    Record.prototype.wasAltered = function() {
      return this._map.wasAltered();
    };

    Record.prototype.__iterator = function(type, reverse) {var this$0 = this;
      return KeyedIterable(this._defaultValues).map(function(_, k)  {return this$0.get(k)}).__iterator(type, reverse);
    };

    Record.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return KeyedIterable(this._defaultValues).map(function(_, k)  {return this$0.get(k)}).__iterate(fn, reverse);
    };

    Record.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map && this._map.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        return this;
      }
      return makeRecord(this, newMap, ownerID);
    };


  var RecordPrototype = Record.prototype;
  RecordPrototype[DELETE] = RecordPrototype.remove;
  RecordPrototype.deleteIn =
  RecordPrototype.removeIn = MapPrototype.removeIn;
  RecordPrototype.merge = MapPrototype.merge;
  RecordPrototype.mergeWith = MapPrototype.mergeWith;
  RecordPrototype.mergeIn = MapPrototype.mergeIn;
  RecordPrototype.mergeDeep = MapPrototype.mergeDeep;
  RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith;
  RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn;
  RecordPrototype.setIn = MapPrototype.setIn;
  RecordPrototype.update = MapPrototype.update;
  RecordPrototype.updateIn = MapPrototype.updateIn;
  RecordPrototype.withMutations = MapPrototype.withMutations;
  RecordPrototype.asMutable = MapPrototype.asMutable;
  RecordPrototype.asImmutable = MapPrototype.asImmutable;


  function makeRecord(likeRecord, map, ownerID) {
    var record = Object.create(Object.getPrototypeOf(likeRecord));
    record._map = map;
    record.__ownerID = ownerID;
    return record;
  }

  function recordName(record) {
    return record._name || record.constructor.name || 'Record';
  }

  function setProps(prototype, names) {
    try {
      names.forEach(setProp.bind(undefined, prototype));
    } catch (error) {
      // Object.defineProperty failed. Probably IE8.
    }
  }

  function setProp(prototype, name) {
    Object.defineProperty(prototype, name, {
      get: function() {
        return this.get(name);
      },
      set: function(value) {
        invariant(this.__ownerID, 'Cannot set on an immutable record.');
        this.set(name, value);
      }
    });
  }

  createClass(Set, SetCollection);

    // @pragma Construction

    function Set(value) {
      return value === null || value === undefined ? emptySet() :
        isSet(value) && !isOrdered(value) ? value :
        emptySet().withMutations(function(set ) {
          var iter = SetIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v ) {return set.add(v)});
        });
    }

    Set.of = function(/*...values*/) {
      return this(arguments);
    };

    Set.fromKeys = function(value) {
      return this(KeyedIterable(value).keySeq());
    };

    Set.prototype.toString = function() {
      return this.__toString('Set {', '}');
    };

    // @pragma Access

    Set.prototype.has = function(value) {
      return this._map.has(value);
    };

    // @pragma Modification

    Set.prototype.add = function(value) {
      return updateSet(this, this._map.set(value, true));
    };

    Set.prototype.remove = function(value) {
      return updateSet(this, this._map.remove(value));
    };

    Set.prototype.clear = function() {
      return updateSet(this, this._map.clear());
    };

    // @pragma Composition

    Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0);
      iters = iters.filter(function(x ) {return x.size !== 0});
      if (iters.length === 0) {
        return this;
      }
      if (this.size === 0 && !this.__ownerID && iters.length === 1) {
        return this.constructor(iters[0]);
      }
      return this.withMutations(function(set ) {
        for (var ii = 0; ii < iters.length; ii++) {
          SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)});
        }
      });
    };

    Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0);
      if (iters.length === 0) {
        return this;
      }
      iters = iters.map(function(iter ) {return SetIterable(iter)});
      var originalSet = this;
      return this.withMutations(function(set ) {
        originalSet.forEach(function(value ) {
          if (!iters.every(function(iter ) {return iter.includes(value)})) {
            set.remove(value);
          }
        });
      });
    };

    Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0);
      if (iters.length === 0) {
        return this;
      }
      iters = iters.map(function(iter ) {return SetIterable(iter)});
      var originalSet = this;
      return this.withMutations(function(set ) {
        originalSet.forEach(function(value ) {
          if (iters.some(function(iter ) {return iter.includes(value)})) {
            set.remove(value);
          }
        });
      });
    };

    Set.prototype.merge = function() {
      return this.union.apply(this, arguments);
    };

    Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1);
      return this.union.apply(this, iters);
    };

    Set.prototype.sort = function(comparator) {
      // Late binding
      return OrderedSet(sortFactory(this, comparator));
    };

    Set.prototype.sortBy = function(mapper, comparator) {
      // Late binding
      return OrderedSet(sortFactory(this, comparator, mapper));
    };

    Set.prototype.wasAltered = function() {
      return this._map.wasAltered();
    };

    Set.prototype.__iterate = function(fn, reverse) {var this$0 = this;
      return this._map.__iterate(function(_, k)  {return fn(k, k, this$0)}, reverse);
    };

    Set.prototype.__iterator = function(type, reverse) {
      return this._map.map(function(_, k)  {return k}).__iterator(type, reverse);
    };

    Set.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      var newMap = this._map.__ensureOwner(ownerID);
      if (!ownerID) {
        this.__ownerID = ownerID;
        this._map = newMap;
        return this;
      }
      return this.__make(newMap, ownerID);
    };


  function isSet(maybeSet) {
    return !!(maybeSet && maybeSet[IS_SET_SENTINEL]);
  }

  Set.isSet = isSet;

  var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@';

  var SetPrototype = Set.prototype;
  SetPrototype[IS_SET_SENTINEL] = true;
  SetPrototype[DELETE] = SetPrototype.remove;
  SetPrototype.mergeDeep = SetPrototype.merge;
  SetPrototype.mergeDeepWith = SetPrototype.mergeWith;
  SetPrototype.withMutations = MapPrototype.withMutations;
  SetPrototype.asMutable = MapPrototype.asMutable;
  SetPrototype.asImmutable = MapPrototype.asImmutable;

  SetPrototype.__empty = emptySet;
  SetPrototype.__make = makeSet;

  function updateSet(set, newMap) {
    if (set.__ownerID) {
      set.size = newMap.size;
      set._map = newMap;
      return set;
    }
    return newMap === set._map ? set :
      newMap.size === 0 ? set.__empty() :
      set.__make(newMap);
  }

  function makeSet(map, ownerID) {
    var set = Object.create(SetPrototype);
    set.size = map ? map.size : 0;
    set._map = map;
    set.__ownerID = ownerID;
    return set;
  }

  var EMPTY_SET;
  function emptySet() {
    return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap()));
  }

  createClass(OrderedSet, Set);

    // @pragma Construction

    function OrderedSet(value) {
      return value === null || value === undefined ? emptyOrderedSet() :
        isOrderedSet(value) ? value :
        emptyOrderedSet().withMutations(function(set ) {
          var iter = SetIterable(value);
          assertNotInfinite(iter.size);
          iter.forEach(function(v ) {return set.add(v)});
        });
    }

    OrderedSet.of = function(/*...values*/) {
      return this(arguments);
    };

    OrderedSet.fromKeys = function(value) {
      return this(KeyedIterable(value).keySeq());
    };

    OrderedSet.prototype.toString = function() {
      return this.__toString('OrderedSet {', '}');
    };


  function isOrderedSet(maybeOrderedSet) {
    return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet);
  }

  OrderedSet.isOrderedSet = isOrderedSet;

  var OrderedSetPrototype = OrderedSet.prototype;
  OrderedSetPrototype[IS_ORDERED_SENTINEL] = true;

  OrderedSetPrototype.__empty = emptyOrderedSet;
  OrderedSetPrototype.__make = makeOrderedSet;

  function makeOrderedSet(map, ownerID) {
    var set = Object.create(OrderedSetPrototype);
    set.size = map ? map.size : 0;
    set._map = map;
    set.__ownerID = ownerID;
    return set;
  }

  var EMPTY_ORDERED_SET;
  function emptyOrderedSet() {
    return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap()));
  }

  createClass(Stack, IndexedCollection);

    // @pragma Construction

    function Stack(value) {
      return value === null || value === undefined ? emptyStack() :
        isStack(value) ? value :
        emptyStack().unshiftAll(value);
    }

    Stack.of = function(/*...values*/) {
      return this(arguments);
    };

    Stack.prototype.toString = function() {
      return this.__toString('Stack [', ']');
    };

    // @pragma Access

    Stack.prototype.get = function(index, notSetValue) {
      var head = this._head;
      index = wrapIndex(this, index);
      while (head && index--) {
        head = head.next;
      }
      return head ? head.value : notSetValue;
    };

    Stack.prototype.peek = function() {
      return this._head && this._head.value;
    };

    // @pragma Modification

    Stack.prototype.push = function(/*...values*/) {
      if (arguments.length === 0) {
        return this;
      }
      var newSize = this.size + arguments.length;
      var head = this._head;
      for (var ii = arguments.length - 1; ii >= 0; ii--) {
        head = {
          value: arguments[ii],
          next: head
        };
      }
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    Stack.prototype.pushAll = function(iter) {
      iter = IndexedIterable(iter);
      if (iter.size === 0) {
        return this;
      }
      assertNotInfinite(iter.size);
      var newSize = this.size;
      var head = this._head;
      iter.reverse().forEach(function(value ) {
        newSize++;
        head = {
          value: value,
          next: head
        };
      });
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    Stack.prototype.pop = function() {
      return this.slice(1);
    };

    Stack.prototype.unshift = function(/*...values*/) {
      return this.push.apply(this, arguments);
    };

    Stack.prototype.unshiftAll = function(iter) {
      return this.pushAll(iter);
    };

    Stack.prototype.shift = function() {
      return this.pop.apply(this, arguments);
    };

    Stack.prototype.clear = function() {
      if (this.size === 0) {
        return this;
      }
      if (this.__ownerID) {
        this.size = 0;
        this._head = undefined;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return emptyStack();
    };

    Stack.prototype.slice = function(begin, end) {
      if (wholeSlice(begin, end, this.size)) {
        return this;
      }
      var resolvedBegin = resolveBegin(begin, this.size);
      var resolvedEnd = resolveEnd(end, this.size);
      if (resolvedEnd !== this.size) {
        // super.slice(begin, end);
        return IndexedCollection.prototype.slice.call(this, begin, end);
      }
      var newSize = this.size - resolvedBegin;
      var head = this._head;
      while (resolvedBegin--) {
        head = head.next;
      }
      if (this.__ownerID) {
        this.size = newSize;
        this._head = head;
        this.__hash = undefined;
        this.__altered = true;
        return this;
      }
      return makeStack(newSize, head);
    };

    // @pragma Mutability

    Stack.prototype.__ensureOwner = function(ownerID) {
      if (ownerID === this.__ownerID) {
        return this;
      }
      if (!ownerID) {
        this.__ownerID = ownerID;
        this.__altered = false;
        return this;
      }
      return makeStack(this.size, this._head, ownerID, this.__hash);
    };

    // @pragma Iteration

    Stack.prototype.__iterate = function(fn, reverse) {
      if (reverse) {
        return this.reverse().__iterate(fn);
      }
      var iterations = 0;
      var node = this._head;
      while (node) {
        if (fn(node.value, iterations++, this) === false) {
          break;
        }
        node = node.next;
      }
      return iterations;
    };

    Stack.prototype.__iterator = function(type, reverse) {
      if (reverse) {
        return this.reverse().__iterator(type);
      }
      var iterations = 0;
      var node = this._head;
      return new Iterator(function()  {
        if (node) {
          var value = node.value;
          node = node.next;
          return iteratorValue(type, iterations++, value);
        }
        return iteratorDone();
      });
    };


  function isStack(maybeStack) {
    return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]);
  }

  Stack.isStack = isStack;

  var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@';

  var StackPrototype = Stack.prototype;
  StackPrototype[IS_STACK_SENTINEL] = true;
  StackPrototype.withMutations = MapPrototype.withMutations;
  StackPrototype.asMutable = MapPrototype.asMutable;
  StackPrototype.asImmutable = MapPrototype.asImmutable;
  StackPrototype.wasAltered = MapPrototype.wasAltered;


  function makeStack(size, head, ownerID, hash) {
    var map = Object.create(StackPrototype);
    map.size = size;
    map._head = head;
    map.__ownerID = ownerID;
    map.__hash = hash;
    map.__altered = false;
    return map;
  }

  var EMPTY_STACK;
  function emptyStack() {
    return EMPTY_STACK || (EMPTY_STACK = makeStack(0));
  }

  /**
   * Contributes additional methods to a constructor
   */
  function mixin(ctor, methods) {
    var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; };
    Object.keys(methods).forEach(keyCopier);
    Object.getOwnPropertySymbols &&
      Object.getOwnPropertySymbols(methods).forEach(keyCopier);
    return ctor;
  }

  Iterable.Iterator = Iterator;

  mixin(Iterable, {

    // ### Conversion to other types

    toArray: function() {
      assertNotInfinite(this.size);
      var array = new Array(this.size || 0);
      this.valueSeq().__iterate(function(v, i)  { array[i] = v; });
      return array;
    },

    toIndexedSeq: function() {
      return new ToIndexedSequence(this);
    },

    toJS: function() {
      return this.toSeq().map(
        function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value}
      ).__toJS();
    },

    toJSON: function() {
      return this.toSeq().map(
        function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value}
      ).__toJS();
    },

    toKeyedSeq: function() {
      return new ToKeyedSequence(this, true);
    },

    toMap: function() {
      // Use Late Binding here to solve the circular dependency.
      return Map(this.toKeyedSeq());
    },

    toObject: function() {
      assertNotInfinite(this.size);
      var object = {};
      this.__iterate(function(v, k)  { object[k] = v; });
      return object;
    },

    toOrderedMap: function() {
      // Use Late Binding here to solve the circular dependency.
      return OrderedMap(this.toKeyedSeq());
    },

    toOrderedSet: function() {
      // Use Late Binding here to solve the circular dependency.
      return OrderedSet(isKeyed(this) ? this.valueSeq() : this);
    },

    toSet: function() {
      // Use Late Binding here to solve the circular dependency.
      return Set(isKeyed(this) ? this.valueSeq() : this);
    },

    toSetSeq: function() {
      return new ToSetSequence(this);
    },

    toSeq: function() {
      return isIndexed(this) ? this.toIndexedSeq() :
        isKeyed(this) ? this.toKeyedSeq() :
        this.toSetSeq();
    },

    toStack: function() {
      // Use Late Binding here to solve the circular dependency.
      return Stack(isKeyed(this) ? this.valueSeq() : this);
    },

    toList: function() {
      // Use Late Binding here to solve the circular dependency.
      return List(isKeyed(this) ? this.valueSeq() : this);
    },


    // ### Common JavaScript methods and properties

    toString: function() {
      return '[Iterable]';
    },

    __toString: function(head, tail) {
      if (this.size === 0) {
        return head + tail;
      }
      return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail;
    },


    // ### ES6 Collection methods (ES6 Array and Map)

    concat: function() {var values = SLICE$0.call(arguments, 0);
      return reify(this, concatFactory(this, values));
    },

    includes: function(searchValue) {
      return this.some(function(value ) {return is(value, searchValue)});
    },

    entries: function() {
      return this.__iterator(ITERATE_ENTRIES);
    },

    every: function(predicate, context) {
      assertNotInfinite(this.size);
      var returnValue = true;
      this.__iterate(function(v, k, c)  {
        if (!predicate.call(context, v, k, c)) {
          returnValue = false;
          return false;
        }
      });
      return returnValue;
    },

    filter: function(predicate, context) {
      return reify(this, filterFactory(this, predicate, context, true));
    },

    find: function(predicate, context, notSetValue) {
      var entry = this.findEntry(predicate, context);
      return entry ? entry[1] : notSetValue;
    },

    forEach: function(sideEffect, context) {
      assertNotInfinite(this.size);
      return this.__iterate(context ? sideEffect.bind(context) : sideEffect);
    },

    join: function(separator) {
      assertNotInfinite(this.size);
      separator = separator !== undefined ? '' + separator : ',';
      var joined = '';
      var isFirst = true;
      this.__iterate(function(v ) {
        isFirst ? (isFirst = false) : (joined += separator);
        joined += v !== null && v !== undefined ? v.toString() : '';
      });
      return joined;
    },

    keys: function() {
      return this.__iterator(ITERATE_KEYS);
    },

    map: function(mapper, context) {
      return reify(this, mapFactory(this, mapper, context));
    },

    reduce: function(reducer, initialReduction, context) {
      assertNotInfinite(this.size);
      var reduction;
      var useFirst;
      if (arguments.length < 2) {
        useFirst = true;
      } else {
        reduction = initialReduction;
      }
      this.__iterate(function(v, k, c)  {
        if (useFirst) {
          useFirst = false;
          reduction = v;
        } else {
          reduction = reducer.call(context, reduction, v, k, c);
        }
      });
      return reduction;
    },

    reduceRight: function(reducer, initialReduction, context) {
      var reversed = this.toKeyedSeq().reverse();
      return reversed.reduce.apply(reversed, arguments);
    },

    reverse: function() {
      return reify(this, reverseFactory(this, true));
    },

    slice: function(begin, end) {
      return reify(this, sliceFactory(this, begin, end, true));
    },

    some: function(predicate, context) {
      return !this.every(not(predicate), context);
    },

    sort: function(comparator) {
      return reify(this, sortFactory(this, comparator));
    },

    values: function() {
      return this.__iterator(ITERATE_VALUES);
    },


    // ### More sequential methods

    butLast: function() {
      return this.slice(0, -1);
    },

    isEmpty: function() {
      return this.size !== undefined ? this.size === 0 : !this.some(function()  {return true});
    },

    count: function(predicate, context) {
      return ensureSize(
        predicate ? this.toSeq().filter(predicate, context) : this
      );
    },

    countBy: function(grouper, context) {
      return countByFactory(this, grouper, context);
    },

    equals: function(other) {
      return deepEqual(this, other);
    },

    entrySeq: function() {
      var iterable = this;
      if (iterable._cache) {
        // We cache as an entries array, so we can just return the cache!
        return new ArraySeq(iterable._cache);
      }
      var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq();
      entriesSequence.fromEntrySeq = function()  {return iterable.toSeq()};
      return entriesSequence;
    },

    filterNot: function(predicate, context) {
      return this.filter(not(predicate), context);
    },

    findEntry: function(predicate, context, notSetValue) {
      var found = notSetValue;
      this.__iterate(function(v, k, c)  {
        if (predicate.call(context, v, k, c)) {
          found = [k, v];
          return false;
        }
      });
      return found;
    },

    findKey: function(predicate, context) {
      var entry = this.findEntry(predicate, context);
      return entry && entry[0];
    },

    findLast: function(predicate, context, notSetValue) {
      return this.toKeyedSeq().reverse().find(predicate, context, notSetValue);
    },

    findLastEntry: function(predicate, context, notSetValue) {
      return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue);
    },

    findLastKey: function(predicate, context) {
      return this.toKeyedSeq().reverse().findKey(predicate, context);
    },

    first: function() {
      return this.find(returnTrue);
    },

    flatMap: function(mapper, context) {
      return reify(this, flatMapFactory(this, mapper, context));
    },

    flatten: function(depth) {
      return reify(this, flattenFactory(this, depth, true));
    },

    fromEntrySeq: function() {
      return new FromEntriesSequence(this);
    },

    get: function(searchKey, notSetValue) {
      return this.find(function(_, key)  {return is(key, searchKey)}, undefined, notSetValue);
    },

    getIn: function(searchKeyPath, notSetValue) {
      var nested = this;
      // Note: in an ES6 environment, we would prefer:
      // for (var key of searchKeyPath) {
      var iter = forceIterator(searchKeyPath);
      var step;
      while (!(step = iter.next()).done) {
        var key = step.value;
        nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET;
        if (nested === NOT_SET) {
          return notSetValue;
        }
      }
      return nested;
    },

    groupBy: function(grouper, context) {
      return groupByFactory(this, grouper, context);
    },

    has: function(searchKey) {
      return this.get(searchKey, NOT_SET) !== NOT_SET;
    },

    hasIn: function(searchKeyPath) {
      return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET;
    },

    isSubset: function(iter) {
      iter = typeof iter.includes === 'function' ? iter : Iterable(iter);
      return this.every(function(value ) {return iter.includes(value)});
    },

    isSuperset: function(iter) {
      iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter);
      return iter.isSubset(this);
    },

    keyOf: function(searchValue) {
      return this.findKey(function(value ) {return is(value, searchValue)});
    },

    keySeq: function() {
      return this.toSeq().map(keyMapper).toIndexedSeq();
    },

    last: function() {
      return this.toSeq().reverse().first();
    },

    lastKeyOf: function(searchValue) {
      return this.toKeyedSeq().reverse().keyOf(searchValue);
    },

    max: function(comparator) {
      return maxFactory(this, comparator);
    },

    maxBy: function(mapper, comparator) {
      return maxFactory(this, comparator, mapper);
    },

    min: function(comparator) {
      return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator);
    },

    minBy: function(mapper, comparator) {
      return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper);
    },

    rest: function() {
      return this.slice(1);
    },

    skip: function(amount) {
      return this.slice(Math.max(0, amount));
    },

    skipLast: function(amount) {
      return reify(this, this.toSeq().reverse().skip(amount).reverse());
    },

    skipWhile: function(predicate, context) {
      return reify(this, skipWhileFactory(this, predicate, context, true));
    },

    skipUntil: function(predicate, context) {
      return this.skipWhile(not(predicate), context);
    },

    sortBy: function(mapper, comparator) {
      return reify(this, sortFactory(this, comparator, mapper));
    },

    take: function(amount) {
      return this.slice(0, Math.max(0, amount));
    },

    takeLast: function(amount) {
      return reify(this, this.toSeq().reverse().take(amount).reverse());
    },

    takeWhile: function(predicate, context) {
      return reify(this, takeWhileFactory(this, predicate, context));
    },

    takeUntil: function(predicate, context) {
      return this.takeWhile(not(predicate), context);
    },

    valueSeq: function() {
      return this.toIndexedSeq();
    },


    // ### Hashable Object

    hashCode: function() {
      return this.__hash || (this.__hash = hashIterable(this));
    }


    // ### Internal

    // abstract __iterate(fn, reverse)

    // abstract __iterator(type, reverse)
  });

  // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@';
  // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@';
  // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@';
  // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@';

  var IterablePrototype = Iterable.prototype;
  IterablePrototype[IS_ITERABLE_SENTINEL] = true;
  IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values;
  IterablePrototype.__toJS = IterablePrototype.toArray;
  IterablePrototype.__toStringMapper = quoteString;
  IterablePrototype.inspect =
  IterablePrototype.toSource = function() { return this.toString(); };
  IterablePrototype.chain = IterablePrototype.flatMap;
  IterablePrototype.contains = IterablePrototype.includes;

  mixin(KeyedIterable, {

    // ### More sequential methods

    flip: function() {
      return reify(this, flipFactory(this));
    },

    mapEntries: function(mapper, context) {var this$0 = this;
      var iterations = 0;
      return reify(this,
        this.toSeq().map(
          function(v, k)  {return mapper.call(context, [k, v], iterations++, this$0)}
        ).fromEntrySeq()
      );
    },

    mapKeys: function(mapper, context) {var this$0 = this;
      return reify(this,
        this.toSeq().flip().map(
          function(k, v)  {return mapper.call(context, k, v, this$0)}
        ).flip()
      );
    }

  });

  var KeyedIterablePrototype = KeyedIterable.prototype;
  KeyedIterablePrototype[IS_KEYED_SENTINEL] = true;
  KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries;
  KeyedIterablePrototype.__toJS = IterablePrototype.toObject;
  KeyedIterablePrototype.__toStringMapper = function(v, k)  {return JSON.stringify(k) + ': ' + quoteString(v)};



  mixin(IndexedIterable, {

    // ### Conversion to other types

    toKeyedSeq: function() {
      return new ToKeyedSequence(this, false);
    },


    // ### ES6 Collection methods (ES6 Array and Map)

    filter: function(predicate, context) {
      return reify(this, filterFactory(this, predicate, context, false));
    },

    findIndex: function(predicate, context) {
      var entry = this.findEntry(predicate, context);
      return entry ? entry[0] : -1;
    },

    indexOf: function(searchValue) {
      var key = this.keyOf(searchValue);
      return key === undefined ? -1 : key;
    },

    lastIndexOf: function(searchValue) {
      var key = this.lastKeyOf(searchValue);
      return key === undefined ? -1 : key;
    },

    reverse: function() {
      return reify(this, reverseFactory(this, false));
    },

    slice: function(begin, end) {
      return reify(this, sliceFactory(this, begin, end, false));
    },

    splice: function(index, removeNum /*, ...values*/) {
      var numArgs = arguments.length;
      removeNum = Math.max(removeNum | 0, 0);
      if (numArgs === 0 || (numArgs === 2 && !removeNum)) {
        return this;
      }
      // If index is negative, it should resolve relative to the size of the
      // collection. However size may be expensive to compute if not cached, so
      // only call count() if the number is in fact negative.
      index = resolveBegin(index, index < 0 ? this.count() : this.size);
      var spliced = this.slice(0, index);
      return reify(
        this,
        numArgs === 1 ?
          spliced :
          spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum))
      );
    },


    // ### More collection methods

    findLastIndex: function(predicate, context) {
      var entry = this.findLastEntry(predicate, context);
      return entry ? entry[0] : -1;
    },

    first: function() {
      return this.get(0);
    },

    flatten: function(depth) {
      return reify(this, flattenFactory(this, depth, false));
    },

    get: function(index, notSetValue) {
      index = wrapIndex(this, index);
      return (index < 0 || (this.size === Infinity ||
          (this.size !== undefined && index > this.size))) ?
        notSetValue :
        this.find(function(_, key)  {return key === index}, undefined, notSetValue);
    },

    has: function(index) {
      index = wrapIndex(this, index);
      return index >= 0 && (this.size !== undefined ?
        this.size === Infinity || index < this.size :
        this.indexOf(index) !== -1
      );
    },

    interpose: function(separator) {
      return reify(this, interposeFactory(this, separator));
    },

    interleave: function(/*...iterables*/) {
      var iterables = [this].concat(arrCopy(arguments));
      var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables);
      var interleaved = zipped.flatten(true);
      if (zipped.size) {
        interleaved.size = zipped.size * iterables.length;
      }
      return reify(this, interleaved);
    },

    keySeq: function() {
      return Range(0, this.size);
    },

    last: function() {
      return this.get(-1);
    },

    skipWhile: function(predicate, context) {
      return reify(this, skipWhileFactory(this, predicate, context, false));
    },

    zip: function(/*, ...iterables */) {
      var iterables = [this].concat(arrCopy(arguments));
      return reify(this, zipWithFactory(this, defaultZipper, iterables));
    },

    zipWith: function(zipper/*, ...iterables */) {
      var iterables = arrCopy(arguments);
      iterables[0] = this;
      return reify(this, zipWithFactory(this, zipper, iterables));
    }

  });

  IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true;
  IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true;



  mixin(SetIterable, {

    // ### ES6 Collection methods (ES6 Array and Map)

    get: function(value, notSetValue) {
      return this.has(value) ? value : notSetValue;
    },

    includes: function(value) {
      return this.has(value);
    },


    // ### More sequential methods

    keySeq: function() {
      return this.valueSeq();
    }

  });

  SetIterable.prototype.has = IterablePrototype.includes;
  SetIterable.prototype.contains = SetIterable.prototype.includes;


  // Mixin subclasses

  mixin(KeyedSeq, KeyedIterable.prototype);
  mixin(IndexedSeq, IndexedIterable.prototype);
  mixin(SetSeq, SetIterable.prototype);

  mixin(KeyedCollection, KeyedIterable.prototype);
  mixin(IndexedCollection, IndexedIterable.prototype);
  mixin(SetCollection, SetIterable.prototype);


  // #pragma Helper functions

  function keyMapper(v, k) {
    return k;
  }

  function entryMapper(v, k) {
    return [k, v];
  }

  function not(predicate) {
    return function() {
      return !predicate.apply(this, arguments);
    }
  }

  function neg(predicate) {
    return function() {
      return -predicate.apply(this, arguments);
    }
  }

  function quoteString(value) {
    return typeof value === 'string' ? JSON.stringify(value) : String(value);
  }

  function defaultZipper() {
    return arrCopy(arguments);
  }

  function defaultNegComparator(a, b) {
    return a < b ? 1 : a > b ? -1 : 0;
  }

  function hashIterable(iterable) {
    if (iterable.size === Infinity) {
      return 0;
    }
    var ordered = isOrdered(iterable);
    var keyed = isKeyed(iterable);
    var h = ordered ? 1 : 0;
    var size = iterable.__iterate(
      keyed ?
        ordered ?
          function(v, k)  { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } :
          function(v, k)  { h = h + hashMerge(hash(v), hash(k)) | 0; } :
        ordered ?
          function(v ) { h = 31 * h + hash(v) | 0; } :
          function(v ) { h = h + hash(v) | 0; }
    );
    return murmurHashOfSize(size, h);
  }

  function murmurHashOfSize(size, h) {
    h = imul(h, 0xCC9E2D51);
    h = imul(h << 15 | h >>> -15, 0x1B873593);
    h = imul(h << 13 | h >>> -13, 5);
    h = (h + 0xE6546B64 | 0) ^ size;
    h = imul(h ^ h >>> 16, 0x85EBCA6B);
    h = imul(h ^ h >>> 13, 0xC2B2AE35);
    h = smi(h ^ h >>> 16);
    return h;
  }

  function hashMerge(a, b) {
    return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int
  }

  var Immutable = {

    Iterable: Iterable,

    Seq: Seq,
    Collection: Collection,
    Map: Map,
    OrderedMap: OrderedMap,
    List: List,
    Stack: Stack,
    Set: Set,
    OrderedSet: OrderedSet,

    Record: Record,
    Range: Range,
    Repeat: Repeat,

    is: is,
    fromJS: fromJS

  };

  return Immutable;

}));

/***/ }),
/* 103 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return async; });
/* harmony import */ var _AsyncAction__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(229);
/* harmony import */ var _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(225);
/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */


var async = /*@__PURE__*/ new _AsyncScheduler__WEBPACK_IMPORTED_MODULE_1__[/* AsyncScheduler */ "a"](_AsyncAction__WEBPACK_IMPORTED_MODULE_0__[/* AsyncAction */ "a"]);
//# sourceMappingURL=async.js.map


/***/ }),
/* 104 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UnitsRepresentation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(115);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(89);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(16);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(23);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(45);
/* harmony import */ var _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(130);
/* harmony import */ var _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(131);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(1);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(6);
/* harmony import */ var _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(77);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */















function UnitsRepresentation(label, ctx, getParams, visualCtor) {
    var version = 0;
    var updated = new rxjs__WEBPACK_IMPORTED_MODULE_4__[/* Subject */ "a"]();
    var materialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_5__[/* getNextMaterialId */ "c"])();
    var renderObjects = [];
    var _state = _representation__WEBPACK_IMPORTED_MODULE_2__[/* StructureRepresentationStateBuilder */ "c"].create();
    var visuals = new Map();
    var _structure;
    var _groups;
    var _params;
    var _props;
    var _theme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_6__[/* Theme */ "a"].createEmpty();
    function createOrUpdate(props, structure) {
        var _this = this;
        if (props === void 0) { props = {}; }
        if (structure && structure !== _structure) {
            _params = getParams(ctx, structure);
            if (!_props)
                _props = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(_params);
        }
        _props = Object.assign({}, _props, props);
        return _mol_task__WEBPACK_IMPORTED_MODULE_7__[/* Task */ "b"].create('Creating or updating UnitsRepresentation', function (runtime) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var i, group, visual, promise, oldVisuals, i, group, visualGroup, visual, promise, arr, visual, promise, i, group, visualGroup, promise, visualsList_1, i, il, visual, promise;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(!_structure && !structure)) return [3 /*break*/, 1];
                        throw new Error('missing structure');
                    case 1:
                        if (!(structure && !_structure)) return [3 /*break*/, 8];
                        // console.log(label, 'initial structure');
                        // First call with a structure, create visuals for each group.
                        _groups = structure.unitSymmetryGroups;
                        i = 0;
                        _a.label = 2;
                    case 2:
                        if (!(i < _groups.length)) return [3 /*break*/, 7];
                        group = _groups[i];
                        visual = visualCtor(materialId);
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, { group: group, structure: structure });
                        if (!promise) return [3 /*break*/, 4];
                        return [4 /*yield*/, promise];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4:
                        // ensure state is current for new visual
                        setVisualState(visual, group, _state);
                        visuals.set(group.hashCode, { visual: visual, group: group });
                        if (!runtime.shouldUpdate) return [3 /*break*/, 6];
                        return [4 /*yield*/, runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length })];
                    case 5:
                        _a.sent();
                        _a.label = 6;
                    case 6:
                        i++;
                        return [3 /*break*/, 2];
                    case 7: return [3 /*break*/, 34];
                    case 8:
                        if (!(structure && !_mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].areEquivalent(structure, _structure))) return [3 /*break*/, 19];
                        // Tries to re-use existing visuals for the groups of the new structure.
                        // Creates additional visuals if needed, destroys left-over visuals.
                        _groups = structure.unitSymmetryGroups;
                        oldVisuals = visuals;
                        visuals = new Map();
                        i = 0;
                        _a.label = 9;
                    case 9:
                        if (!(i < _groups.length)) return [3 /*break*/, 18];
                        group = _groups[i];
                        visualGroup = oldVisuals.get(group.hashCode);
                        if (!visualGroup) return [3 /*break*/, 12];
                        visual = visualGroup.visual;
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, { group: group, structure: structure });
                        if (!promise) return [3 /*break*/, 11];
                        return [4 /*yield*/, promise];
                    case 10:
                        _a.sent();
                        _a.label = 11;
                    case 11:
                        visuals.set(group.hashCode, { visual: visual, group: group });
                        oldVisuals.delete(group.hashCode);
                        // Remove highlight
                        // TODO: remove selection too??
                        if (visual.renderObject) {
                            arr = visual.renderObject.values.tMarker.ref.value.array;
                            Object(_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__[/* applyMarkerAction */ "c"])(arr, _mol_data_int__WEBPACK_IMPORTED_MODULE_13__["Interval"].ofBounds(0, arr.length), _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__[/* MarkerAction */ "a"].RemoveHighlight);
                        }
                        return [3 /*break*/, 15];
                    case 12:
                        visual = visualCtor(materialId);
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, { group: group, structure: structure });
                        if (!promise) return [3 /*break*/, 14];
                        return [4 /*yield*/, promise];
                    case 13:
                        _a.sent();
                        _a.label = 14;
                    case 14:
                        // ensure state is current for new visual
                        setVisualState(visual, group, _state);
                        visuals.set(group.hashCode, { visual: visual, group: group });
                        _a.label = 15;
                    case 15:
                        if (!runtime.shouldUpdate) return [3 /*break*/, 17];
                        return [4 /*yield*/, runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length })];
                    case 16:
                        _a.sent();
                        _a.label = 17;
                    case 17:
                        i++;
                        return [3 /*break*/, 9];
                    case 18:
                        oldVisuals.forEach(function (_a) {
                            var visual = _a.visual;
                            // console.log(label, 'removed unused visual');
                            visual.destroy();
                        });
                        return [3 /*break*/, 34];
                    case 19:
                        if (!(structure && structure !== _structure && _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].areEquivalent(structure, _structure))) return [3 /*break*/, 28];
                        // console.log(label, 'structures equivalent but not identical');
                        // Expects that for structures with the same hashCode,
                        // the unitSymmetryGroups are the same as well.
                        // Re-uses existing visuals for the groups of the new structure.
                        _groups = structure.unitSymmetryGroups;
                        i = 0;
                        _a.label = 20;
                    case 20:
                        if (!(i < _groups.length)) return [3 /*break*/, 27];
                        group = _groups[i];
                        visualGroup = visuals.get(group.hashCode);
                        if (!visualGroup) return [3 /*break*/, 23];
                        promise = visualGroup.visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, { group: group, structure: structure });
                        if (!promise) return [3 /*break*/, 22];
                        return [4 /*yield*/, promise];
                    case 21:
                        _a.sent();
                        _a.label = 22;
                    case 22:
                        visualGroup.group = group;
                        return [3 /*break*/, 24];
                    case 23: throw new Error("expected to find visual for hashCode " + group.hashCode);
                    case 24:
                        if (!runtime.shouldUpdate) return [3 /*break*/, 26];
                        return [4 /*yield*/, runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: _groups.length })];
                    case 25:
                        _a.sent();
                        _a.label = 26;
                    case 26:
                        i++;
                        return [3 /*break*/, 20];
                    case 27: return [3 /*break*/, 34];
                    case 28:
                        visualsList_1 = [];
                        visuals.forEach(function (_a) {
                            var visual = _a.visual, group = _a.group;
                            return visualsList_1.push([visual, group]);
                        });
                        i = 0, il = visualsList_1.length;
                        _a.label = 29;
                    case 29:
                        if (!(i < il)) return [3 /*break*/, 34];
                        visual = visualsList_1[i][0];
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props);
                        if (!promise) return [3 /*break*/, 31];
                        return [4 /*yield*/, promise];
                    case 30:
                        _a.sent();
                        _a.label = 31;
                    case 31:
                        if (!runtime.shouldUpdate) return [3 /*break*/, 33];
                        return [4 /*yield*/, runtime.update({ message: 'Creating or updating UnitsVisual', current: i, max: il })];
                    case 32:
                        _a.sent();
                        _a.label = 33;
                    case 33:
                        ++i;
                        return [3 /*break*/, 29];
                    case 34:
                        // update list of renderObjects
                        renderObjects.length = 0;
                        visuals.forEach(function (_a) {
                            var visual = _a.visual;
                            if (visual.renderObject)
                                renderObjects.push(visual.renderObject);
                        });
                        // set new structure
                        if (structure)
                            _structure = structure;
                        // increment version
                        updated.next(version++);
                        return [2 /*return*/];
                }
            });
        }); });
    }
    function getLoci(pickingId) {
        if (pickingId === undefined)
            return _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Loci(_structure);
        var loci = _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["EmptyLoci"];
        visuals.forEach(function (_a) {
            var visual = _a.visual;
            var _loci = visual.getLoci(pickingId);
            if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isEmptyLoci"])(_loci))
                loci = _loci;
        });
        return loci;
    }
    function mark(loci, action) {
        if (!_structure)
            return false;
        if (!_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__[/* MarkerActions */ "b"].is(_state.markerActions, action))
            return false;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].isLoci(loci) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Loci.is(loci) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Bond"].isLoci(loci)) {
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].areRootsEquivalent(loci.structure, _structure))
                return false;
            // Remap `loci` from equivalent structure to the current `_structure`
            loci = _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["Loci"].remap(loci, _structure);
        }
        else if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isEveryLoci"])(loci) && !Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isDataLoci"])(loci)) {
            return false;
        }
        if (_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["Loci"].isEmpty(loci))
            return false;
        var changed = false;
        visuals.forEach(function (_a) {
            var visual = _a.visual;
            changed = visual.mark(loci, action) || changed;
        });
        return changed;
    }
    function setVisualState(visual, group, state) {
        var visible = state.visible, alphaFactor = state.alphaFactor, pickable = state.pickable, overpaint = state.overpaint, transparency = state.transparency, clipping = state.clipping, transform = state.transform, unitTransforms = state.unitTransforms;
        if (visible !== undefined)
            visual.setVisibility(visible);
        if (alphaFactor !== undefined)
            visual.setAlphaFactor(alphaFactor);
        if (pickable !== undefined)
            visual.setPickable(pickable);
        if (overpaint !== undefined)
            visual.setOverpaint(overpaint);
        if (transparency !== undefined)
            visual.setTransparency(transparency);
        if (clipping !== undefined)
            visual.setClipping(clipping);
        if (transform !== undefined)
            visual.setTransform(transform);
        if (unitTransforms !== undefined) {
            if (unitTransforms) {
                // console.log(group.hashCode, unitTransforms.getSymmetryGroupTransforms(group))
                visual.setTransform(undefined, unitTransforms.getSymmetryGroupTransforms(group));
            }
            else {
                visual.setTransform(undefined, null);
            }
        }
    }
    function setState(state) {
        var visible = state.visible, alphaFactor = state.alphaFactor, pickable = state.pickable, overpaint = state.overpaint, transparency = state.transparency, clipping = state.clipping, transform = state.transform, unitTransforms = state.unitTransforms, syncManually = state.syncManually, markerActions = state.markerActions;
        var newState = {};
        if (visible !== _state.visible)
            newState.visible = visible;
        if (alphaFactor !== _state.alphaFactor)
            newState.alphaFactor = alphaFactor;
        if (pickable !== _state.pickable)
            newState.pickable = pickable;
        if (overpaint !== undefined && !_mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_10__[/* Overpaint */ "a"].areEqual(overpaint, _state.overpaint)) {
            if (_structure) {
                newState.overpaint = _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_10__[/* Overpaint */ "a"].remap(overpaint, _structure);
            }
        }
        if (transparency !== undefined && !_mol_theme_transparency__WEBPACK_IMPORTED_MODULE_11__[/* Transparency */ "a"].areEqual(transparency, _state.transparency)) {
            if (_structure) {
                newState.transparency = _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_11__[/* Transparency */ "a"].remap(transparency, _structure);
            }
        }
        if (clipping !== undefined && !_mol_theme_clipping__WEBPACK_IMPORTED_MODULE_14__[/* Clipping */ "a"].areEqual(clipping, _state.clipping)) {
            if (_structure) {
                newState.clipping = _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_14__[/* Clipping */ "a"].remap(clipping, _structure);
            }
        }
        if (transform !== undefined && !_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_12__["Mat4"].areEqual(transform, _state.transform, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_12__["EPSILON"])) {
            newState.transform = transform;
        }
        if (unitTransforms !== _state.unitTransforms || (unitTransforms === null || unitTransforms === void 0 ? void 0 : unitTransforms.version) !== state.unitTransformsVersion) {
            newState.unitTransforms = unitTransforms;
            _state.unitTransformsVersion = unitTransforms ? unitTransforms === null || unitTransforms === void 0 ? void 0 : unitTransforms.version : -1;
        }
        if (syncManually !== _state.syncManually)
            newState.syncManually = syncManually;
        if (markerActions !== _state.markerActions)
            newState.markerActions = markerActions;
        visuals.forEach(function (_a) {
            var visual = _a.visual, group = _a.group;
            return setVisualState(visual, group, newState);
        });
        _representation__WEBPACK_IMPORTED_MODULE_2__[/* StructureRepresentationStateBuilder */ "c"].update(_state, newState);
    }
    function setTheme(theme) {
        _theme = theme;
    }
    function destroy() {
        visuals.forEach(function (_a) {
            var visual = _a.visual;
            return visual.destroy();
        });
        visuals.clear();
    }
    return {
        label: label,
        get groupCount() {
            var groupCount = 0;
            visuals.forEach(function (_a) {
                var visual = _a.visual;
                if (visual.renderObject)
                    groupCount += visual.groupCount;
            });
            return groupCount;
        },
        get props() { return _props; },
        get params() { return _params; },
        get state() { return _state; },
        get theme() { return _theme; },
        renderObjects: renderObjects,
        updated: updated,
        createOrUpdate: createOrUpdate,
        setState: setState,
        setTheme: setTheme,
        getLoci: getLoci,
        mark: mark,
        destroy: destroy
    };
}
//# sourceMappingURL=units-representation.js.map

/***/ }),
/* 105 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(82);
/* harmony import */ var _vec3__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(137);
/* harmony import */ var _misc__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */



function Mat4() {
    return Mat4.zero();
}
/**
 * Stores a 4x4 matrix in a column major (j * 4 + i indexing) format.
 */
(function (Mat4) {
    function zero() {
        // force double backing array by 0.1.
        var ret = [0.1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        ret[0] = 0.0;
        return ret;
    }
    Mat4.zero = zero;
    function identity() {
        var out = zero();
        out[0] = 1;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = 1;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = 1;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
    }
    Mat4.identity = identity;
    function setIdentity(mat) {
        mat[0] = 1;
        mat[1] = 0;
        mat[2] = 0;
        mat[3] = 0;
        mat[4] = 0;
        mat[5] = 1;
        mat[6] = 0;
        mat[7] = 0;
        mat[8] = 0;
        mat[9] = 0;
        mat[10] = 1;
        mat[11] = 0;
        mat[12] = 0;
        mat[13] = 0;
        mat[14] = 0;
        mat[15] = 1;
        return mat;
    }
    Mat4.setIdentity = setIdentity;
    function setZero(mat) {
        for (var i = 0; i < 16; i++)
            mat[i] = 0;
        return mat;
    }
    Mat4.setZero = setZero;
    function ofRows(rows) {
        var out = zero();
        for (var i = 0; i < 4; i++) {
            var r = rows[i];
            for (var j = 0; j < 4; j++) {
                out[4 * j + i] = r[j];
            }
        }
        return out;
    }
    Mat4.ofRows = ofRows;
    var _id = identity();
    function isIdentity(m, eps) {
        return areEqual(m, _id, typeof eps === 'undefined' ? _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"] : eps);
    }
    Mat4.isIdentity = isIdentity;
    function hasNaN(m) {
        for (var i = 0; i < 16; i++)
            if (isNaN(m[i]))
                return true;
        return false;
    }
    Mat4.hasNaN = hasNaN;
    function areEqual(a, b, eps) {
        for (var i = 0; i < 16; i++) {
            if (Math.abs(a[i] - b[i]) > eps)
                return false;
        }
        return true;
    }
    Mat4.areEqual = areEqual;
    function setValue(a, i, j, value) {
        a[4 * j + i] = value;
    }
    Mat4.setValue = setValue;
    function getValue(a, i, j) {
        return a[4 * j + i];
    }
    Mat4.getValue = getValue;
    function toArray(a, out, offset) {
        out[offset + 0] = a[0];
        out[offset + 1] = a[1];
        out[offset + 2] = a[2];
        out[offset + 3] = a[3];
        out[offset + 4] = a[4];
        out[offset + 5] = a[5];
        out[offset + 6] = a[6];
        out[offset + 7] = a[7];
        out[offset + 8] = a[8];
        out[offset + 9] = a[9];
        out[offset + 10] = a[10];
        out[offset + 11] = a[11];
        out[offset + 12] = a[12];
        out[offset + 13] = a[13];
        out[offset + 14] = a[14];
        out[offset + 15] = a[15];
        return out;
    }
    Mat4.toArray = toArray;
    function fromArray(a, array, offset) {
        a[0] = array[offset + 0];
        a[1] = array[offset + 1];
        a[2] = array[offset + 2];
        a[3] = array[offset + 3];
        a[4] = array[offset + 4];
        a[5] = array[offset + 5];
        a[6] = array[offset + 6];
        a[7] = array[offset + 7];
        a[8] = array[offset + 8];
        a[9] = array[offset + 9];
        a[10] = array[offset + 10];
        a[11] = array[offset + 11];
        a[12] = array[offset + 12];
        a[13] = array[offset + 13];
        a[14] = array[offset + 14];
        a[15] = array[offset + 15];
        return a;
    }
    Mat4.fromArray = fromArray;
    function fromBasis(a, x, y, z) {
        Mat4.setZero(a);
        Mat4.setValue(a, 0, 0, x[0]);
        Mat4.setValue(a, 1, 0, x[1]);
        Mat4.setValue(a, 2, 0, x[2]);
        Mat4.setValue(a, 0, 1, y[0]);
        Mat4.setValue(a, 1, 1, y[1]);
        Mat4.setValue(a, 2, 1, y[2]);
        Mat4.setValue(a, 0, 2, z[0]);
        Mat4.setValue(a, 1, 2, z[1]);
        Mat4.setValue(a, 2, 2, z[2]);
        Mat4.setValue(a, 3, 3, 1);
        return a;
    }
    Mat4.fromBasis = fromBasis;
    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;
    }
    Mat4.copy = copy;
    function clone(a) {
        return Mat4.copy(Mat4.zero(), a);
    }
    Mat4.clone = clone;
    /**
     * Returns the translation vector component of a transformation matrix.
     */
    function getTranslation(out, mat) {
        out[0] = mat[12];
        out[1] = mat[13];
        out[2] = mat[14];
        return out;
    }
    Mat4.getTranslation = getTranslation;
    /**
     * Returns the scaling factor component of a transformation matrix.
     */
    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;
    }
    Mat4.getScaling = getScaling;
    /**
     * Returns a quaternion representing the rotational component of a transformation matrix.
     */
    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;
    }
    Mat4.getRotation = getRotation;
    function extractRotation(out, mat) {
        var scaleX = 1 / Math.sqrt(mat[0] * mat[0] + mat[1] * mat[1] + mat[2] * mat[2]);
        var scaleY = 1 / Math.sqrt(mat[4] * mat[4] + mat[5] * mat[5] + mat[6] * mat[6]);
        var scaleZ = 1 / Math.sqrt(mat[8] * mat[8] + mat[9] * mat[9] + mat[10] * mat[10]);
        out[0] = mat[0] * scaleX;
        out[1] = mat[1] * scaleX;
        out[2] = mat[2] * scaleX;
        out[3] = 0;
        out[4] = mat[4] * scaleY;
        out[5] = mat[5] * scaleY;
        out[6] = mat[6] * scaleY;
        out[7] = 0;
        out[8] = mat[8] * scaleZ;
        out[9] = mat[9] * scaleZ;
        out[10] = mat[10] * scaleZ;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
    }
    Mat4.extractRotation = extractRotation;
    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;
    }
    Mat4.transpose = transpose;
    function invert(out, a) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
        // Calculate the determinant
        var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
        if (!det) {
            console.warn('non-invertible matrix.', a);
            return out;
        }
        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;
    }
    Mat4.invert = invert;
    function mul(out, a, b) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15];
        // 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;
    }
    Mat4.mul = mul;
    /**
     * Like `mul` but with offsets into arrays
     */
    function mulOffset(out, a, b, oOut, oA, oB) {
        var a00 = a[0 + oA], a01 = a[1 + oA], a02 = a[2 + oA], a03 = a[3 + oA], a10 = a[4 + oA], a11 = a[5 + oA], a12 = a[6 + oA], a13 = a[7 + oA], a20 = a[8 + oA], a21 = a[9 + oA], a22 = a[10 + oA], a23 = a[11 + oA], a30 = a[12 + oA], a31 = a[13 + oA], a32 = a[14 + oA], a33 = a[15 + oA];
        // Cache only the current line of the second matrix
        var b0 = b[0 + oB], b1 = b[1 + oB], b2 = b[2 + oB], b3 = b[3 + oB];
        out[0 + oOut] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[1 + oOut] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[2 + oOut] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[3 + oOut] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[4 + oB];
        b1 = b[5 + oB];
        b2 = b[6 + oB];
        b3 = b[7 + oB];
        out[4 + oOut] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[5 + oOut] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[6 + oOut] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[7 + oOut] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[8 + oB];
        b1 = b[9 + oB];
        b2 = b[10 + oB];
        b3 = b[11 + oB];
        out[8 + oOut] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[9 + oOut] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[10 + oOut] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[11 + oOut] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        b0 = b[12 + oB];
        b1 = b[13 + oB];
        b2 = b[14 + oB];
        b3 = b[15 + oB];
        out[12 + oOut] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30;
        out[13 + oOut] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31;
        out[14 + oOut] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32;
        out[15 + oOut] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33;
        return out;
    }
    Mat4.mulOffset = mulOffset;
    function mul3(out, a, b, c) {
        return mul(out, mul(out, a, b), c);
    }
    Mat4.mul3 = mul3;
    /** Translate a Mat4 by the given Vec3 */
    function translate(out, a, v) {
        var x = v[0], y = v[1], z = v[2];
        var a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23;
        if (a === out) {
            out[12] = a[0] * x + a[4] * y + a[8] * z + a[12];
            out[13] = a[1] * x + a[5] * y + a[9] * z + a[13];
            out[14] = a[2] * x + a[6] * y + a[10] * z + a[14];
            out[15] = a[3] * x + a[7] * y + a[11] * z + a[15];
        }
        else {
            a00 = a[0];
            a01 = a[1];
            a02 = a[2];
            a03 = a[3];
            a10 = a[4];
            a11 = a[5];
            a12 = a[6];
            a13 = a[7];
            a20 = a[8];
            a21 = a[9];
            a22 = a[10];
            a23 = a[11];
            out[0] = a00;
            out[1] = a01;
            out[2] = a02;
            out[3] = a03;
            out[4] = a10;
            out[5] = a11;
            out[6] = a12;
            out[7] = a13;
            out[8] = a20;
            out[9] = a21;
            out[10] = a22;
            out[11] = a23;
            out[12] = a00 * x + a10 * y + a20 * z + a[12];
            out[13] = a01 * x + a11 * y + a21 * z + a[13];
            out[14] = a02 * x + a12 * y + a22 * z + a[14];
            out[15] = a03 * x + a13 * y + a23 * z + a[15];
        }
        return out;
    }
    Mat4.translate = translate;
    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;
    }
    Mat4.fromTranslation = fromTranslation;
    function setTranslation(out, v) {
        out[12] = v[0];
        out[13] = v[1];
        out[14] = v[2];
        return out;
    }
    Mat4.setTranslation = setTranslation;
    /**
     * 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.
     */
    function setAxes(out, view, right, up) {
        out[0] = right[0];
        out[4] = right[1];
        out[8] = right[2];
        out[1] = up[0];
        out[5] = up[1];
        out[9] = up[2];
        out[2] = view[0];
        out[6] = view[1];
        out[10] = view[2];
        return out;
    }
    Mat4.setAxes = setAxes;
    function rotate(out, a, rad, axis) {
        var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22;
        if (Math.abs(len) < _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"]) {
            return Mat4.identity();
        }
        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;
    }
    Mat4.rotate = rotate;
    function fromRotation(out, rad, axis) {
        var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t;
        if (Math.abs(len) < _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"]) {
            return setIdentity(out);
        }
        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;
    }
    Mat4.fromRotation = fromRotation;
    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;
    }
    Mat4.scale = scale;
    function scaleUniformly(out, a, scale) {
        out[0] = a[0] * scale;
        out[1] = a[1] * scale;
        out[2] = a[2] * scale;
        out[3] = a[3] * scale;
        out[4] = a[4] * scale;
        out[5] = a[5] * scale;
        out[6] = a[6] * scale;
        out[7] = a[7] * scale;
        out[8] = a[8] * scale;
        out[9] = a[9] * scale;
        out[10] = a[10] * scale;
        out[11] = a[11] * scale;
        out[12] = a[12];
        out[13] = a[13];
        out[14] = a[14];
        out[15] = a[15];
        return out;
    }
    Mat4.scaleUniformly = scaleUniformly;
    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;
    }
    Mat4.fromScaling = fromScaling;
    function fromUniformScaling(out, scale) {
        out[0] = scale;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = scale;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = scale;
        out[11] = 0;
        out[12] = 0;
        out[13] = 0;
        out[14] = 0;
        out[15] = 1;
        return out;
    }
    Mat4.fromUniformScaling = fromUniformScaling;
    /**
     * Copies the mat3 into upper-left 3x3 values.
     */
    function fromMat3(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        out[4] = a[3];
        out[5] = a[4];
        out[6] = a[5];
        out[8] = a[6];
        out[9] = a[7];
        out[10] = a[8];
        return out;
    }
    Mat4.fromMat3 = fromMat3;
    function makeTable(m) {
        var ret = '';
        for (var i = 0; i < 4; i++) {
            for (var j = 0; j < 4; j++) {
                ret += m[4 * j + i].toString();
                if (j < 3)
                    ret += ' ';
            }
            if (i < 3)
                ret += '\n';
        }
        return ret;
    }
    Mat4.makeTable = makeTable;
    function determinant(a) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
        // Calculate the determinant
        return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
    }
    Mat4.determinant = determinant;
    /**
     * Check if the matrix has the form
     * [ Rotation    Translation ]
     * [ 0           1           ]
     *
     * Allows for improper rotations
     */
    function isRotationAndTranslation(a, eps) {
        return _isRotationAndTranslation(a, typeof eps !== 'undefined' ? eps : _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"]);
    }
    Mat4.isRotationAndTranslation = isRotationAndTranslation;
    function _isRotationAndTranslation(a, eps) {
        var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a33 = a[15];
        if (!Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a33, 1, eps) || !Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a03, 0, eps) || !Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a13, 0, eps) || !Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a23, 0, eps)) {
            return false;
        }
        // use `abs` to allow for improper rotations
        var det3x3 = Math.abs(a00 * (a11 * a22 - a12 * a21) - a01 * (a10 * a22 - a12 * a20) + a02 * (a10 * a21 - a11 * a20));
        if (!Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(det3x3, 1, eps)) {
            return false;
        }
        return true;
    }
    /**
     * Check if the matrix has only translation and uniform scaling
     * [ S  0  0  X ]
     * [ 0  S  0  Y ]
     * [ 0  0  S  Z ]
     * [ 0  0  0  1 ]
     */
    function isTranslationAndUniformScaling(a, eps) {
        return _isTranslationAndUniformScaling(a, typeof eps !== 'undefined' ? eps : _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"]);
    }
    Mat4.isTranslationAndUniformScaling = isTranslationAndUniformScaling;
    function _isTranslationAndUniformScaling(a, eps) {
        var a00 = a[0];
        return (
        // 0 base scaling
        Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[1], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[2], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[3], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[4], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[5], a00, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[6], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[7], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[8], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[9], 0, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[10], a00, eps) &&
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[11], 0, eps) &&
            // 12, 13, 14 translation can be anything
            Object(_common__WEBPACK_IMPORTED_MODULE_0__[/* equalEps */ "b"])(a[15], 1, eps));
    }
    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;
    }
    Mat4.fromQuat = fromQuat;
    /**
     * Generates a perspective projection (frustum) matrix with the given bounds
     */
    function perspective(out, left, right, top, bottom, near, far) {
        var x = 2 * near / (right - left);
        var y = 2 * near / (top - bottom);
        var a = (right + left) / (right - left);
        var b = (top + bottom) / (top - bottom);
        var c = -(far + near) / (far - near);
        var d = -2 * far * near / (far - near);
        out[0] = x;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = y;
        out[6] = 0;
        out[7] = 0;
        out[8] = a;
        out[9] = b;
        out[10] = c;
        out[11] = -1;
        out[12] = 0;
        out[13] = 0;
        out[14] = d;
        out[15] = 0;
        return out;
    }
    Mat4.perspective = perspective;
    /**
     * Generates a orthogonal projection matrix with the given bounds
     */
    function ortho(out, left, right, top, bottom, near, far) {
        var w = 1.0 / (right - left);
        var h = 1.0 / (top - bottom);
        var p = 1.0 / (far - near);
        var x = (right + left) * w;
        var y = (top + bottom) * h;
        var z = (far + near) * p;
        out[0] = 2 * w;
        out[1] = 0;
        out[2] = 0;
        out[3] = 0;
        out[4] = 0;
        out[5] = 2 * h;
        out[6] = 0;
        out[7] = 0;
        out[8] = 0;
        out[9] = 0;
        out[10] = -2 * p;
        out[11] = 0;
        out[12] = -x;
        out[13] = -y;
        out[14] = -z;
        out[15] = 1;
        return out;
    }
    Mat4.ortho = ortho;
    /**
     * Generates a look-at matrix with the given eye position, focal point, and up axis
     */
    function lookAt(out, eye, center, up) {
        var x0, x1, x2, y0, y1, y2, z0, z1, z2, len;
        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) < _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"] &&
            Math.abs(eyey - centery) < _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"] &&
            Math.abs(eyez - centerz) < _common__WEBPACK_IMPORTED_MODULE_0__[/* EPSILON */ "a"]) {
            return setIdentity(out);
        }
        z0 = eyex - centerx;
        z1 = eyey - centery;
        z2 = eyez - centerz;
        len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2);
        z0 *= len;
        z1 *= len;
        z2 *= len;
        x0 = upy * z2 - upz * z1;
        x1 = upz * z0 - upx * z2;
        x2 = upx * z1 - upy * z0;
        len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2);
        if (!len) {
            x0 = 0;
            x1 = 0;
            x2 = 0;
        }
        else {
            len = 1 / len;
            x0 *= len;
            x1 *= len;
            x2 *= len;
        }
        y0 = z1 * x2 - z2 * x1;
        y1 = z2 * x0 - z0 * x2;
        y2 = z0 * x1 - z1 * x0;
        len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2);
        if (!len) {
            y0 = 0;
            y1 = 0;
            y2 = 0;
        }
        else {
            len = 1 / len;
            y0 *= len;
            y1 *= len;
            y2 *= len;
        }
        out[0] = x0;
        out[1] = y0;
        out[2] = z0;
        out[3] = 0;
        out[4] = x1;
        out[5] = y1;
        out[6] = z1;
        out[7] = 0;
        out[8] = x2;
        out[9] = y2;
        out[10] = z2;
        out[11] = 0;
        out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez);
        out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez);
        out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez);
        out[15] = 1;
        return out;
    }
    Mat4.lookAt = lookAt;
    /**
     * Generates a matrix that makes something look at something else.
     */
    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;
    }
    Mat4.targetTo = targetTo;
    /**
     * Perm is 0-indexed permutation
     */
    function fromPermutation(out, perm) {
        setZero(out);
        for (var i = 0; i < 4; i++) {
            var p = perm[i];
            setValue(out, i, p, 1);
        }
        return out;
    }
    Mat4.fromPermutation = fromPermutation;
    function getMaxScaleOnAxis(m) {
        var scaleXSq = m[0] * m[0] + m[1] * m[1] + m[2] * m[2];
        var scaleYSq = m[4] * m[4] + m[5] * m[5] + m[6] * m[6];
        var scaleZSq = m[8] * m[8] + m[9] * m[9] + m[10] * m[10];
        return Math.sqrt(Math.max(scaleXSq, scaleYSq, scaleZSq));
    }
    Mat4.getMaxScaleOnAxis = getMaxScaleOnAxis;
    var xAxis = _vec3__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(1, 0, 0);
    var yAxis = _vec3__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(0, 1, 0);
    var zAxis = _vec3__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(0, 0, 1);
    /** Rotation matrix for 90deg around x-axis */
    Mat4.rotX90 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(90), xAxis);
    /** Rotation matrix for 180deg around x-axis */
    Mat4.rotX180 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(180), xAxis);
    /** Rotation matrix for 90deg around y-axis */
    Mat4.rotY90 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(90), yAxis);
    /** Rotation matrix for 180deg around y-axis */
    Mat4.rotY180 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(180), yAxis);
    /** Rotation matrix for 270deg around y-axis */
    Mat4.rotY270 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(270), yAxis);
    /** Rotation matrix for 90deg around z-axis */
    Mat4.rotZ90 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(90), zAxis);
    /** Rotation matrix for 180deg around z-axis */
    Mat4.rotZ180 = Mat4.fromRotation(Mat4(), Object(_misc__WEBPACK_IMPORTED_MODULE_2__[/* degToRad */ "c"])(180), zAxis);
    /** Rotation matrix for 90deg around first x-axis and then y-axis */
    Mat4.rotXY90 = Mat4.mul(Mat4(), Mat4.rotX90, Mat4.rotY90);
    /** Rotation matrix for 90deg around first z-axis and then y-axis */
    Mat4.rotZY90 = Mat4.mul(Mat4(), Mat4.rotZ90, Mat4.rotY90);
    /** Rotation matrix for 90deg around first z-axis and then y-axis and then z-axis */
    Mat4.rotZYZ90 = Mat4.mul(Mat4(), Mat4.rotZY90, Mat4.rotZ90);
    /** Rotation matrix for 90deg around first z-axis and then 180deg around x-axis */
    Mat4.rotZ90X180 = Mat4.mul(Mat4(), Mat4.rotZ90, Mat4.rotX180);
    /** Rotation matrix for 90deg around first y-axis and then 180deg around z-axis */
    Mat4.rotY90Z180 = Mat4.mul(Mat4(), Mat4.rotY90, Mat4.rotZ180);
    /** Identity matrix */
    Mat4.id = Mat4.identity();
})(Mat4 || (Mat4 = {}));
/* harmony default export */ __webpack_exports__["a"] = (Mat4);
//# sourceMappingURL=mat4.js.map

/***/ }),
/* 106 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from CIFTools.js (https://github.com/dsehnal/CIFTools.js)
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var StringBuilder;
(function (StringBuilder) {
    function create(chunkCapacity) {
        if (chunkCapacity === void 0) { chunkCapacity = 512; }
        return {
            current: [],
            offset: 0,
            capacity: chunkCapacity,
            chunks: []
        };
    }
    StringBuilder.create = create;
    function getString(builder) {
        if (!builder.chunks.length) {
            if (builder.current.length === builder.offset)
                return builder.current.join('');
            return builder.current.splice(0, builder.offset).join('');
        }
        if (builder.offset > 0) {
            builder.chunks[builder.chunks.length] = builder.current.length === builder.offset
                ? builder.current.join('')
                : builder.current.slice(0, builder.offset).join('');
        }
        return builder.chunks.join('');
    }
    StringBuilder.getString = getString;
    function getSize(builder) {
        var size = 0;
        for (var _i = 0, _a = builder.chunks; _i < _a.length; _i++) {
            var c = _a[_i];
            size += c.length;
        }
        for (var i = 0; i < builder.offset; i++)
            size += builder.current[i].length;
        return size;
    }
    StringBuilder.getSize = getSize;
    function getChunks(builder) {
        if (builder.offset > 0) {
            if (builder.current.length === builder.offset)
                builder.chunks[builder.chunks.length] = builder.current.join('');
            else
                builder.chunks[builder.chunks.length] = builder.current.slice(0, builder.offset).join('');
            builder.offset = 0;
        }
        return builder.chunks;
    }
    StringBuilder.getChunks = getChunks;
    var __paddingSpaces = [];
    (function () {
        var s = '';
        for (var i = 0; i < 512 /* Count */; i++) {
            __paddingSpaces[i] = s;
            s = s + ' ';
        }
    })();
    function newline(builder) {
        writeSafe(builder, '\n');
    }
    StringBuilder.newline = newline;
    function whitespace(builder, len) {
        if (len > 0)
            writeSafe(builder, __paddingSpaces[len]);
    }
    StringBuilder.whitespace = whitespace;
    function whitespace1(builder) {
        writeSafe(builder, ' ');
    }
    StringBuilder.whitespace1 = whitespace1;
    function write(builder, val) {
        if (!val)
            return;
        if (builder.offset === builder.capacity) {
            builder.chunks[builder.chunks.length] = builder.current.join('');
            builder.offset = 0;
        }
        builder.current[builder.offset++] = val;
    }
    StringBuilder.write = write;
    /** Write without check. */
    function writeSafe(builder, val) {
        if (builder.offset === builder.capacity) {
            builder.chunks[builder.chunks.length] = builder.current.join('');
            builder.offset = 0;
        }
        builder.current[builder.offset++] = val;
    }
    StringBuilder.writeSafe = writeSafe;
    function writePadLeft(builder, val, totalWidth) {
        if (!val) {
            whitespace(builder, totalWidth);
            return;
        }
        var padding = totalWidth - val.length;
        whitespace(builder, padding);
        writeSafe(builder, val);
    }
    StringBuilder.writePadLeft = writePadLeft;
    function writePadRight(builder, val, totalWidth) {
        if (!val) {
            whitespace(builder, totalWidth);
            return;
        }
        var padding = totalWidth - val.length;
        writeSafe(builder, val);
        whitespace(builder, padding);
    }
    StringBuilder.writePadRight = writePadRight;
    function writeInteger(builder, val) {
        writeSafe(builder, '' + val);
    }
    StringBuilder.writeInteger = writeInteger;
    function writeIntegerAndSpace(builder, val) {
        writeSafe(builder, '' + val + ' ');
    }
    StringBuilder.writeIntegerAndSpace = writeIntegerAndSpace;
    function writeIntegerPadLeft(builder, val, totalWidth) {
        var s = '' + val;
        var padding = totalWidth - s.length;
        whitespace(builder, padding);
        writeSafe(builder, s);
    }
    StringBuilder.writeIntegerPadLeft = writeIntegerPadLeft;
    function writeIntegerPadRight(builder, val, totalWidth) {
        var s = '' + val;
        var padding = totalWidth - s.length;
        writeSafe(builder, s);
        whitespace(builder, padding);
    }
    StringBuilder.writeIntegerPadRight = writeIntegerPadRight;
    /**
     * @example writeFloat(123.2123, 100) -- 2 decim
     */
    function writeFloat(builder, val, precisionMultiplier) {
        writeSafe(builder, '' + Math.round(precisionMultiplier * val) / precisionMultiplier);
    }
    StringBuilder.writeFloat = writeFloat;
    function writeFloatPadLeft(builder, val, precisionMultiplier, totalWidth) {
        var s = '' + Math.round(precisionMultiplier * val) / precisionMultiplier;
        var padding = totalWidth - s.length;
        whitespace(builder, padding);
        writeSafe(builder, s);
    }
    StringBuilder.writeFloatPadLeft = writeFloatPadLeft;
    function writeFloatPadRight(builder, val, precisionMultiplier, totalWidth) {
        var s = '' + Math.round(precisionMultiplier * val) / precisionMultiplier;
        var padding = totalWidth - s.length;
        writeSafe(builder, s);
        whitespace(builder, padding);
    }
    StringBuilder.writeFloatPadRight = writeFloatPadRight;
})(StringBuilder || (StringBuilder = {}));
/* harmony default export */ __webpack_exports__["a"] = (StringBuilder);
//# sourceMappingURL=string-builder.js.map

/***/ }),
/* 107 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ArrayEncoderImpl */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArrayEncoder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ArrayEncoding; });
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9);
/* harmony import */ var _encoding__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(250);
/* harmony import */ var _classifier__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(260);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from CIFTools.js (https://github.com/dsehnal/CIFTools.js; MIT) and MMTF (https://github.com/rcsb/mmtf-javascript/; MIT)
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var ArrayEncoderImpl = /** @class */ (function () {
    function ArrayEncoderImpl(providers) {
        this.providers = providers;
    }
    ArrayEncoderImpl.prototype.and = function (f) {
        return new ArrayEncoderImpl(this.providers.concat([f]));
    };
    ArrayEncoderImpl.prototype.encode = function (data) {
        var encoding = [];
        for (var _i = 0, _a = this.providers; _i < _a.length; _i++) {
            var p = _a[_i];
            var t = p(data);
            if (!t.encodings.length) {
                throw new Error('Encodings must be non-empty.');
            }
            data = t.data;
            for (var _b = 0, _c = t.encodings; _b < _c.length; _b++) {
                var e = _c[_b];
                encoding.push(e);
            }
        }
        if (!(data instanceof Uint8Array)) {
            throw new Error('The encoding must result in a Uint8Array. Fix your encoding chain.');
        }
        return {
            encoding: encoding,
            data: data
        };
    };
    return ArrayEncoderImpl;
}());

var ArrayEncoder;
(function (ArrayEncoder) {
    function by(f) {
        return new ArrayEncoderImpl([f]);
    }
    ArrayEncoder.by = by;
    function fromEncoding(encoding) {
        var e = by(getProvider(encoding[0]));
        for (var i = 1; i < encoding.length; i++)
            e = e.and(getProvider(encoding[i]));
        return e;
    }
    ArrayEncoder.fromEncoding = fromEncoding;
    function getProvider(e) {
        switch (e.kind) {
            case 'ByteArray': return ArrayEncoding.byteArray;
            case 'FixedPoint': return ArrayEncoding.fixedPoint(e.factor);
            case 'IntervalQuantization': return ArrayEncoding.intervalQuantizaiton(e.min, e.max, e.numSteps);
            case 'RunLength': return ArrayEncoding.runLength;
            case 'Delta': return ArrayEncoding.delta;
            case 'IntegerPacking': return ArrayEncoding.integerPacking;
            case 'StringArray': return ArrayEncoding.stringArray;
        }
    }
})(ArrayEncoder || (ArrayEncoder = {}));
var ArrayEncoding;
(function (ArrayEncoding) {
    var _a, _b;
    function by(f) {
        return new ArrayEncoderImpl([f]);
    }
    ArrayEncoding.by = by;
    function uint8(data) {
        return {
            encodings: [{ kind: 'ByteArray', type: 4 /* Uint8 */ }],
            data: data
        };
    }
    function int8(data) {
        return {
            encodings: [{ kind: 'ByteArray', type: 1 /* Int8 */ }],
            data: new Uint8Array(data.buffer, data.byteOffset)
        };
    }
    var writers = (_a = {},
        _a[2 /* Int16 */] = function (v, i, a) { v.setInt16(2 * i, a, true); },
        _a[5 /* Uint16 */] = function (v, i, a) { v.setUint16(2 * i, a, true); },
        _a[3 /* Int32 */] = function (v, i, a) { v.setInt32(4 * i, a, true); },
        _a[6 /* Uint32 */] = function (v, i, a) { v.setUint32(4 * i, a, true); },
        _a[32 /* Float32 */] = function (v, i, a) { v.setFloat32(4 * i, a, true); },
        _a[33 /* Float64 */] = function (v, i, a) { v.setFloat64(8 * i, a, true); },
        _a);
    var byteSizes = (_b = {},
        _b[2 /* Int16 */] = 2,
        _b[5 /* Uint16 */] = 2,
        _b[3 /* Int32 */] = 4,
        _b[6 /* Uint32 */] = 4,
        _b[32 /* Float32 */] = 4,
        _b[33 /* Float64 */] = 8,
        _b);
    function byteArray(data) {
        var type = _encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].getDataType(data);
        if (type === 1 /* Int8 */)
            return int8(data);
        else if (type === 4 /* Uint8 */)
            return uint8(data);
        var result = new Uint8Array(data.length * byteSizes[type]);
        var w = writers[type];
        var view = new DataView(result.buffer);
        for (var i = 0, n = data.length; i < n; i++) {
            w(view, i, data[i]);
        }
        return {
            encodings: [{ kind: 'ByteArray', type: type }],
            data: result
        };
    }
    ArrayEncoding.byteArray = byteArray;
    function _fixedPoint(data, factor) {
        var srcType = _encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].getDataType(data);
        var result = new Int32Array(data.length);
        for (var i = 0, n = data.length; i < n; i++) {
            result[i] = Math.round(data[i] * factor);
        }
        return {
            encodings: [{ kind: 'FixedPoint', factor: factor, srcType: srcType }],
            data: result
        };
    }
    function fixedPoint(factor) { return function (data) { return _fixedPoint(data, factor); }; }
    ArrayEncoding.fixedPoint = fixedPoint;
    function _intervalQuantizaiton(data, min, max, numSteps, arrayType) {
        var srcType = _encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].getDataType(data);
        if (!data.length) {
            return {
                encodings: [{ kind: 'IntervalQuantization', min: min, max: max, numSteps: numSteps, srcType: srcType }],
                data: new Int32Array(0)
            };
        }
        if (max < min) {
            var t = min;
            min = max;
            max = t;
        }
        var delta = (max - min) / (numSteps - 1);
        var output = new arrayType(data.length);
        for (var i = 0, n = data.length; i < n; i++) {
            var v = data[i];
            if (v <= min)
                output[i] = 0;
            else if (v >= max)
                output[i] = numSteps - 1;
            else
                output[i] = (Math.round((v - min) / delta)) | 0;
        }
        return {
            encodings: [{ kind: 'IntervalQuantization', min: min, max: max, numSteps: numSteps, srcType: srcType }],
            data: output
        };
    }
    function intervalQuantizaiton(min, max, numSteps, arrayType) {
        if (arrayType === void 0) { arrayType = Int32Array; }
        return function (data) { return _intervalQuantizaiton(data, min, max, numSteps, arrayType); };
    }
    ArrayEncoding.intervalQuantizaiton = intervalQuantizaiton;
    function runLength(data) {
        var srcType = _encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].getDataType(data);
        if (srcType === void 0) {
            data = new Int32Array(data);
            srcType = 3 /* Int32 */;
        }
        if (!data.length) {
            return {
                encodings: [{ kind: 'RunLength', srcType: srcType, srcSize: 0 }],
                data: new Int32Array(0)
            };
        }
        // calculate output size
        var fullLength = 2;
        for (var i = 1, il = data.length; i < il; i++) {
            if (data[i - 1] !== data[i]) {
                fullLength += 2;
            }
        }
        var output = new Int32Array(fullLength);
        var offset = 0;
        var runLength = 1;
        for (var i = 1, il = data.length; i < il; i++) {
            if (data[i - 1] !== data[i]) {
                output[offset] = data[i - 1];
                output[offset + 1] = runLength;
                runLength = 1;
                offset += 2;
            }
            else {
                ++runLength;
            }
        }
        output[offset] = data[data.length - 1];
        output[offset + 1] = runLength;
        return {
            encodings: [{ kind: 'RunLength', srcType: srcType, srcSize: data.length }],
            data: output
        };
    }
    ArrayEncoding.runLength = runLength;
    function delta(data) {
        if (!_encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].isSignedIntegerDataType(data)) {
            throw new Error('Only signed integer types can be encoded using delta encoding.');
        }
        var srcType = _encoding__WEBPACK_IMPORTED_MODULE_1__[/* Encoding */ "a"].getDataType(data);
        if (srcType === void 0) {
            data = new Int32Array(data);
            srcType = 3 /* Int32 */;
        }
        if (!data.length) {
            return {
                encodings: [{ kind: 'Delta', origin: 0, srcType: srcType }],
                data: new data.constructor(0)
            };
        }
        var output = new data.constructor(data.length);
        var origin = data[0];
        output[0] = data[0];
        for (var i = 1, n = data.length; i < n; i++) {
            output[i] = data[i] - data[i - 1];
        }
        output[0] = 0;
        return {
            encodings: [{ kind: 'Delta', origin: origin, srcType: srcType }],
            data: output
        };
    }
    ArrayEncoding.delta = delta;
    function isSigned(data) {
        for (var i = 0, n = data.length; i < n; i++) {
            if (data[i] < 0)
                return true;
        }
        return false;
    }
    function packingSize(data, upperLimit) {
        var lowerLimit = -upperLimit - 1;
        var size = 0;
        for (var i = 0, n = data.length; i < n; i++) {
            var value = data[i];
            if (value === 0) {
                size += 1;
            }
            else if (value > 0) {
                size += Math.ceil(value / upperLimit);
                if (value % upperLimit === 0)
                    size += 1;
            }
            else {
                size += Math.ceil(value / lowerLimit);
                if (value % lowerLimit === 0)
                    size += 1;
            }
        }
        return size;
    }
    function determinePacking(data) {
        var signed = isSigned(data);
        var size8 = signed ? packingSize(data, 0x7F) : packingSize(data, 0xFF);
        var size16 = signed ? packingSize(data, 0x7FFF) : packingSize(data, 0xFFFF);
        if (data.length * 4 < size16 * 2) {
            // 4 byte packing is the most effective
            return {
                isSigned: signed,
                size: data.length,
                bytesPerElement: 4
            };
        }
        else if (size16 * 2 < size8) {
            // 2 byte packing is the most effective
            return {
                isSigned: signed,
                size: size16,
                bytesPerElement: 2
            };
        }
        else {
            // 1 byte packing is the most effective
            return {
                isSigned: signed,
                size: size8,
                bytesPerElement: 1
            };
        }
        ;
    }
    function _integerPacking(data, packing) {
        var upperLimit = packing.isSigned
            ? (packing.bytesPerElement === 1 ? 0x7F : 0x7FFF)
            : (packing.bytesPerElement === 1 ? 0xFF : 0xFFFF);
        var lowerLimit = -upperLimit - 1;
        var n = data.length;
        var packed = packing.isSigned
            ? packing.bytesPerElement === 1 ? new Int8Array(packing.size) : new Int16Array(packing.size)
            : packing.bytesPerElement === 1 ? new Uint8Array(packing.size) : new Uint16Array(packing.size);
        var j = 0;
        for (var i = 0; i < n; i++) {
            var value = data[i];
            if (value >= 0) {
                while (value >= upperLimit) {
                    packed[j] = upperLimit;
                    ++j;
                    value -= upperLimit;
                }
            }
            else {
                while (value <= lowerLimit) {
                    packed[j] = lowerLimit;
                    ++j;
                    value -= lowerLimit;
                }
            }
            packed[j] = value;
            ++j;
        }
        var result = byteArray(packed);
        return {
            encodings: [{
                    kind: 'IntegerPacking',
                    byteCount: packing.bytesPerElement,
                    isUnsigned: !packing.isSigned,
                    srcSize: n
                },
                result.encodings[0]
            ],
            data: result.data
        };
    }
    /**
     * Packs Int32 array. The packing level is determined automatically to either 1-, 2-, or 4-byte words.
     */
    function integerPacking(data) {
        // if (!(data instanceof Int32Array)) {
        //     throw new Error('Integer packing can only be applied to Int32 data.');
        // }
        var packing = determinePacking(data);
        if (packing.bytesPerElement === 4) {
            // no packing done, Int32 encoding will be used
            return byteArray(data);
        }
        return _integerPacking(data, packing);
    }
    ArrayEncoding.integerPacking = integerPacking;
    function stringArray(data) {
        var map = Object.create(null);
        var strings = [];
        var output = new Int32Array(data.length);
        var offsets = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Int32Array, 1, Math.min(1024, data.length < 32 ? data.length + 1 : Math.round(data.length / 8) + 1));
        _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add(offsets, 0);
        var accLength = 0;
        var i = 0;
        for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
            var s = data_1[_i];
            // handle null strings.
            if (s === null || s === void 0) {
                output[i++] = -1;
                continue;
            }
            var index = map[s];
            if (index === void 0) {
                // increment the length
                accLength += s.length;
                // store the string and index
                index = strings.length;
                strings[index] = s;
                map[s] = index;
                // write the offset
                _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add(offsets, accLength);
            }
            output[i++] = index;
        }
        var offsetArray = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(offsets);
        var offsetEncoding = Object(_classifier__WEBPACK_IMPORTED_MODULE_2__[/* classifyIntArray */ "b"])(offsetArray);
        var encodedOddsets = offsetEncoding.encode(offsetArray);
        var dataEncoding = Object(_classifier__WEBPACK_IMPORTED_MODULE_2__[/* classifyIntArray */ "b"])(output);
        var encodedData = dataEncoding.encode(output);
        return {
            encodings: [{ kind: 'StringArray', dataEncoding: encodedData.encoding, stringData: strings.join(''), offsetEncoding: encodedOddsets.encoding, offsets: encodedOddsets.data }],
            data: encodedData.data
        };
    }
    ArrayEncoding.stringArray = stringArray;
})(ArrayEncoding || (ArrayEncoding = {}));
//# sourceMappingURL=array-encoder.js.map

/***/ }),
/* 108 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export InteractionsParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InteractionsProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _interactions_interactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(200);
/* harmony import */ var _common_custom_structure_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(204);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(65);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var InteractionsParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _interactions_interactions__WEBPACK_IMPORTED_MODULE_2__[/* InteractionsParams */ "b"]);
var InteractionsProvider = _common_custom_structure_property__WEBPACK_IMPORTED_MODULE_3__[/* CustomStructureProperty */ "a"].createProvider({
    label: 'Interactions',
    descriptor: Object(_mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__["CustomPropertyDescriptor"])({
        name: 'molstar_computed_interactions',
    }),
    type: 'local',
    defaultParams: InteractionsParams,
    getParams: function (data) { return InteractionsParams; },
    isApplicable: function (data) { return true; },
    obtain: function (ctx, data, props) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(void 0, void 0, void 0, function () {
        var p, _a;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(InteractionsParams)), props);
                    _a = {};
                    return [4 /*yield*/, Object(_interactions_interactions__WEBPACK_IMPORTED_MODULE_2__[/* computeInteractions */ "c"])(ctx, data, p)];
                case 1: return [2 /*return*/, (_a.value = _b.sent(), _a)];
            }
        });
    }); }
});
//# sourceMappingURL=interactions.js.map

/***/ }),
/* 109 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DefaultBondComputationProps; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return MetalsSet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getElementIdx; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getElementPairThreshold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return getElementThreshold; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isHydrogen; });
/**
 * Copyright (c) 2017-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var DefaultBondComputationProps = {
    forceCompute: false,
    noCompute: false
};
// H,D,T are all mapped to H
var __ElementIndex = { 'H': 0, 'h': 0, 'D': 0, 'd': 0, 'T': 0, 't': 0, 'He': 2, 'HE': 2, 'he': 2, 'Li': 3, 'LI': 3, 'li': 3, 'Be': 4, 'BE': 4, 'be': 4, 'B': 5, 'b': 5, 'C': 6, 'c': 6, 'N': 7, 'n': 7, 'O': 8, 'o': 8, 'F': 9, 'f': 9, 'Ne': 10, 'NE': 10, 'ne': 10, 'Na': 11, 'NA': 11, 'na': 11, 'Mg': 12, 'MG': 12, 'mg': 12, 'Al': 13, 'AL': 13, 'al': 13, 'Si': 14, 'SI': 14, 'si': 14, 'P': 15, 'p': 15, 'S': 16, 's': 16, 'Cl': 17, 'CL': 17, 'cl': 17, 'Ar': 18, 'AR': 18, 'ar': 18, 'K': 19, 'k': 19, 'Ca': 20, 'CA': 20, 'ca': 20, 'Sc': 21, 'SC': 21, 'sc': 21, 'Ti': 22, 'TI': 22, 'ti': 22, 'V': 23, 'v': 23, 'Cr': 24, 'CR': 24, 'cr': 24, 'Mn': 25, 'MN': 25, 'mn': 25, 'Fe': 26, 'FE': 26, 'fe': 26, 'Co': 27, 'CO': 27, 'co': 27, 'Ni': 28, 'NI': 28, 'ni': 28, 'Cu': 29, 'CU': 29, 'cu': 29, 'Zn': 30, 'ZN': 30, 'zn': 30, 'Ga': 31, 'GA': 31, 'ga': 31, 'Ge': 32, 'GE': 32, 'ge': 32, 'As': 33, 'AS': 33, 'as': 33, 'Se': 34, 'SE': 34, 'se': 34, 'Br': 35, 'BR': 35, 'br': 35, 'Kr': 36, 'KR': 36, 'kr': 36, 'Rb': 37, 'RB': 37, 'rb': 37, 'Sr': 38, 'SR': 38, 'sr': 38, 'Y': 39, 'y': 39, 'Zr': 40, 'ZR': 40, 'zr': 40, 'Nb': 41, 'NB': 41, 'nb': 41, 'Mo': 42, 'MO': 42, 'mo': 42, 'Tc': 43, 'TC': 43, 'tc': 43, 'Ru': 44, 'RU': 44, 'ru': 44, 'Rh': 45, 'RH': 45, 'rh': 45, 'Pd': 46, 'PD': 46, 'pd': 46, 'Ag': 47, 'AG': 47, 'ag': 47, 'Cd': 48, 'CD': 48, 'cd': 48, 'In': 49, 'IN': 49, 'in': 49, 'Sn': 50, 'SN': 50, 'sn': 50, 'Sb': 51, 'SB': 51, 'sb': 51, 'Te': 52, 'TE': 52, 'te': 52, 'I': 53, 'i': 53, 'Xe': 54, 'XE': 54, 'xe': 54, 'Cs': 55, 'CS': 55, 'cs': 55, 'Ba': 56, 'BA': 56, 'ba': 56, 'La': 57, 'LA': 57, 'la': 57, 'Ce': 58, 'CE': 58, 'ce': 58, 'Pr': 59, 'PR': 59, 'pr': 59, 'Nd': 60, 'ND': 60, 'nd': 60, 'Pm': 61, 'PM': 61, 'pm': 61, 'Sm': 62, 'SM': 62, 'sm': 62, 'Eu': 63, 'EU': 63, 'eu': 63, 'Gd': 64, 'GD': 64, 'gd': 64, 'Tb': 65, 'TB': 65, 'tb': 65, 'Dy': 66, 'DY': 66, 'dy': 66, 'Ho': 67, 'HO': 67, 'ho': 67, 'Er': 68, 'ER': 68, 'er': 68, 'Tm': 69, 'TM': 69, 'tm': 69, 'Yb': 70, 'YB': 70, 'yb': 70, 'Lu': 71, 'LU': 71, 'lu': 71, 'Hf': 72, 'HF': 72, 'hf': 72, 'Ta': 73, 'TA': 73, 'ta': 73, 'W': 74, 'w': 74, 'Re': 75, 'RE': 75, 're': 75, 'Os': 76, 'OS': 76, 'os': 76, 'Ir': 77, 'IR': 77, 'ir': 77, 'Pt': 78, 'PT': 78, 'pt': 78, 'Au': 79, 'AU': 79, 'au': 79, 'Hg': 80, 'HG': 80, 'hg': 80, 'Tl': 81, 'TL': 81, 'tl': 81, 'Pb': 82, 'PB': 82, 'pb': 82, 'Bi': 83, 'BI': 83, 'bi': 83, 'Po': 84, 'PO': 84, 'po': 84, 'At': 85, 'AT': 85, 'at': 85, 'Rn': 86, 'RN': 86, 'rn': 86, 'Fr': 87, 'FR': 87, 'fr': 87, 'Ra': 88, 'RA': 88, 'ra': 88, 'Ac': 89, 'AC': 89, 'ac': 89, 'Th': 90, 'TH': 90, 'th': 90, 'Pa': 91, 'PA': 91, 'pa': 91, 'U': 92, 'u': 92, 'Np': 93, 'NP': 93, 'np': 93, 'Pu': 94, 'PU': 94, 'pu': 94, 'Am': 95, 'AM': 95, 'am': 95, 'Cm': 96, 'CM': 96, 'cm': 96, 'Bk': 97, 'BK': 97, 'bk': 97, 'Cf': 98, 'CF': 98, 'cf': 98, 'Es': 99, 'ES': 99, 'es': 99, 'Fm': 100, 'FM': 100, 'fm': 100, 'Md': 101, 'MD': 101, 'md': 101, 'No': 102, 'NO': 102, 'no': 102, 'Lr': 103, 'LR': 103, 'lr': 103, 'Rf': 104, 'RF': 104, 'rf': 104, 'Db': 105, 'DB': 105, 'db': 105, 'Sg': 106, 'SG': 106, 'sg': 106, 'Bh': 107, 'BH': 107, 'bh': 107, 'Hs': 108, 'HS': 108, 'hs': 108, 'Mt': 109, 'MT': 109, 'mt': 109 };
// Increased P (15) threshold from 1.9 to 2.0 (e.g. for G16 in 1O08)
var __ElementBondThresholds = { 0: 1.42, 1: 1.42, 3: 2.7, 4: 2.7, 6: 1.75, 7: 1.6, 8: 1.52, 11: 2.7, 12: 2.7, 13: 2.7, 14: 1.9, 15: 2.0, 16: 1.9, 17: 1.8, 19: 2.7, 20: 2.7, 21: 2.7, 22: 2.7, 23: 2.7, 24: 2.7, 25: 2.7, 26: 2.7, 27: 2.7, 28: 2.7, 29: 2.7, 30: 2.7, 31: 2.7, 33: 2.68, 37: 2.7, 38: 2.7, 39: 2.7, 40: 2.7, 41: 2.7, 42: 2.7, 43: 2.7, 44: 2.7, 45: 2.7, 46: 2.7, 47: 2.7, 48: 2.7, 49: 2.7, 50: 2.7, 55: 2.7, 56: 2.7, 57: 2.7, 58: 2.7, 59: 2.7, 60: 2.7, 61: 2.7, 62: 2.7, 63: 2.7, 64: 2.7, 65: 2.7, 66: 2.7, 67: 2.7, 68: 2.7, 69: 2.7, 70: 2.7, 71: 2.7, 72: 2.7, 73: 2.7, 74: 2.7, 75: 2.7, 76: 2.7, 77: 2.7, 78: 2.7, 79: 2.7, 80: 2.7, 81: 2.7, 82: 2.7, 83: 2.7, 87: 2.7, 88: 2.7, 89: 2.7, 90: 2.7, 91: 2.7, 92: 2.7, 93: 2.7, 94: 2.7, 95: 2.7, 96: 2.7, 97: 2.7, 98: 2.7, 99: 2.7, 100: 2.7, 101: 2.7, 102: 2.7, 103: 2.7, 104: 2.7, 105: 2.7, 106: 2.7, 107: 2.7, 108: 2.7, 109: 2.88 };
/**
 * Increased N-N (112) threshold from 1.55 to 1.6 (e.g. for 0QH in 1BMA)
 *
 * More experimentally observed bond length here (https://cccbdb.nist.gov/expbondlengths1x.asp)
 *
 * H-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rHH)
 * - 0.741
 *
 * Changed C-H (27) to 1.2
 * C-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rCH)
 * - Average    1.091 (+/- 0.017)
 * - Min        0.931
 * - Max        1.140
 *
 * Changed N-H (35) to 1.15
 * N-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rNH)
 * - Average    1.009 (+/- 0.043)
 * - Min        0.836
 * - Max        1.090
 *
 * Changed O-H (44) to 1.1
 * O-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rOH)
 * - Average    0.967 (+/- 0.022)
 * - Min        0.912
 * - Max        1.033
 *
 * Added P-H (135) as 1.47
 * P-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rPH)
 * - Average    1.423 ((+/- 0.007)
 * - Min        0.912
 * - Max        1.033
 *
 * Added S-H (152) as 1.45
 * S-H (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rSH)
 * - Average    1.345 (+/- 0.020)
 * - Min        1.322
 * - Max        1.400
 *
 * Added Si-Si (420) as 2.37
 * (https://cccbdb.nist.gov/expbondlengths2x.asp?descript=rSiSi)
 */
var __ElementPairThresholds = { 0: 0.8, 20: 1.31, 27: 1.2, 35: 1.15, 44: 1.1, 54: 1, 60: 1.84, 72: 1.88, 84: 1.75, 85: 1.56, 86: 1.76, 98: 1.6, 99: 1.68, 100: 1.63, 112: 1.6, 113: 1.59, 114: 1.36, 129: 1.45, 135: 1.47, 144: 1.6, 152: 1.45, 170: 1.4, 180: 1.55, 202: 2.4, 222: 2.24, 224: 1.91, 225: 1.98, 243: 2.02, 269: 2, 293: 1.9, 420: 2.37, 480: 2.3, 512: 2.3, 544: 2.3, 612: 2.1, 629: 1.54, 665: 1, 813: 2.6, 854: 2.27, 894: 1.93, 896: 2.1, 937: 2.05, 938: 2.06, 981: 1.62, 1258: 2.68, 1309: 2.33, 1484: 1, 1763: 2.14, 1823: 2.48, 1882: 2.1, 1944: 1.72, 2380: 2.34, 3367: 2.44, 3733: 2.11, 3819: 2.6, 3821: 2.36, 4736: 2.75, 5724: 2.73, 5959: 2.63, 6519: 2.84, 6750: 2.87, 8991: 2.81 };
var __DefaultBondingRadius = 2.001;
var MetalsSet = (function () {
    var metals = ['LI', 'NA', 'K', 'RB', 'CS', 'FR', 'BE', 'MG', 'CA', 'SR', 'BA', 'RA', 'AL', 'GA', 'IN', 'SN', 'TL', 'PB', 'BI', 'SC', 'TI', 'V', 'CR', 'MN', 'FE', 'CO', 'NI', 'CU', 'ZN', 'Y', 'ZR', 'NB', 'MO', 'TC', 'RU', 'RH', 'PD', 'AG', 'CD', 'LA', 'HF', 'TA', 'W', 'RE', 'OS', 'IR', 'PT', 'AU', 'HG', 'AC', 'RF', 'DB', 'SG', 'BH', 'HS', 'MT', 'CE', 'PR', 'ND', 'PM', 'SM', 'EU', 'GD', 'TB', 'DY', 'HO', 'ER', 'TM', 'YB', 'LU', 'TH', 'PA', 'U', 'NP', 'PU', 'AM', 'CM', 'BK', 'CF', 'ES', 'FM', 'MD', 'NO', 'LR'];
    var set = new Set();
    for (var _i = 0, metals_1 = metals; _i < metals_1.length; _i++) {
        var m = metals_1[_i];
        set.add(__ElementIndex[m]);
    }
    return set;
})();
function pair(a, b) {
    if (a < b)
        return (a + b) * (a + b + 1) / 2 + b;
    else
        return (a + b) * (a + b + 1) / 2 + a;
}
function getElementIdx(e) {
    var i = __ElementIndex[e];
    if (i === void 0)
        return -1;
    return i;
}
function getElementPairThreshold(i, j) {
    if (i < 0 || j < 0)
        return -1;
    var r = __ElementPairThresholds[pair(i, j)];
    if (r === void 0)
        return -1;
    return r;
}
function getElementThreshold(i) {
    if (i < 0)
        return __DefaultBondingRadius;
    var r = __ElementBondThresholds[i];
    if (r === void 0)
        return __DefaultBondingRadius;
    return r;
}
var H_ID = __ElementIndex['H'];
function isHydrogen(i) {
    return i === H_ID;
}
//# sourceMappingURL=common.js.map

/***/ }),
/* 110 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ComplexVisual */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return ComplexMeshParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return ComplexMeshVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ComplexLinesParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ComplexLinesVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return ComplexTextParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return ComplexTextVisual; });
/* unused harmony export ComplexDirectVolumeParams */
/* unused harmony export ComplexDirectVolumeVisual */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _visual__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(69);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(145);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(89);
/* harmony import */ var _mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(182);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(115);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(23);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(6);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(164);
/* harmony import */ var _mol_theme_color__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(196);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(5);
/* harmony import */ var _mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(146);
/* harmony import */ var _mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(117);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(39);
/* harmony import */ var _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(123);
/* harmony import */ var _mol_theme_size__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(150);
/* harmony import */ var _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(265);
/* harmony import */ var _mol_geo_geometry_marker_data__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(125);
/* harmony import */ var _params__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(94);
/* harmony import */ var _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(74);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





















function createComplexRenderObject(structure, geometry, locationIt, theme, props, materialId) {
    var _a = _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Geometry */ "a"].getUtils(geometry), createValues = _a.createValues, createRenderableState = _a.createRenderableState;
    var transform = Object(_mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_5__[/* createIdentityTransform */ "a"])();
    var values = createValues(geometry, transform, locationIt, theme, props);
    var state = createRenderableState(props);
    return Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_6__[/* createRenderObject */ "a"])(geometry.kind, values, state, materialId);
}
function ComplexVisual(builder, materialId) {
    var defaultProps = builder.defaultProps, createGeometry = builder.createGeometry, createLocationIterator = builder.createLocationIterator, getLoci = builder.getLoci, eachLocation = builder.eachLocation, setUpdateState = builder.setUpdateState;
    var _a = builder.geometryUtils, updateValues = _a.updateValues, updateBoundingSphere = _a.updateBoundingSphere, updateRenderableState = _a.updateRenderableState;
    var updateState = _util__WEBPACK_IMPORTED_MODULE_9__[/* VisualUpdateState */ "a"].create();
    var renderObject;
    var newProps;
    var newTheme;
    var newStructure;
    var currentProps = Object.assign({}, defaultProps);
    var currentTheme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_4__[/* Theme */ "a"].createEmpty();
    var currentStructure;
    var geometry;
    var locationIt;
    function prepareUpdate(theme, props, structure) {
        if (!structure && !currentStructure) {
            throw new Error('missing structure');
        }
        newProps = Object.assign({}, currentProps, props);
        newTheme = theme;
        newStructure = structure;
        _util__WEBPACK_IMPORTED_MODULE_9__[/* VisualUpdateState */ "a"].reset(updateState);
        if (!renderObject) {
            updateState.createNew = true;
        }
        else if (!currentStructure || !_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].areEquivalent(newStructure, currentStructure)) {
            updateState.createNew = true;
        }
        if (updateState.createNew) {
            updateState.createGeometry = true;
            return;
        }
        setUpdateState(updateState, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure);
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].conformationHash(newStructure) !== _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].conformationHash(currentStructure)) {
            updateState.updateTransform = true;
            updateState.createGeometry = true;
        }
        if (!_mol_theme_color__WEBPACK_IMPORTED_MODULE_10__[/* ColorTheme */ "a"].areEqual(theme.color, currentTheme.color)) {
            updateState.updateColor = true;
        }
        if (!Object(_mol_util__WEBPACK_IMPORTED_MODULE_11__[/* deepEqual */ "h"])(newProps.unitKinds, currentProps.unitKinds)) {
            updateState.createGeometry = true;
        }
        if (updateState.createGeometry) {
            updateState.updateColor = true;
        }
    }
    function update(newGeometry) {
        if (updateState.createNew) {
            locationIt = createLocationIterator(newStructure);
            if (newGeometry) {
                renderObject = createComplexRenderObject(newStructure, newGeometry, locationIt, newTheme, newProps, materialId);
            }
            else {
                throw new Error('expected geometry to be given');
            }
        }
        else {
            if (!renderObject) {
                throw new Error('expected renderObject to be available');
            }
            if (updateState.updateTransform) {
                // console.log('update transform')
                locationIt = createLocationIterator(newStructure);
                var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
                Object(_mol_geo_geometry_marker_data__WEBPACK_IMPORTED_MODULE_18__[/* createMarkers */ "a"])(instanceCount * groupCount, renderObject.values);
            }
            if (updateState.createGeometry) {
                if (newGeometry) {
                    _mol_util__WEBPACK_IMPORTED_MODULE_11__[/* ValueCell */ "e"].update(renderObject.values.drawCount, _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Geometry */ "a"].getDrawCount(newGeometry));
                    updateBoundingSphere(renderObject.values, newGeometry);
                }
                else {
                    throw new Error('expected geometry to be given');
                }
            }
            if (updateState.updateSize) {
                // not all geometries have size data, so check here
                if ('uSize' in renderObject.values) {
                    Object(_mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_12__[/* createSizes */ "a"])(locationIt, newTheme.size, renderObject.values);
                }
            }
            if (updateState.updateColor) {
                Object(_mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_13__[/* createColors */ "a"])(locationIt, newTheme.color, renderObject.values);
            }
            updateValues(renderObject.values, newProps);
            updateRenderableState(renderObject.state, newProps);
        }
        currentProps = newProps;
        currentTheme = newTheme;
        currentStructure = newStructure;
        if (newGeometry)
            geometry = newGeometry;
    }
    function lociIsSuperset(loci) {
        if (Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_7__["isEveryLoci"])(loci))
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].isLoci(loci) && _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].areRootsEquivalent(loci.structure, currentStructure))
            return true;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(loci) && _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].areRootsEquivalent(loci.structure, currentStructure)) {
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.isWholeStructure(loci))
                return true;
        }
        return false;
    }
    function lociApply(loci, apply, isMarking) {
        if (lociIsSuperset(loci)) {
            return apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_8__["Interval"].ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
        }
        else {
            return eachLocation(loci, currentStructure, apply, isMarking);
        }
    }
    return {
        get groupCount() { return locationIt ? locationIt.count : 0; },
        get renderObject() { return locationIt && locationIt.count ? renderObject : undefined; },
        createOrUpdate: function (ctx, theme, props, structure) {
            if (props === void 0) { props = {}; }
            prepareUpdate(theme, props, structure || currentStructure);
            if (updateState.createGeometry) {
                var newGeometry = createGeometry(ctx, newStructure, newTheme, newProps, geometry);
                return newGeometry instanceof Promise ? newGeometry.then(update) : update(newGeometry);
            }
            else {
                update();
            }
        },
        getLoci: function (pickingId) {
            return renderObject ? getLoci(pickingId, currentStructure, renderObject.id) : _mol_model_loci__WEBPACK_IMPORTED_MODULE_7__["EmptyLoci"];
        },
        mark: function (loci, action) {
            return _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].mark(renderObject, loci, action, lociApply);
        },
        setVisibility: function (visible) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setVisibility(renderObject, visible);
        },
        setAlphaFactor: function (alphaFactor) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setAlphaFactor(renderObject, alphaFactor);
        },
        setPickable: function (pickable) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setPickable(renderObject, pickable);
        },
        setTransform: function (matrix, instanceMatrices) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setTransform(renderObject, matrix, instanceMatrices);
        },
        setOverpaint: function (overpaint) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setOverpaint(renderObject, overpaint, lociApply, true);
        },
        setTransparency: function (transparency) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setTransparency(renderObject, transparency, lociApply, true);
        },
        setClipping: function (clipping) {
            _visual__WEBPACK_IMPORTED_MODULE_1__[/* Visual */ "a"].setClipping(renderObject, clipping, lociApply, true);
        },
        destroy: function () {
            // TODO
            renderObject = undefined;
        }
    };
}
// mesh
var ComplexMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureMeshParams */ "c"]), _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureParams */ "d"]);
function ComplexMeshVisual(builder, materialId) {
    return ComplexVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
        }, geometryUtils: _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_14__[/* Mesh */ "a"].Utils }), materialId);
}
// lines
var ComplexLinesParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureLinesParams */ "b"]), _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureParams */ "d"]);
function ComplexLinesVisual(builder, materialId) {
    return ComplexVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
        }, geometryUtils: _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_20__[/* Lines */ "a"].Utils }), materialId);
}
// text
var ComplexTextParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureTextParams */ "g"]), _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureParams */ "d"]);
function ComplexTextVisual(builder, materialId) {
    return ComplexVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.updateSize = true;
            if (newProps.background !== currentProps.background)
                state.createGeometry = true;
            if (newProps.backgroundMargin !== currentProps.backgroundMargin)
                state.createGeometry = true;
            if (newProps.tether !== currentProps.tether)
                state.createGeometry = true;
            if (newProps.tetherLength !== currentProps.tetherLength)
                state.createGeometry = true;
            if (newProps.tetherBaseWidth !== currentProps.tetherBaseWidth)
                state.createGeometry = true;
            if (newProps.attachment !== currentProps.attachment)
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_text_text__WEBPACK_IMPORTED_MODULE_15__[/* Text */ "a"].Utils }), materialId);
}
// direct-volume
var ComplexDirectVolumeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureDirectVolumeParams */ "a"]), _params__WEBPACK_IMPORTED_MODULE_19__[/* StructureParams */ "d"]);
function ComplexDirectVolumeVisual(builder, materialId) {
    return ComplexVisual(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, builder), { setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure) {
            builder.setUpdateState(state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure);
            if (!_mol_theme_size__WEBPACK_IMPORTED_MODULE_16__[/* SizeTheme */ "a"].areEqual(newTheme.size, currentTheme.size))
                state.createGeometry = true;
        }, geometryUtils: _mol_geo_geometry_direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_17__[/* DirectVolume */ "a"].Utils }), materialId);
}
//# sourceMappingURL=complex-visual.js.map

/***/ }),
/* 111 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ getPaletteParams; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ getPalette; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/legend.js
var mol_util_legend = __webpack_require__(141);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/spaces/lab.js
var spaces_lab = __webpack_require__(161);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/spaces/hcl.js
var hcl = __webpack_require__(233);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/color/distinct.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * adapted from https://github.com/internalfx/distinct-colors (ISC License Copyright (c) 2015, InternalFX Inc.)
 * which is heavily inspired by http://tools.medialab.sciences-po.fr/iwanthue/
 */







var DistinctColorsParams = {
    hue: param_definition["ParamDefinition"].Interval([1, 360], { min: 0, max: 360, step: 1 }),
    chroma: param_definition["ParamDefinition"].Interval([40, 70], { min: 0, max: 100, step: 1 }),
    luminance: param_definition["ParamDefinition"].Interval([15, 85], { min: 0, max: 100, step: 1 }),
    clusteringStepCount: param_definition["ParamDefinition"].Numeric(50, { min: 10, max: 200, step: 1 }, { isHidden: true }),
    minSampleCount: param_definition["ParamDefinition"].Numeric(800, { min: 100, max: 5000, step: 100 }, { isHidden: true })
};
function distance(colorA, colorB) {
    return Math.sqrt(Math.pow(Math.abs(colorA[0] - colorB[0]), 2) +
        Math.pow(Math.abs(colorA[1] - colorB[1]), 2) +
        Math.pow(Math.abs(colorA[2] - colorB[2]), 2));
}
var LabTolerance = 2;
var tmpCheckColorHcl = [0, 0, 0];
var tmpCheckColorLab = [0, 0, 0];
function checkColor(lab, props) {
    spaces_lab["a" /* Lab */].toHcl(tmpCheckColorHcl, lab);
    // roundtrip to RGB for conversion tolerance testing
    spaces_lab["a" /* Lab */].fromColor(tmpCheckColorLab, spaces_lab["a" /* Lab */].toColor(lab));
    return (tmpCheckColorHcl[0] >= props.hue[0] &&
        tmpCheckColorHcl[0] <= props.hue[1] &&
        tmpCheckColorHcl[1] >= props.chroma[0] &&
        tmpCheckColorHcl[1] <= props.chroma[1] &&
        tmpCheckColorHcl[2] >= props.luminance[0] &&
        tmpCheckColorHcl[2] <= props.luminance[1] &&
        tmpCheckColorLab[0] >= (lab[0] - LabTolerance) &&
        tmpCheckColorLab[0] <= (lab[0] + LabTolerance) &&
        tmpCheckColorLab[1] >= (lab[1] - LabTolerance) &&
        tmpCheckColorLab[1] <= (lab[1] + LabTolerance) &&
        tmpCheckColorLab[2] >= (lab[2] - LabTolerance) &&
        tmpCheckColorLab[2] <= (lab[2] + LabTolerance));
}
function sortByContrast(colors) {
    var unsortedColors = colors.slice(0);
    var sortedColors = [unsortedColors.shift()];
    while (unsortedColors.length > 0) {
        var lastColor = sortedColors[sortedColors.length - 1];
        var nearest = 0;
        var maxDist = Number.MIN_SAFE_INTEGER;
        for (var i = 0; i < unsortedColors.length; ++i) {
            var dist = distance(lastColor, unsortedColors[i]);
            if (dist > maxDist) {
                maxDist = dist;
                nearest = i;
            }
        }
        sortedColors.push(unsortedColors.splice(nearest, 1)[0]);
    }
    return sortedColors;
}
function getSamples(count, p) {
    var samples = new Map();
    var rangeDivider = Math.cbrt(count) * 1.001;
    var hStep = (p.hue[1] - p.hue[0]) / rangeDivider;
    var cStep = (p.chroma[1] - p.chroma[0]) / rangeDivider;
    var lStep = (p.luminance[1] - p.luminance[0]) / rangeDivider;
    for (var h = p.hue[0]; h <= p.hue[1]; h += hStep) {
        for (var c = p.chroma[0]; c <= p.chroma[1]; c += cStep) {
            for (var l = p.luminance[0]; l <= p.luminance[1]; l += lStep) {
                var lab = spaces_lab["a" /* Lab */].fromHcl(Object(spaces_lab["a" /* Lab */])(), hcl["a" /* Hcl */].create(h, c, l));
                if (checkColor(lab, p))
                    samples.set(lab.toString(), lab);
            }
        }
    }
    return Array.from(samples.values());
}
/**
 * Create a list of visually distinct colors
 */
function distinctColors(count, props) {
    if (props === void 0) { props = {}; }
    var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(DistinctColorsParams)), props);
    if (count <= 0)
        return [];
    var samples = getSamples(Math.max(p.minSampleCount, count * 5), p);
    if (samples.length < count) {
        throw new Error('Not enough samples to generate distinct colors, increase sample count.');
    }
    var colors = [];
    var zonesProto = [];
    var sliceSize = Math.floor(samples.length / count);
    for (var i = 0; i < samples.length; i += sliceSize) {
        colors.push(samples[i]);
        zonesProto.push([]);
        if (colors.length >= count)
            break;
    }
    for (var step = 1; step <= p.clusteringStepCount; ++step) {
        var zones = Object(object["b" /* deepClone */])(zonesProto);
        // Find closest color for each sample
        for (var i = 0; i < samples.length; ++i) {
            var minDist = Number.MAX_SAFE_INTEGER;
            var nearest = 0;
            for (var j = 0; j < colors.length; j++) {
                var dist = distance(samples[i], colors[j]);
                if (dist < minDist) {
                    minDist = dist;
                    nearest = j;
                }
            }
            zones[nearest].push(samples[i]);
        }
        var lastColors = Object(object["b" /* deepClone */])(colors);
        for (var i = 0; i < zones.length; ++i) {
            var zone = zones[i];
            var size = zone.length;
            var Ls = [];
            var As = [];
            var Bs = [];
            for (var _i = 0, zone_1 = zone; _i < zone_1.length; _i++) {
                var sample = zone_1[_i];
                Ls.push(sample[0]);
                As.push(sample[1]);
                Bs.push(sample[2]);
            }
            var lAvg = Object(array["arraySum"])(Ls) / size;
            var aAvg = Object(array["arraySum"])(As) / size;
            var bAvg = Object(array["arraySum"])(Bs) / size;
            colors[i] = [lAvg, aAvg, bAvg];
        }
        if (Object(mol_util["h" /* deepEqual */])(lastColors, colors))
            break;
    }
    return sortByContrast(colors).map(function (c) { return spaces_lab["a" /* Lab */].toColor(c); });
}
//# sourceMappingURL=distinct.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/lists.js
var lists = __webpack_require__(88);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/scale.js
var color_scale = __webpack_require__(337);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/color/palette.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var DefaultGetPaletteProps = {
    type: 'generate',
    colorList: 'red-yellow-blue'
};
var LabelParams = {
    valueLabel: param_definition["ParamDefinition"].Value(function (i) { return "" + (i + 1); }, { isHidden: true }),
    minLabel: param_definition["ParamDefinition"].Value('Start', { isHidden: true }),
    maxLabel: param_definition["ParamDefinition"].Value('End', { isHidden: true })
};
function getPaletteParams(props) {
    if (props === void 0) { props = {}; }
    var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultGetPaletteProps), props);
    return {
        palette: param_definition["ParamDefinition"].MappedStatic(p.type, {
            colors: param_definition["ParamDefinition"].Group(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, LabelParams), { list: param_definition["ParamDefinition"].ColorList(p.colorList) }), { isFlat: true }),
            generate: param_definition["ParamDefinition"].Group(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, LabelParams), DistinctColorsParams), { maxCount: param_definition["ParamDefinition"].Numeric(75, { min: 1, max: 250, step: 1 }) }), { isFlat: true })
        }, {
            options: [
                ['colors', 'Color List'],
                ['generate', 'Generate Distinct']
            ]
        })
    };
}
var DefaultPaletteProps = param_definition["ParamDefinition"].getDefaultValues(getPaletteParams());
function getPalette(count, props) {
    var color;
    var legend;
    if (props.palette.name === 'colors' && props.palette.params.list.kind === 'interpolate') {
        var _a = props.palette.params, list = _a.list, minLabel = _a.minLabel, maxLabel = _a.maxLabel;
        var domain = [0, count - 1];
        var colors = list.colors;
        if (colors.length === 0)
            colors = Object(lists["getColorListFromName"])(DefaultGetPaletteProps.colorList).list;
        var scale = color_scale["a" /* ColorScale */].create({ listOrName: colors, domain: domain, minLabel: minLabel, maxLabel: maxLabel });
        legend = scale.legend;
        color = scale.color;
    }
    else {
        var colors_1;
        if (props.palette.name === 'colors') {
            colors_1 = props.palette.params.list.colors;
            if (colors_1.length === 0)
                colors_1 = Object(lists["getColorListFromName"])('dark-2').list;
        }
        else {
            count = Math.min(count, props.palette.params.maxCount);
            colors_1 = distinctColors(count, props.palette.params);
        }
        var valueLabel = props.palette.params.valueLabel || (function (i) { return '' + i; });
        var colorsLength_1 = colors_1.length;
        var table = [];
        for (var i = 0; i < count; ++i) {
            var j = i % colorsLength_1;
            if (table[j] === undefined) {
                table[j] = [valueLabel(i), colors_1[j]];
            }
            else {
                table[j][0] += ", " + valueLabel(i);
            }
        }
        legend = Object(mol_util_legend["b" /* TableLegend */])(table);
        color = function (i) { return colors_1[i % colorsLength_1]; };
    }
    return { color: color, legend: legend };
}
//# sourceMappingURL=palette.js.map

/***/ }),
/* 112 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/symmetry-operator.js
var symmetry_operator = __webpack_require__(136);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element.js + 3 modules
var structure_element = __webpack_require__(129);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit.js + 2 modules
var structure_unit = __webpack_require__(37);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary-helper.js
var boundary_helper = __webpack_require__(126);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/boundary.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var tmpBox = Object(geometry["b" /* Box3D */])();
var tmpSphere = Object(geometry["g" /* Sphere3D */])();
var boundaryHelper = new boundary_helper["a" /* BoundaryHelper */]('98');
function computeStructureBoundary(s) {
    var min = linear_algebra["Vec3"].create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
    var max = linear_algebra["Vec3"].create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
    var units = s.units;
    boundaryHelper.reset();
    for (var i = 0, _i = units.length; i < _i; i++) {
        var u = units[i];
        var invariantBoundary = u.lookup3d.boundary;
        var o = u.conformation.operator;
        if (o.isIdentity) {
            linear_algebra["Vec3"].min(min, min, invariantBoundary.box.min);
            linear_algebra["Vec3"].max(max, max, invariantBoundary.box.max);
            boundaryHelper.includePositionRadius(invariantBoundary.sphere.center, invariantBoundary.sphere.radius);
        }
        else {
            geometry["b" /* Box3D */].transform(tmpBox, invariantBoundary.box, o.matrix);
            linear_algebra["Vec3"].min(min, min, tmpBox.min);
            linear_algebra["Vec3"].max(max, max, tmpBox.max);
            geometry["g" /* Sphere3D */].transform(tmpSphere, invariantBoundary.sphere, o.matrix);
            boundaryHelper.includePositionRadius(tmpSphere.center, tmpSphere.radius);
        }
    }
    boundaryHelper.finishedIncludeStep();
    for (var i = 0, _i = units.length; i < _i; i++) {
        var u = units[i];
        var invariantBoundary = u.lookup3d.boundary;
        var o = u.conformation.operator;
        if (o.isIdentity) {
            boundaryHelper.radiusPositionRadius(invariantBoundary.sphere.center, invariantBoundary.sphere.radius);
        }
        else {
            geometry["g" /* Sphere3D */].transform(tmpSphere, invariantBoundary.sphere, o.matrix);
            boundaryHelper.radiusPositionRadius(tmpSphere.center, tmpSphere.radius);
        }
    }
    return { box: { min: min, max: max }, sphere: boundaryHelper.getSphere() };
}
//# sourceMappingURL=boundary.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary.js
var boundary = __webpack_require__(185);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/lookup3d.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var StructureResult;
(function (StructureResult) {
    function add(result, unit, index, distSq) {
        result.indices[result.count] = index;
        result.units[result.count] = unit;
        result.squaredDistances[result.count] = distSq;
        result.count++;
    }
    StructureResult.add = add;
    function create() {
        return { count: 0, indices: [], units: [], squaredDistances: [] };
    }
    StructureResult.create = create;
    function copy(out, result) {
        for (var i = 0; i < result.count; ++i) {
            out.indices[i] = result.indices[i];
            out.units[i] = result.units[i];
            out.squaredDistances[i] = result.squaredDistances[i];
        }
        out.count = result.count;
        return out;
    }
    StructureResult.copy = copy;
})(StructureResult || (StructureResult = {}));
var lookup3d_StructureLookup3D = /** @class */ (function () {
    function StructureLookup3D(structure) {
        this.structure = structure;
        this.pivot = linear_algebra["Vec3"].zero();
        this.result = StructureResult.create();
        this._boundary = void 0;
        var units = structure.units;
        var unitCount = units.length;
        var xs = new Float32Array(unitCount);
        var ys = new Float32Array(unitCount);
        var zs = new Float32Array(unitCount);
        var radius = new Float32Array(unitCount);
        var center = linear_algebra["Vec3"].zero();
        for (var i = 0; i < unitCount; i++) {
            var unit = units[i];
            var lookup = unit.lookup3d;
            var s = lookup.boundary.sphere;
            linear_algebra["Vec3"].transformMat4(center, s.center, unit.conformation.operator.matrix);
            xs[i] = center[0];
            ys[i] = center[1];
            zs[i] = center[2];
            radius[i] = s.radius;
        }
        var position = { x: xs, y: ys, z: zs, radius: radius, indices: mol_data_int["OrderedSet"].ofBounds(0, unitCount) };
        this.unitLookup = Object(geometry["c" /* GridLookup3D */])(position, Object(boundary["a" /* getBoundary */])(position));
    }
    StructureLookup3D.prototype.findUnitIndices = function (x, y, z, radius) {
        return this.unitLookup.find(x, y, z, radius);
    };
    StructureLookup3D.prototype.find = function (x, y, z, radius) {
        geometry["d" /* Result */].reset(this.result);
        var units = this.structure.units;
        var closeUnits = this.unitLookup.find(x, y, z, radius);
        if (closeUnits.count === 0)
            return this.result;
        for (var t = 0, _t = closeUnits.count; t < _t; t++) {
            var unit = units[closeUnits.indices[t]];
            linear_algebra["Vec3"].set(this.pivot, x, y, z);
            if (!unit.conformation.operator.isIdentity) {
                linear_algebra["Vec3"].transformMat4(this.pivot, this.pivot, unit.conformation.operator.inverse);
            }
            var unitLookup = unit.lookup3d;
            var groupResult = unitLookup.find(this.pivot[0], this.pivot[1], this.pivot[2], radius);
            for (var j = 0, _j = groupResult.count; j < _j; j++) {
                StructureResult.add(this.result, unit, groupResult.indices[j], groupResult.squaredDistances[j]);
            }
        }
        return this.result;
    };
    StructureLookup3D.prototype.findIntoBuilder = function (x, y, z, radius, builder) {
        var units = this.structure.units;
        var closeUnits = this.unitLookup.find(x, y, z, radius);
        if (closeUnits.count === 0)
            return;
        for (var t = 0, _t = closeUnits.count; t < _t; t++) {
            var unit = units[closeUnits.indices[t]];
            linear_algebra["Vec3"].set(this.pivot, x, y, z);
            if (!unit.conformation.operator.isIdentity) {
                linear_algebra["Vec3"].transformMat4(this.pivot, this.pivot, unit.conformation.operator.inverse);
            }
            var unitLookup = unit.lookup3d;
            var groupResult = unitLookup.find(this.pivot[0], this.pivot[1], this.pivot[2], radius);
            if (groupResult.count === 0)
                continue;
            var elements = unit.elements;
            builder.beginUnit(unit.id);
            for (var j = 0, _j = groupResult.count; j < _j; j++) {
                builder.addElement(elements[groupResult.indices[j]]);
            }
            builder.commitUnit();
        }
    };
    StructureLookup3D.prototype.findIntoBuilderWithRadius = function (x, y, z, pivotR, maxRadius, radius, eRadius, builder) {
        var units = this.structure.units;
        var closeUnits = this.unitLookup.find(x, y, z, radius);
        if (closeUnits.count === 0)
            return;
        var se = structure_element["a" /* default */].Location.create(this.structure);
        var queryRadius = pivotR + maxRadius + radius;
        for (var t = 0, _t = closeUnits.count; t < _t; t++) {
            var unit = units[closeUnits.indices[t]];
            linear_algebra["Vec3"].set(this.pivot, x, y, z);
            if (!unit.conformation.operator.isIdentity) {
                linear_algebra["Vec3"].transformMat4(this.pivot, this.pivot, unit.conformation.operator.inverse);
            }
            var unitLookup = unit.lookup3d;
            var groupResult = unitLookup.find(this.pivot[0], this.pivot[1], this.pivot[2], queryRadius);
            if (groupResult.count === 0)
                continue;
            var elements = unit.elements;
            se.unit = unit;
            builder.beginUnit(unit.id);
            for (var j = 0, _j = groupResult.count; j < _j; j++) {
                se.element = elements[groupResult.indices[j]];
                var rr = eRadius(se);
                if (Math.sqrt(groupResult.squaredDistances[j]) - pivotR - rr > radius)
                    continue;
                builder.addElement(elements[groupResult.indices[j]]);
            }
            builder.commitUnit();
        }
    };
    StructureLookup3D.prototype.check = function (x, y, z, radius) {
        var units = this.structure.units;
        var closeUnits = this.unitLookup.find(x, y, z, radius);
        if (closeUnits.count === 0)
            return false;
        for (var t = 0, _t = closeUnits.count; t < _t; t++) {
            var unit = units[closeUnits.indices[t]];
            linear_algebra["Vec3"].set(this.pivot, x, y, z);
            if (!unit.conformation.operator.isIdentity) {
                linear_algebra["Vec3"].transformMat4(this.pivot, this.pivot, unit.conformation.operator.inverse);
            }
            var groupLookup = unit.lookup3d;
            if (groupLookup.check(this.pivot[0], this.pivot[1], this.pivot[2], radius))
                return true;
        }
        return false;
    };
    Object.defineProperty(StructureLookup3D.prototype, "boundary", {
        get: function () {
            if (this._boundary)
                return this._boundary;
            this._boundary = computeStructureBoundary(this.structure);
            return this._boundary;
        },
        enumerable: false,
        configurable: true
    });
    return StructureLookup3D;
}());

//# sourceMappingURL=lookup3d.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/symmetry.js
var symmetry = __webpack_require__(239);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/subset-builder.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var subset_builder_StructureSubsetBuilder = /** @class */ (function () {
    function StructureSubsetBuilder(parent, isSorted) {
        this.parent = parent;
        this.isSorted = isSorted;
        this.ids = [];
        this.unitMap = mol_data_int["IntMap"].Mutable();
        this.parentId = -1;
        this.currentUnit = [];
        this.elementCount = 0;
    }
    StructureSubsetBuilder.prototype.addToUnit = function (parentId, e) {
        var unit = this.unitMap.get(parentId);
        if (!!unit) {
            unit[unit.length] = e;
        }
        else {
            this.unitMap.set(parentId, [e]);
            this.ids[this.ids.length] = parentId;
        }
        this.elementCount++;
    };
    StructureSubsetBuilder.prototype.beginUnit = function (parentId) {
        this.parentId = parentId;
        this.currentUnit = this.currentUnit.length > 0 ? [] : this.currentUnit;
    };
    StructureSubsetBuilder.prototype.addElement = function (e) {
        this.currentUnit[this.currentUnit.length] = e;
        this.elementCount++;
    };
    StructureSubsetBuilder.prototype.commitUnit = function () {
        if (this.currentUnit.length === 0)
            return;
        this.ids[this.ids.length] = this.parentId;
        this.unitMap.set(this.parentId, this.currentUnit);
        this.parentId = -1;
    };
    StructureSubsetBuilder.prototype.setUnit = function (parentId, elements) {
        this.ids[this.ids.length] = parentId;
        this.unitMap.set(parentId, elements);
        this.elementCount += elements.length;
    };
    StructureSubsetBuilder.prototype._getStructure = function (deduplicateElements) {
        if (this.isEmpty)
            return structure_structure.Empty;
        var newUnits = [];
        Object(util["q" /* sortArray */])(this.ids);
        var symmGroups = symmetry["a" /* default */].UnitEquivalenceBuilder();
        for (var i = 0, _i = this.ids.length; i < _i; i++) {
            var id = this.ids[i];
            var parent_1 = this.parent.unitMap.get(id);
            var unit = this.unitMap.get(id);
            var sorted = false;
            if (deduplicateElements) {
                if (!this.isSorted)
                    Object(util["q" /* sortArray */])(unit);
                unit = mol_data_int["SortedArray"].deduplicate(mol_data_int["SortedArray"].ofSortedArray(this.currentUnit));
                sorted = true;
            }
            var l = unit.length;
            // if the length is the same, just copy the old unit.
            if (unit.length === parent_1.elements.length) {
                newUnits[newUnits.length] = parent_1;
                symmGroups.add(parent_1.id, parent_1);
                continue;
            }
            if (!this.isSorted && !sorted && l > 1)
                Object(util["q" /* sortArray */])(unit);
            var child = parent_1.getChild(mol_data_int["SortedArray"].ofSortedArray(unit));
            var pivot = symmGroups.add(child.id, child);
            if (child !== pivot)
                child = pivot.applyOperator(child.id, child.conformation.operator, true);
            newUnits[newUnits.length] = child;
        }
        return structure_structure.create(newUnits, { parent: this.parent });
    };
    StructureSubsetBuilder.prototype.getStructure = function () {
        return this._getStructure(false);
    };
    StructureSubsetBuilder.prototype.getStructureDeduplicate = function () {
        return this._getStructure(true);
    };
    StructureSubsetBuilder.prototype.setSingletonLocation = function (location) {
        var id = this.ids[0];
        location.unit = this.parent.unitMap.get(id);
        location.element = this.unitMap.get(id)[0];
    };
    Object.defineProperty(StructureSubsetBuilder.prototype, "isEmpty", {
        get: function () {
            return this.elementCount === 0;
        },
        enumerable: false,
        configurable: true
    });
    return StructureSubsetBuilder;
}());

//# sourceMappingURL=subset-builder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds.js + 3 modules
var bonds = __webpack_require__(159);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/properties.js
var properties = __webpack_require__(168);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-data/util/combination.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function P(m, n) {
    var p = 1;
    while (n--)
        p *= m--;
    return p;
}
function C(m, n) {
    if (n > m)
        return 0;
    return P(m, n) / P(n, n);
}
function nextIndex(n) {
    var smallest = n & -n;
    var ripple = n + smallest;
    var newSmallest = ripple & -ripple;
    var ones = ((newSmallest / smallest) >> 1) - 1;
    return ripple | ones;
}
;
var CombinationIterator = /** @class */ (function () {
    function CombinationIterator(array, count) {
        this.array = array;
        this.hasNext = false;
        this.index = (1 << count) - 1;
        this.size = C(array.length, count);
        this.maxIndex = 1 << array.length,
            this.value = new Array(count);
        this.hasNext = count > 0 && count <= array.length;
    }
    CombinationIterator.prototype.move = function () {
        if (this.hasNext) {
            var i = 0, j = 0, n = this.index;
            for (; n; n >>>= 1, i++) {
                if (n & 1)
                    this.value[j++] = this.array[i];
            }
            this.index = nextIndex(this.index);
            this.hasNext = this.index < this.maxIndex;
        }
        return this.value;
    };
    return CombinationIterator;
}());

function combinations(array, count) {
    var out = [];
    var combinationIt = new CombinationIterator(array, count);
    while (combinationIt.hasNext)
        out.push(combinationIt.move().slice());
    return out;
}
//# sourceMappingURL=combination.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph.js + 1 modules
var graph = __webpack_require__(171);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/principal-axes.js + 1 modules
var principal_axes = __webpack_require__(227);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var mol_util_array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/util.js
var structure_util = __webpack_require__(147);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/data.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var EmptyArray = [];
var EmptyCarbohydrates = {
    links: EmptyArray,
    terminalLinks: EmptyArray,
    elements: EmptyArray,
    partialElements: EmptyArray,
    getElementIndices: function () { return EmptyArray; },
    getLinkIndices: function () { return EmptyArray; },
    getTerminalLinkIndices: function () { return EmptyArray; },
};
//# sourceMappingURL=data.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/rings.js + 1 modules
var unit_rings = __webpack_require__(201);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/compute.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */













var compute_C = Object(types["ElementSymbol"])('C'), O = Object(types["ElementSymbol"])('O');
var SugarRingFps = [
    unit_rings["a" /* UnitRing */].elementFingerprint([compute_C, compute_C, compute_C, O]),
    unit_rings["a" /* UnitRing */].elementFingerprint([compute_C, compute_C, compute_C, compute_C, O]),
    unit_rings["a" /* UnitRing */].elementFingerprint([compute_C, compute_C, compute_C, compute_C, compute_C, O]),
    unit_rings["a" /* UnitRing */].elementFingerprint([compute_C, compute_C, compute_C, compute_C, compute_C, compute_C, O]),
];
function getAnomericCarbon(unit, ringAtoms) {
    var indexHasTwoOxygen = -1, indexHasOxygenAndCarbon = -1, indexHasC1Name = -1, indexIsCarbon = -1;
    var elements = unit.elements;
    var _a = unit.model.atomicHierarchy.atoms, type_symbol = _a.type_symbol, label_atom_id = _a.label_atom_id;
    var _b = unit.bonds, neighbor = _b.b, offset = _b.offset;
    for (var i = 0, il = ringAtoms.length; i < il; ++i) {
        var ei = elements[ringAtoms[i]];
        if (type_symbol.value(ei) !== compute_C)
            continue;
        var linkedOxygenCount = 0;
        var linkedCarbonCount = 0;
        for (var j = offset[ringAtoms[i]], jl = offset[ringAtoms[i] + 1]; j < jl; ++j) {
            var ej = elements[neighbor[j]];
            var typeSymbol = type_symbol.value(ej);
            if (typeSymbol === O)
                ++linkedOxygenCount;
            else if (typeSymbol === compute_C)
                ++linkedCarbonCount;
        }
        if (linkedOxygenCount === 2) {
            // found anomeric carbon
            indexHasTwoOxygen = ei;
            break;
        }
        else if (linkedOxygenCount === 1 && linkedCarbonCount === 1) {
            // possibly an anomeric carbon if this is a mono-saccharide without a glycosidic bond
            indexHasOxygenAndCarbon = ei;
        }
        else if (label_atom_id.value(ei).startsWith('C1')) {
            // likely the anomeric carbon as it is named C1 by convention
            indexHasC1Name = ei;
        }
        else {
            // use any carbon as a fallback
            indexIsCarbon = ei;
        }
    }
    return (indexHasTwoOxygen !== -1 ? indexHasTwoOxygen
        : indexHasOxygenAndCarbon !== -1 ? indexHasOxygenAndCarbon
            : indexHasC1Name !== -1 ? indexHasC1Name
                : indexIsCarbon !== -1 ? indexIsCarbon
                    : elements[ringAtoms[0]]);
}
function getAltId(unit, index) {
    var elements = unit.elements;
    var label_alt_id = unit.model.atomicHierarchy.atoms.label_alt_id;
    return label_alt_id.value(elements[index]);
}
function getDirection(direction, unit, index, center) {
    var position = unit.conformation.position;
    linear_algebra["Vec3"].normalize(direction, linear_algebra["Vec3"].sub(direction, center, position(index, direction)));
    return direction;
}
function getAtomId(unit, index) {
    var elements = unit.elements;
    var label_atom_id = unit.model.atomicHierarchy.atoms.label_atom_id;
    return label_atom_id.value(elements[index]);
}
function filterFusedRings(unitRings, rings) {
    if (!rings || !rings.length)
        return;
    var unit = unitRings.unit, all = unitRings.all;
    var fusedRings = new Set();
    var ringCombinations = combinations(Object(mol_util_array["fillSerial"])(new Array(rings.length)), 2);
    for (var i = 0, il = ringCombinations.length; i < il; ++i) {
        var rc = ringCombinations[i];
        var r0 = all[rings[rc[0]]], r1 = all[rings[rc[1]]];
        if (mol_data_int["SortedArray"].areIntersecting(r0, r1) &&
            unit_rings["a" /* UnitRing */].getAltId(unit, r0) === unit_rings["a" /* UnitRing */].getAltId(unit, r1)) {
            fusedRings.add(rings[rc[0]]);
            fusedRings.add(rings[rc[1]]);
        }
    }
    if (fusedRings.size) {
        var filteredRings = [];
        for (var i = 0, il = rings.length; i < il; ++i) {
            if (!fusedRings.has(rings[i]))
                filteredRings.push(rings[i]);
        }
        return filteredRings;
    }
    else {
        return rings;
    }
}
function getSaccharideComp(compId, model) {
    return model.properties.saccharideComponentMap.get(compId);
}
function computeCarbohydrates(structure) {
    // skip computation if there are no saccharide components in any model
    if (structure.models.reduce(function (a, v) { return a + v.properties.saccharideComponentMap.size; }, 0) === 0)
        return EmptyCarbohydrates;
    var links = [];
    var terminalLinks = [];
    var elements = [];
    var partialElements = [];
    var elementsWithRingMap = new Map();
    function ringElementKey(residueIndex, unitId, altId) {
        return residueIndex + "|" + unitId + "|" + altId;
    }
    function addRingElement(key, elementIndex) {
        if (elementsWithRingMap.has(key))
            elementsWithRingMap.get(key).push(elementIndex);
        else
            elementsWithRingMap.set(key, [elementIndex]);
    }
    function fixLinkDirection(iA, iB) {
        linear_algebra["Vec3"].sub(elements[iA].geometry.direction, elements[iB].geometry.center, elements[iA].geometry.center);
        linear_algebra["Vec3"].normalize(elements[iA].geometry.direction, elements[iA].geometry.direction);
    }
    var tmpV = linear_algebra["Vec3"].zero();
    function fixTerminalLinkDirection(iA, indexB, unitB) {
        var pos = unitB.conformation.position, geo = elements[iA].geometry;
        linear_algebra["Vec3"].sub(geo.direction, pos(unitB.elements[indexB], tmpV), geo.center);
        linear_algebra["Vec3"].normalize(geo.direction, geo.direction);
    }
    // get carbohydrate elements and carbohydrate links induced by intra-residue bonds
    for (var i = 0, il = structure.units.length; i < il; ++i) {
        var unit = structure.units[i];
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        var model = unit.model, rings = unit.rings;
        var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments, atoms = _a.atoms;
        var label_comp_id = atoms.label_comp_id;
        var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, unit.elements);
        var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, unit.elements);
        var sugarResidueMap = void 0;
        while (chainIt.hasNext) {
            residueIt.setSegment(chainIt.move());
            while (residueIt.hasNext) {
                var residueIndex = residueIt.move().index;
                var saccharideComp = getSaccharideComp(label_comp_id.value(residueAtomSegments.offsets[residueIndex]), model);
                if (!saccharideComp)
                    continue;
                if (!sugarResidueMap) {
                    sugarResidueMap = unit_rings["b" /* UnitRings */].byFingerprintAndResidue(rings, SugarRingFps);
                }
                var sugarRings = filterFusedRings(rings, sugarResidueMap.get(residueIndex));
                if (!sugarRings || !sugarRings.length) {
                    partialElements.push({ unit: unit, residueIndex: residueIndex, component: saccharideComp });
                    continue;
                }
                var ringElements = [];
                for (var j = 0, jl = sugarRings.length; j < jl; ++j) {
                    var ringAtoms = rings.all[sugarRings[j]];
                    var anomericCarbon = getAnomericCarbon(unit, ringAtoms);
                    var ma = principal_axes["a" /* PrincipalAxes */].calculateMomentsAxes(Object(structure_util["c" /* getPositions */])(unit, ringAtoms));
                    var center = linear_algebra["Vec3"].copy(linear_algebra["Vec3"].zero(), ma.origin);
                    var normal = linear_algebra["Vec3"].copy(linear_algebra["Vec3"].zero(), ma.dirC);
                    var direction = getDirection(linear_algebra["Vec3"].zero(), unit, anomericCarbon, center);
                    linear_algebra["Vec3"].orthogonalize(direction, normal, direction);
                    var ringAltId = unit_rings["a" /* UnitRing */].getAltId(unit, ringAtoms);
                    var elementIndex = elements.length;
                    ringElements.push(elementIndex);
                    addRingElement(ringElementKey(residueIndex, unit.id, ringAltId), elementIndex);
                    if (ringAltId)
                        addRingElement(ringElementKey(residueIndex, unit.id, ''), elementIndex);
                    elements.push({
                        geometry: { center: center, normal: normal, direction: direction },
                        component: saccharideComp,
                        ringIndex: sugarRings[j],
                        altId: ringAltId,
                        unit: unit, residueIndex: residueIndex
                    });
                }
                // add carbohydrate links induced by intra-residue bonds
                // (e.g. for structures from the PDB archive __before__ carbohydrate remediation)
                var ringCombinations = combinations(Object(mol_util_array["fillSerial"])(new Array(sugarRings.length)), 2);
                for (var j = 0, jl = ringCombinations.length; j < jl; ++j) {
                    var rc = ringCombinations[j];
                    var r0 = rings.all[sugarRings[rc[0]]], r1 = rings.all[sugarRings[rc[1]]];
                    // 1,6 glycosidic links are distance 3 and 1,4 glycosidic links are distance 2
                    if (graph["a" /* IntAdjacencyGraph */].areVertexSetsConnected(unit.bonds, r0, r1, 3)) {
                        var re0 = ringElements[rc[0]];
                        var re1 = ringElements[rc[1]];
                        if (elements[re0].altId === elements[re1].altId) {
                            // TODO handle better, for now fix both directions as it is unclear where the C1 atom is
                            //      would need to know the path connecting the two rings
                            fixLinkDirection(re0, re1);
                            fixLinkDirection(re1, re0);
                            links.push({ carbohydrateIndexA: re0, carbohydrateIndexB: re1 });
                            links.push({ carbohydrateIndexA: re1, carbohydrateIndexB: re0 });
                        }
                    }
                }
            }
        }
    }
    function getRingElementIndices(unit, index) {
        return elementsWithRingMap.get(ringElementKey(unit.getResidueIndex(index), unit.id, getAltId(unit, index))) || [];
    }
    // add carbohydrate links induced by intra-unit bonds
    // (e.g. for structures from the PDB archive __after__ carbohydrate remediation)
    for (var i = 0, il = elements.length; i < il; ++i) {
        var cA = elements[i];
        var unit = cA.unit;
        for (var j = i + 1; j < il; ++j) {
            var cB = elements[j];
            if (unit !== cB.unit || cA.residueIndex === cB.residueIndex)
                continue;
            var rA = unit.rings.all[cA.ringIndex];
            var rB = unit.rings.all[cB.ringIndex];
            if (graph["a" /* IntAdjacencyGraph */].areVertexSetsConnected(unit.bonds, rA, rB, 3)) {
                // TODO handle better, for now fix both directions as it is unclear where the C1 atom is
                //      would need to know the path connecting the two rings
                fixLinkDirection(i, j);
                fixLinkDirection(j, i);
                links.push({ carbohydrateIndexA: i, carbohydrateIndexB: j });
                links.push({ carbohydrateIndexA: j, carbohydrateIndexB: i });
            }
        }
    }
    // get carbohydrate links induced by inter-unit bonds, that is
    // inter monosaccharide links for structures from the
    // PDB archive __before__ carbohydrate remediation
    // plus terminal links for __before__ and __after__
    for (var i = 0, il = structure.units.length; i < il; ++i) {
        var unit = structure.units[i];
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        structure.interUnitBonds.getConnectedUnits(unit).forEach(function (pairBonds) {
            pairBonds.connectedIndices.forEach(function (indexA) {
                pairBonds.getEdges(indexA).forEach(function (_a) {
                    var props = _a.props, indexB = _a.indexB;
                    if (!types["BondType"].isCovalent(props.flag))
                        return;
                    var unitA = pairBonds.unitA, unitB = pairBonds.unitB;
                    var ringElementIndicesA = getRingElementIndices(unitA, indexA);
                    var ringElementIndicesB = getRingElementIndices(unitB, indexB);
                    if (ringElementIndicesA.length > 0 && ringElementIndicesB.length > 0) {
                        var lA = ringElementIndicesA.length;
                        var lB = ringElementIndicesB.length;
                        for (var j = 0, jl = Math.max(lA, lB); j < jl; ++j) {
                            var ringElementIndexA = ringElementIndicesA[Math.min(j, lA - 1)];
                            var ringElementIndexB = ringElementIndicesB[Math.min(j, lB - 1)];
                            var atomIdA = getAtomId(unitA, indexA);
                            if (atomIdA.startsWith('O1') || atomIdA.startsWith('C1')) {
                                fixLinkDirection(ringElementIndexA, ringElementIndexB);
                            }
                            links.push({
                                carbohydrateIndexA: ringElementIndexA,
                                carbohydrateIndexB: ringElementIndexB
                            });
                        }
                    }
                    else if (ringElementIndicesB.length === 0) {
                        for (var _i = 0, ringElementIndicesA_1 = ringElementIndicesA; _i < ringElementIndicesA_1.length; _i++) {
                            var ringElementIndexA = ringElementIndicesA_1[_i];
                            var atomIdA = getAtomId(unitA, indexA);
                            if (atomIdA.startsWith('O1') || atomIdA.startsWith('C1')) {
                                fixTerminalLinkDirection(ringElementIndexA, indexB, unitB);
                            }
                            terminalLinks.push({
                                carbohydrateIndex: ringElementIndexA,
                                elementIndex: indexB,
                                elementUnit: unitB,
                                fromCarbohydrate: true
                            });
                        }
                    }
                    else if (ringElementIndicesA.length === 0) {
                        for (var _b = 0, ringElementIndicesB_1 = ringElementIndicesB; _b < ringElementIndicesB_1.length; _b++) {
                            var ringElementIndexB = ringElementIndicesB_1[_b];
                            terminalLinks.push({
                                carbohydrateIndex: ringElementIndexB,
                                elementIndex: indexA,
                                elementUnit: unitA,
                                fromCarbohydrate: false
                            });
                        }
                    }
                });
            });
        });
    }
    return Object(tslib_es6["__assign"])({ links: links, terminalLinks: terminalLinks, elements: elements, partialElements: partialElements }, buildLookups(elements, links, terminalLinks));
}
function buildLookups(elements, links, terminalLinks) {
    function key(unit, element) {
        return Object(util["f" /* cantorPairing */])(unit.id, element);
    }
    function getIndices(map, unit, index) {
        var indices = [];
        var il = map.get(key(unit, index));
        if (il !== undefined) {
            for (var _i = 0, il_1 = il; _i < il_1.length; _i++) {
                var i = il_1[_i];
                Object(mol_util_array["arraySetAdd"])(indices, i);
            }
        }
        return indices;
    }
    // elements
    var elementsMap = new Map();
    for (var i = 0, il = elements.length; i < il; ++i) {
        var _a = elements[i], unit = _a.unit, ringIndex = _a.ringIndex;
        var ring = unit.rings.all[ringIndex];
        for (var j = 0, jl = ring.length; j < jl; ++j) {
            var k = key(unit, unit.elements[ring[j]]);
            var e = elementsMap.get(k);
            if (e === undefined)
                elementsMap.set(k, [i]);
            else
                e.push(i);
        }
    }
    function getElementIndices(unit, index) {
        return getIndices(elementsMap, unit, index);
    }
    // links
    var linksMap = new Map();
    for (var i = 0, il = links.length; i < il; ++i) {
        var l = links[i];
        var _b = elements[l.carbohydrateIndexA], unit = _b.unit, ringIndex = _b.ringIndex;
        var ring = unit.rings.all[ringIndex];
        for (var j = 0, jl = ring.length; j < jl; ++j) {
            var k = key(unit, unit.elements[ring[j]]);
            var e = linksMap.get(k);
            if (e === undefined)
                linksMap.set(k, [i]);
            else
                e.push(i);
        }
    }
    function getLinkIndices(unit, index) {
        return getIndices(linksMap, unit, index);
    }
    // terminal links
    var terminalLinksMap = new Map();
    for (var i = 0, il = terminalLinks.length; i < il; ++i) {
        var _c = terminalLinks[i], fromCarbohydrate = _c.fromCarbohydrate, carbohydrateIndex = _c.carbohydrateIndex, elementUnit = _c.elementUnit, elementIndex = _c.elementIndex;
        if (fromCarbohydrate) {
            var _d = elements[carbohydrateIndex], unit = _d.unit, ringIndex = _d.ringIndex;
            var ring = unit.rings.all[ringIndex];
            for (var j = 0, jl = ring.length; j < jl; ++j) {
                var k = key(unit, unit.elements[ring[j]]);
                var e = terminalLinksMap.get(k);
                if (e === undefined)
                    terminalLinksMap.set(k, [i]);
                else
                    e.push(i);
            }
        }
        else {
            var k = key(elementUnit, elementUnit.elements[elementIndex]);
            var e = terminalLinksMap.get(k);
            if (e === undefined)
                terminalLinksMap.set(k, [i]);
            else
                e.push(i);
        }
    }
    function getTerminalLinkIndices(unit, index) {
        return getIndices(terminalLinksMap, unit, index);
    }
    return { getElementIndices: getElementIndices, getLinkIndices: getLinkIndices, getTerminalLinkIndices: getTerminalLinkIndices };
}
//# sourceMappingURL=compute.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/id-factory.js
var id_factory = __webpack_require__(96);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic.js
var atomic = __webpack_require__(119);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/selection.js
var selection = __webpack_require__(38);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-structure-property.js
var custom_structure_property = __webpack_require__(204);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/structure.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





















var structure_Structure = /** @class */ (function () {
    function Structure(units, props) {
        if (props === void 0) { props = {}; }
        this._props = {
            hashCode: -1,
            transformHash: -1,
            elementCount: -1,
            bondCount: -1,
            uniqueElementCount: -1,
            atomicResidueCount: -1,
            polymerResidueCount: -1,
            polymerUnitCount: -1,
            coordinateSystem: symmetry_operator["a" /* SymmetryOperator */].Default,
            label: ''
        };
        var _a = this.initUnits(units), unitMap = _a.unitMap, unitIndexMap = _a.unitIndexMap;
        this.unitMap = unitMap;
        this.unitIndexMap = unitIndexMap;
        this.units = units;
        if (props.parent)
            this._props.parent = props.parent.parent || props.parent;
        if (props.coordinateSystem)
            this._props.coordinateSystem = props.coordinateSystem;
        else if (props.parent)
            this._props.coordinateSystem = props.parent.coordinateSystem;
        if (props.label)
            this._props.label = props.label;
        else if (props.parent)
            this._props.label = props.parent.label;
        if (props.masterModel)
            this._props.masterModel = props.masterModel;
        else if (props.parent)
            this._props.masterModel = props.parent.masterModel;
        if (props.representativeModel)
            this._props.representativeModel = props.representativeModel;
        else if (props.parent)
            this._props.representativeModel = props.parent.representativeModel;
    }
    Structure.prototype.subsetBuilder = function (isSorted) {
        return new subset_builder_StructureSubsetBuilder(this, isSorted);
    };
    Object.defineProperty(Structure.prototype, "elementCount", {
        /** Count of all elements in the structure, i.e. the sum of the elements in the units */
        get: function () {
            return this._props.elementCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "bondCount", {
        /** Count of all bonds (intra- and inter-unit) in the structure */
        get: function () {
            if (!this._props.bondCount) {
                this._props.bondCount = this.interUnitBonds.edgeCount + bonds["a" /* Bond */].getIntraUnitBondCount(this);
            }
            return this._props.bondCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "hasCustomProperties", {
        get: function () {
            return !!this._props.customProps && this._props.customProps.all.length > 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "customPropertyDescriptors", {
        get: function () {
            if (!this._props.customProps)
                this._props.customProps = new custom_property["CustomProperties"]();
            return this._props.customProps;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "currentPropertyData", {
        /**
         * Property data unique to this instance of the structure.
         */
        get: function () {
            if (!this._props.propertyData)
                this._props.propertyData = Object.create(null);
            return this._props.propertyData;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "inheritedPropertyData", {
        /**
         * Property data of the parent structure if it exists, currentPropertyData otherwise.
         */
        get: function () {
            return this.parent ? this.parent.currentPropertyData : this.currentPropertyData;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "polymerResidueCount", {
        /** Count of all polymer residues in the structure */
        get: function () {
            if (this._props.polymerResidueCount === -1) {
                this._props.polymerResidueCount = getPolymerResidueCount(this);
            }
            return this._props.polymerResidueCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "polymerUnitCount", {
        get: function () {
            if (this._props.polymerUnitCount === -1) {
                this._props.polymerUnitCount = getPolymerUnitCount(this);
            }
            return this._props.polymerUnitCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "uniqueElementCount", {
        get: function () {
            if (this._props.uniqueElementCount === -1) {
                this._props.uniqueElementCount = getUniqueElementCount(this);
            }
            return this._props.uniqueElementCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "atomicResidueCount", {
        get: function () {
            if (this._props.atomicResidueCount === -1) {
                this._props.atomicResidueCount = getAtomicResidueCount(this);
            }
            return this._props.atomicResidueCount;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "isCoarseGrained", {
        /**
         * Coarse-grained structure, defined as containing less than
         * twice as many elements as polymer residues
         */
        get: function () {
            var ec = this.elementCount;
            var prc = this.polymerResidueCount;
            return prc && ec ? ec / prc < 2 : false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "isEmpty", {
        get: function () {
            return this.units.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "hashCode", {
        get: function () {
            if (this._props.hashCode !== -1)
                return this._props.hashCode;
            return this.computeHash();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "transformHash", {
        /** Hash based on all unit.id values in the structure, reflecting the units transformation */
        get: function () {
            if (this._props.transformHash !== -1)
                return this._props.transformHash;
            this._props.transformHash = Object(util["l" /* hashFnv32a */])(this.units.map(function (u) { return u.id; }));
            return this._props.transformHash;
        },
        enumerable: false,
        configurable: true
    });
    Structure.prototype.computeHash = function () {
        var hash = 23;
        for (var i = 0, _i = this.units.length; i < _i; i++) {
            var u = this.units[i];
            hash = (31 * hash + u.id) | 0;
            hash = (31 * hash + mol_data_int["SortedArray"].hashCode(u.elements)) | 0;
        }
        hash = (31 * hash + this.elementCount) | 0;
        hash = Object(util["h" /* hash1 */])(hash);
        if (hash === -1)
            hash = 0;
        this._props.hashCode = hash;
        return hash;
    };
    /** Returns a new element location iterator */
    Structure.prototype.elementLocations = function () {
        return new Structure.ElementLocationIterator(this);
    };
    Object.defineProperty(Structure.prototype, "root", {
        /** The parent or itself in case this is the root */
        get: function () {
            return this._props.parent || this;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "parent", {
        /** The root/top-most parent or `undefined` in case this is the root */
        get: function () {
            return this._props.parent;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "coordinateSystem", {
        /**
         * Conformation transformation that was applied to every unit of this structure.
         *
         * Coordinate system applies to the *current* structure only.
         * A parent structure can have a different coordinate system and thefore it has to be composed "manualy"
         * by the consumer.
         */
        get: function () {
            return this._props.coordinateSystem;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "label", {
        get: function () {
            return this._props.label;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "boundary", {
        get: function () {
            return this.lookup3d.boundary;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "lookup3d", {
        get: function () {
            if (this._props.lookup3d)
                return this._props.lookup3d;
            this._props.lookup3d = new lookup3d_StructureLookup3D(this);
            return this._props.lookup3d;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "interUnitBonds", {
        get: function () {
            if (this._props.interUnitBonds)
                return this._props.interUnitBonds;
            this._props.interUnitBonds = Object(bonds["b" /* computeInterUnitBonds */])(this);
            return this._props.interUnitBonds;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "unitSymmetryGroups", {
        get: function () {
            if (this._props.unitSymmetryGroups)
                return this._props.unitSymmetryGroups;
            this._props.unitSymmetryGroups = symmetry["a" /* default */].computeTransformGroups(this);
            return this._props.unitSymmetryGroups;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "unitSymmetryGroupsIndexMap", {
        /** Maps unit.invariantId to index of SymmetryGroup in unitSymmetryGroups array */
        get: function () {
            if (this._props.unitSymmetryGroupsIndexMap)
                return this._props.unitSymmetryGroupsIndexMap;
            this._props.unitSymmetryGroupsIndexMap = structure_unit["a" /* default */].SymmetryGroup.getUnitSymmetryGroupsIndexMap(this.unitSymmetryGroups);
            return this._props.unitSymmetryGroupsIndexMap;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "carbohydrates", {
        get: function () {
            if (this._props.carbohydrates)
                return this._props.carbohydrates;
            this._props.carbohydrates = computeCarbohydrates(this);
            return this._props.carbohydrates;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "models", {
        get: function () {
            if (this._props.models)
                return this._props.models;
            this._props.models = getModels(this);
            return this._props.models;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "uniqueResidueNames", {
        get: function () {
            return this._props.uniqueResidueNames
                || (this._props.uniqueResidueNames = getUniqueResidueNames(this));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "uniqueElementSymbols", {
        get: function () {
            return this._props.uniqueElementSymbols
                || (this._props.uniqueElementSymbols = getUniqueElementSymbols(this));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "entityIndices", {
        get: function () {
            return this._props.entityIndices
                || (this._props.entityIndices = getEntityIndices(this));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "uniqueAtomicResidueIndices", {
        get: function () {
            return this._props.uniqueAtomicResidueIndices
                || (this._props.uniqueAtomicResidueIndices = getUniqueAtomicResidueIndices(this));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "isAtomic", {
        /** Contains only atomic units */
        get: function () {
            for (var _a = 0, _b = this.units; _a < _b.length; _a++) {
                var u = _b[_a];
                if (structure_unit["a" /* default */].isAtomic(u))
                    return false;
            }
            return true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "hasAtomic", {
        /** Contains some atomic units */
        get: function () {
            for (var _a = 0, _b = this.units; _a < _b.length; _a++) {
                var u = _b[_a];
                if (structure_unit["a" /* default */].isAtomic(u))
                    return true;
            }
            return false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "isCoarse", {
        /** Contains only coarse units */
        get: function () {
            for (var _a = 0, _b = this.units; _a < _b.length; _a++) {
                var u = _b[_a];
                if (structure_unit["a" /* default */].isCoarse(u))
                    return false;
            }
            return true;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "hasCoarse", {
        /** Contains some coarse units */
        get: function () {
            for (var _a = 0, _b = this.units; _a < _b.length; _a++) {
                var u = _b[_a];
                if (structure_unit["a" /* default */].isCoarse(u))
                    return true;
            }
            return false;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "serialMapping", {
        /**
         * Provides mapping for serial element indices accross all units.
         *
         * Note that this is especially costly for structures with many units that are grouped
         * into few symmetry groups. Use only when needed and prefer `StructureElement`
         * to address elements in a structure.
         */
        get: function () {
            return this._props.serialMapping || (this._props.serialMapping = getSerialMapping(this));
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "model", {
        /**
         * If the structure is based on a single model or has a master-/representative-model, return it.
         * Otherwise throw an exception.
         */
        get: function () {
            if (this._props.model)
                return this._props.model;
            if (this._props.representativeModel)
                return this._props.representativeModel;
            if (this._props.masterModel)
                return this._props.masterModel;
            var models = this.models;
            if (models.length > 1) {
                throw new Error('The structure is based on multiple models and has neither a master- nor a representative-model.');
            }
            this._props.model = models[0];
            return this._props.model;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "masterModel", {
        /** The master-model, other models can have bonds to it  */
        get: function () {
            return this._props.masterModel;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Structure.prototype, "representativeModel", {
        /** A representative model, e.g. the first model of a trajectory */
        get: function () {
            return this._props.representativeModel;
        },
        enumerable: false,
        configurable: true
    });
    Structure.prototype.hasElement = function (e) {
        if (!this.unitMap.has(e.unit.id))
            return false;
        return mol_data_int["SortedArray"].has(this.unitMap.get(e.unit.id).elements, e.element);
    };
    Structure.prototype.getModelIndex = function (m) {
        return this.models.indexOf(m);
    };
    Structure.prototype.initUnits = function (units) {
        var unitMap = mol_data_int["IntMap"].Mutable();
        var unitIndexMap = mol_data_int["IntMap"].Mutable();
        var elementCount = 0;
        var isSorted = true;
        var lastId = units.length > 0 ? units[0].id : 0;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var u = units[i];
            unitMap.set(u.id, u);
            elementCount += u.elements.length;
            if (u.id < lastId)
                isSorted = false;
            lastId = u.id;
        }
        if (!isSorted)
            Object(util["p" /* sort */])(units, 0, units.length, cmpUnits, util["e" /* arraySwap */]);
        for (var i = 0, _i = units.length; i < _i; i++) {
            unitIndexMap.set(units[i].id, i);
        }
        this._props.elementCount = elementCount;
        return { unitMap: unitMap, unitIndexMap: unitIndexMap };
    };
    return Structure;
}());
function cmpUnits(units, i, j) { return units[i].id - units[j].id; }
function getModels(s) {
    var units = s.units;
    var arr = generic["c" /* UniqueArray */].create();
    for (var _a = 0, units_1 = units; _a < units_1.length; _a++) {
        var u = units_1[_a];
        generic["c" /* UniqueArray */].add(arr, u.model.id, u.model);
    }
    return arr.array;
}
function getUniqueResidueNames(s) {
    var microheterogeneityCompIds = properties["a" /* default */].residue.microheterogeneityCompIds;
    var names = new Set();
    var loc = structure_element["a" /* default */].Location.create(s);
    for (var _a = 0, _b = s.unitSymmetryGroups; _a < _b.length; _a++) {
        var unitGroup = _b[_a];
        var unit = unitGroup.units[0];
        // TODO: support coarse unit?
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        var residues = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements);
        loc.unit = unit;
        while (residues.hasNext) {
            var seg = residues.move();
            loc.element = unit.elements[seg.start];
            var compIds = microheterogeneityCompIds(loc);
            for (var _c = 0, compIds_1 = compIds; _c < compIds_1.length; _c++) {
                var compId = compIds_1[_c];
                names.add(compId);
            }
        }
    }
    return names;
}
function getUniqueElementSymbols(s) {
    var prop = properties["a" /* default */].atom.type_symbol;
    var symbols = new Set();
    var loc = structure_element["a" /* default */].Location.create(s);
    for (var _a = 0, _b = s.unitSymmetryGroups; _a < _b.length; _a++) {
        var unitGroup = _b[_a];
        var unit = unitGroup.units[0];
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        loc.unit = unit;
        for (var i = 0, il = unit.elements.length; i < il; ++i) {
            loc.element = unit.elements[i];
            symbols.add(prop(loc));
        }
    }
    return symbols;
}
function getEntityIndices(structure) {
    var units = structure.units;
    var l = structure_element["a" /* default */].Location.create(structure);
    var keys = generic["c" /* UniqueArray */].create();
    for (var _a = 0, units_2 = units; _a < units_2.length; _a++) {
        var unit = units_2[_a];
        var prop = unit.kind === 0 /* Atomic */ ? properties["a" /* default */].entity.key : properties["a" /* default */].coarse.entityKey;
        l.unit = unit;
        var elements = unit.elements;
        var chainsIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements);
        while (chainsIt.hasNext) {
            var chainSegment = chainsIt.move();
            l.element = elements[chainSegment.start];
            var key = prop(l);
            generic["c" /* UniqueArray */].add(keys, key, key);
        }
    }
    Object(util["q" /* sortArray */])(keys.array);
    return keys.array;
}
function getUniqueAtomicResidueIndices(structure) {
    var map = new Map();
    var modelIds = [];
    var unitGroups = structure.unitSymmetryGroups;
    for (var _a = 0, unitGroups_1 = unitGroups; _a < unitGroups_1.length; _a++) {
        var unitGroup = unitGroups_1[_a];
        var unit = unitGroup.units[0];
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        var uniqueResidues = void 0;
        if (map.has(unit.model.id))
            uniqueResidues = map.get(unit.model.id);
        else {
            uniqueResidues = generic["c" /* UniqueArray */].create();
            modelIds.push(unit.model.id);
            map.set(unit.model.id, uniqueResidues);
        }
        var residues = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements);
        while (residues.hasNext) {
            var seg = residues.move();
            generic["c" /* UniqueArray */].add(uniqueResidues, seg.index, seg.index);
        }
    }
    var ret = new Map();
    for (var _b = 0, modelIds_1 = modelIds; _b < modelIds_1.length; _b++) {
        var id = modelIds_1[_b];
        var array = map.get(id).array;
        Object(util["q" /* sortArray */])(array);
        ret.set(id, array);
    }
    return ret;
}
function getUniqueElementCount(structure) {
    var unitSymmetryGroups = structure.unitSymmetryGroups;
    var uniqueElementCount = 0;
    for (var i = 0, _i = unitSymmetryGroups.length; i < _i; i++) {
        uniqueElementCount += unitSymmetryGroups[i].elements.length;
    }
    return uniqueElementCount;
}
function getPolymerResidueCount(structure) {
    var units = structure.units;
    var polymerResidueCount = 0;
    for (var i = 0, _i = units.length; i < _i; i++) {
        polymerResidueCount += units[i].polymerElements.length;
    }
    return polymerResidueCount;
}
function getPolymerUnitCount(structure) {
    var units = structure.units;
    var polymerUnitCount = 0;
    for (var i = 0, _i = units.length; i < _i; i++) {
        if (units[i].polymerElements.length > 0)
            polymerUnitCount += 1;
    }
    return polymerUnitCount;
}
function getAtomicResidueCount(structure) {
    var units = structure.units;
    var atomicResidueCount = 0;
    for (var i = 0, _i = units.length; i < _i; i++) {
        var unit = units[i];
        if (!structure_unit["a" /* default */].isAtomic(unit))
            continue;
        var elements = unit.elements, residueIndex = unit.residueIndex;
        var idx = -1;
        var prevIdx = -1;
        for (var j = 0, jl = elements.length; j < jl; ++j) {
            idx = residueIndex[elements[j]];
            if (idx !== prevIdx) {
                atomicResidueCount += 1;
                prevIdx = idx;
            }
        }
    }
    return atomicResidueCount;
}
function getSerialMapping(structure) {
    var units = structure.units, elementCount = structure.elementCount, unitIndexMap = structure.unitIndexMap;
    var cumulativeUnitElementCount = new Uint32Array(units.length);
    var unitIndices = new Uint32Array(elementCount);
    var elementIndices = new Uint32Array(elementCount);
    for (var i = 0, m = 0, il = units.length; i < il; ++i) {
        cumulativeUnitElementCount[i] = m;
        var elements = units[i].elements;
        for (var j = 0, jl = elements.length; j < jl; ++j) {
            var mj = m + j;
            unitIndices[mj] = i;
            elementIndices[mj] = elements[j];
        }
        m += elements.length;
    }
    return {
        cumulativeUnitElementCount: cumulativeUnitElementCount,
        unitIndices: unitIndices,
        elementIndices: elementIndices,
        getSerialIndex: function (unit, element) { return cumulativeUnitElementCount[unitIndexMap.get(unit.id)] + mol_data_int["OrderedSet"].indexOf(unit.elements, element); }
    };
}
(function (Structure) {
    Structure.Empty = new Structure([]);
    function Loci(structure) {
        return { kind: 'structure-loci', structure: structure };
    }
    Structure.Loci = Loci;
    function toStructureElementLoci(structure) {
        var elements = [];
        for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
            var unit = _b[_a];
            elements.push({ unit: unit, indices: mol_data_int["Interval"].ofBounds(0, unit.elements.length) });
        }
        return structure_element["a" /* default */].Loci(structure, elements);
    }
    Structure.toStructureElementLoci = toStructureElementLoci;
    function toSubStructureElementLoci(parent, structure) {
        return selection["a" /* StructureSelection */].toLociWithSourceUnits(selection["a" /* StructureSelection */].Singletons(parent, structure));
    }
    Structure.toSubStructureElementLoci = toSubStructureElementLoci;
    function isLoci(x) {
        return !!x && x.kind === 'structure-loci';
    }
    Structure.isLoci = isLoci;
    function areLociEqual(a, b) {
        return a.structure === b.structure;
    }
    Structure.areLociEqual = areLociEqual;
    function isLociEmpty(loci) {
        return loci.structure.isEmpty;
    }
    Structure.isLociEmpty = isLociEmpty;
    function remapLoci(loci, structure) {
        if (structure === loci.structure)
            return loci;
        return Loci(structure);
    }
    Structure.remapLoci = remapLoci;
    function create(units, props) {
        return new Structure(units, props);
    }
    Structure.create = create;
    function ofTrajectory(trajectory) {
        if (trajectory.length === 0)
            return Structure.Empty;
        var units = [];
        var count = 0;
        for (var i = 0, il = trajectory.length; i < il; ++i) {
            var structure = ofModel(trajectory[i]);
            for (var j = 0, jl = structure.units.length; j < jl; ++j) {
                var u = structure.units[j];
                var invariantId = u.invariantId + count;
                var chainGroupId = u.chainGroupId + count;
                var newUnit = structure_unit["a" /* default */].create(units.length, invariantId, chainGroupId, u.traits, u.kind, u.model, u.conformation.operator, u.elements);
                units.push(newUnit);
            }
            count = units.length;
        }
        return create(units, { representativeModel: trajectory[0], label: trajectory[0].label });
    }
    Structure.ofTrajectory = ofTrajectory;
    var PARTITION = false;
    /**
     * Construct a Structure from a model.
     *
     * Generally, a single unit corresponds to a single chain, with the exception
     * of consecutive "single atom chains" with same entity_id and same auth_asym_id.
     */
    function ofModel(model) {
        var chains = model.atomicHierarchy.chainAtomSegments;
        var index = model.atomicHierarchy.index;
        var auth_asym_id = model.atomicHierarchy.chains.auth_asym_id;
        var atomicChainOperatorMappinng = model.atomicChainOperatorMappinng;
        var builder = new StructureBuilder({ label: model.label });
        for (var c = 0; c < chains.count; c++) {
            var operator = atomicChainOperatorMappinng.get(c) || symmetry_operator["a" /* SymmetryOperator */].Default;
            var start = chains.offsets[c];
            // set to true for chains that consist of "single atom residues",
            // note that it assumes there are no "zero atom residues"
            var singleAtomResidues = atomic["AtomicHierarchy"].chainResidueCount(model.atomicHierarchy, c) === chains.offsets[c + 1] - chains.offsets[c];
            // merge all consecutive "single atom chains" with same entity_id and same auth_asym_id
            var multiChain = false;
            while (c + 1 < chains.count
                && chains.offsets[c + 1] - chains.offsets[c] === 1
                && chains.offsets[c + 2] - chains.offsets[c + 1] === 1) {
                singleAtomResidues = true;
                var e1 = index.getEntityFromChain(c);
                var e2 = index.getEntityFromChain(c + 1);
                if (e1 !== e2)
                    break;
                var a1 = auth_asym_id.value(c);
                var a2 = auth_asym_id.value(c + 1);
                if (a1 !== a2)
                    break;
                var op1 = atomicChainOperatorMappinng.get(c);
                var op2 = atomicChainOperatorMappinng.get(c + 1);
                if (op1 !== op2)
                    break;
                multiChain = true;
                c++;
            }
            var elements = mol_data_int["SortedArray"].ofBounds(start, chains.offsets[c + 1]);
            if (PARTITION) {
                // check for polymer to exclude CA/P-only models
                if (singleAtomResidues && !isPolymerChain(model, c)) {
                    partitionAtomicUnitByAtom(model, elements, builder, multiChain, operator);
                }
                else if (elements.length > 200000 || isWaterChain(model, c)) {
                    // split up very large chains e.g. lipid bilayers, micelles or water with explicit H
                    partitionAtomicUnitByResidue(model, elements, builder, multiChain, operator);
                }
                else {
                    builder.addUnit(0 /* Atomic */, model, operator, elements, multiChain ? 1 /* MultiChain */ : 0 /* None */);
                }
            }
            else {
                builder.addUnit(0 /* Atomic */, model, operator, elements, multiChain ? 1 /* MultiChain */ : 0 /* None */);
            }
        }
        var cs = model.coarseHierarchy;
        if (cs.isDefined) {
            if (cs.spheres.count > 0) {
                addCoarseUnits(builder, model, model.coarseHierarchy.spheres, 1 /* Spheres */);
            }
            if (cs.gaussians.count > 0) {
                addCoarseUnits(builder, model, model.coarseHierarchy.gaussians, 2 /* Gaussians */);
            }
        }
        return builder.getStructure();
    }
    Structure.ofModel = ofModel;
    function isWaterChain(model, chainIndex) {
        var e = model.atomicHierarchy.index.getEntityFromChain(chainIndex);
        return model.entities.data.type.value(e) === 'water';
    }
    function isPolymerChain(model, chainIndex) {
        var e = model.atomicHierarchy.index.getEntityFromChain(chainIndex);
        return model.entities.data.type.value(e) === 'polymer';
    }
    function partitionAtomicUnitByAtom(model, indices, builder, multiChain, operator) {
        var _a = model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
        var position = { x: x, y: y, z: z, indices: indices };
        var lookup = Object(geometry["c" /* GridLookup3D */])(position, Object(boundary["a" /* getBoundary */])(position), 8192);
        var _b = lookup.buckets, offset = _b.offset, count = _b.count, array = _b.array;
        var traits = (multiChain ? 1 /* MultiChain */ : 0 /* None */) | (offset.length > 1 ? 2 /* Partitioned */ : 0 /* None */);
        builder.beginChainGroup();
        for (var i = 0, _i = offset.length; i < _i; i++) {
            var start = offset[i];
            var set = new Int32Array(count[i]);
            for (var j = 0, _j = count[i]; j < _j; j++) {
                set[j] = indices[array[start + j]];
            }
            builder.addUnit(0 /* Atomic */, model, operator, mol_data_int["SortedArray"].ofSortedArray(set), traits);
        }
        builder.endChainGroup();
    }
    // keeps atoms of residues together
    function partitionAtomicUnitByResidue(model, indices, builder, multiChain, operator) {
        var residueAtomSegments = model.atomicHierarchy.residueAtomSegments;
        var startIndices = [];
        var endIndices = [];
        var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, indices);
        while (residueIt.hasNext) {
            var residueSegment = residueIt.move();
            startIndices[startIndices.length] = indices[residueSegment.start];
            endIndices[endIndices.length] = indices[residueSegment.end];
        }
        var firstResidueAtomCount = endIndices[0] - startIndices[0];
        var gridCellCount = 512 * firstResidueAtomCount;
        var _a = model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
        var position = { x: x, y: y, z: z, indices: mol_data_int["SortedArray"].ofSortedArray(startIndices) };
        var lookup = Object(geometry["c" /* GridLookup3D */])(position, Object(boundary["a" /* getBoundary */])(position), gridCellCount);
        var _b = lookup.buckets, offset = _b.offset, count = _b.count, array = _b.array;
        var traits = (multiChain ? 1 /* MultiChain */ : 0 /* None */) | (offset.length > 1 ? 2 /* Partitioned */ : 0 /* None */);
        builder.beginChainGroup();
        for (var i = 0, _i = offset.length; i < _i; i++) {
            var start = offset[i];
            var set = [];
            for (var j = 0, _j = count[i]; j < _j; j++) {
                var k = array[start + j];
                for (var l = startIndices[k], _l = endIndices[k]; l < _l; l++) {
                    set[set.length] = l;
                }
            }
            builder.addUnit(0 /* Atomic */, model, operator, mol_data_int["SortedArray"].ofSortedArray(new Int32Array(set)), traits);
        }
        builder.endChainGroup();
    }
    function addCoarseUnits(builder, model, elements, kind) {
        var chainElementSegments = elements.chainElementSegments;
        for (var cI = 0; cI < chainElementSegments.count; cI++) {
            var elements_1 = mol_data_int["SortedArray"].ofBounds(chainElementSegments.offsets[cI], chainElementSegments.offsets[cI + 1]);
            builder.addUnit(kind, model, symmetry_operator["a" /* SymmetryOperator */].Default, elements_1, 0 /* None */);
        }
    }
    function transform(s, transform) {
        if (linear_algebra["Mat4"].isIdentity(transform))
            return s;
        if (!linear_algebra["Mat4"].isRotationAndTranslation(transform, symmetry_operator["a" /* SymmetryOperator */].RotationTranslationEpsilon))
            throw new Error('Only rotation/translation combination can be applied.');
        var units = [];
        for (var _a = 0, _b = s.units; _a < _b.length; _a++) {
            var u = _b[_a];
            var old = u.conformation.operator;
            var op = symmetry_operator["a" /* SymmetryOperator */].create(old.name, transform, old);
            units.push(u.applyOperator(u.id, op));
        }
        var cs = s.coordinateSystem;
        var newCS = symmetry_operator["a" /* SymmetryOperator */].compose(symmetry_operator["a" /* SymmetryOperator */].create(cs.name, transform, cs), cs);
        return new Structure(units, { parent: s, coordinateSystem: newCS });
    }
    Structure.transform = transform;
    var StructureBuilder = /** @class */ (function () {
        function StructureBuilder(props) {
            if (props === void 0) { props = {}; }
            this.props = props;
            this.units = [];
            this.invariantId = Object(id_factory["a" /* idFactory */])();
            this.chainGroupId = -1;
            this.inChainGroup = false;
            this.p = Object(linear_algebra["Vec3"])();
            this.singleElementUnits = new Map();
        }
        StructureBuilder.prototype.beginChainGroup = function () {
            this.chainGroupId++;
            this.inChainGroup = true;
        };
        StructureBuilder.prototype.endChainGroup = function () {
            this.inChainGroup = false;
        };
        StructureBuilder.prototype.addUnit = function (kind, model, operator, elements, traits, invariantId) {
            if (invariantId === undefined)
                invariantId = this.invariantId();
            var chainGroupId = this.inChainGroup ? this.chainGroupId : ++this.chainGroupId;
            var unit = structure_unit["a" /* default */].create(this.units.length, invariantId, chainGroupId, traits, kind, model, operator, elements);
            return this.add(unit);
        };
        StructureBuilder.prototype.add = function (unit) {
            // this is to avoid adding many identical single atom units,
            // for example, from 'degenerate' spacegroups
            // - Diamond (COD 9008564)
            if (unit.elements.length === 1) {
                unit.conformation.position(unit.elements[0], this.p);
                var hash = [unit.invariantId, this.p[0], this.p[1], this.p[2]].join('|');
                if (this.singleElementUnits.has(hash)) {
                    return this.singleElementUnits.get(hash);
                }
                else {
                    this.singleElementUnits.set(hash, unit);
                }
            }
            this.units.push(unit);
            return unit;
        };
        StructureBuilder.prototype.addWithOperator = function (unit, operator) {
            return this.add(unit.applyOperator(this.units.length, operator));
        };
        StructureBuilder.prototype.getStructure = function () {
            return create(this.units, this.props);
        };
        Object.defineProperty(StructureBuilder.prototype, "isEmpty", {
            get: function () {
                return this.units.length === 0;
            },
            enumerable: false,
            configurable: true
        });
        return StructureBuilder;
    }());
    Structure.StructureBuilder = StructureBuilder;
    function Builder(props) {
        if (props === void 0) { props = {}; }
        return new StructureBuilder(props);
    }
    Structure.Builder = Builder;
    function hashCode(s) {
        return s.hashCode;
    }
    Structure.hashCode = hashCode;
    /** Hash based on all unit.model conformation values in the structure */
    function conformationHash(s) {
        return Object(util["m" /* hashString */])(s.units.map(function (u) { return structure_unit["a" /* default */].conformationId(u); }).join('|'));
    }
    Structure.conformationHash = conformationHash;
    // TODO: there should be a version that properly supports partitioned units
    function areUnitAndIndicesEqual(a, b) {
        if (a === b)
            return true;
        if (a.elementCount !== b.elementCount)
            return false;
        var len = a.units.length;
        if (len !== b.units.length)
            return false;
        for (var i = 0; i < len; i++) {
            if (a.units[i].id !== b.units[i].id)
                return false;
        }
        for (var i = 0; i < len; i++) {
            if (!mol_data_int["SortedArray"].areEqual(a.units[i].elements, b.units[i].elements))
                return false;
        }
        return true;
    }
    Structure.areUnitAndIndicesEqual = areUnitAndIndicesEqual;
    function areEquivalent(a, b) {
        return a === b || (a.hashCode === b.hashCode &&
            symmetry["a" /* default */].areTransformGroupsEquivalent(a.unitSymmetryGroups, b.unitSymmetryGroups));
    }
    Structure.areEquivalent = areEquivalent;
    /** Check if the structures or their parents are equivalent */
    function areRootsEquivalent(a, b) {
        return areEquivalent(a.root, b.root);
    }
    Structure.areRootsEquivalent = areRootsEquivalent;
    /** Check if the structures or their parents are equal */
    function areRootsEqual(a, b) {
        return a.root === b.root;
    }
    Structure.areRootsEqual = areRootsEqual;
    var ElementLocationIterator = /** @class */ (function () {
        function ElementLocationIterator(structure) {
            this.structure = structure;
            this.unitIndex = 0;
            this.maxIdx = 0;
            this.idx = -1;
            this.current = structure_element["a" /* default */].Location.create(structure);
            this.hasNext = structure.elementCount > 0;
            if (this.hasNext) {
                this.elements = structure.units[0].elements;
                this.maxIdx = this.elements.length - 1;
                this.current.unit = structure.units[0];
            }
        }
        ElementLocationIterator.prototype.move = function () {
            this.advance();
            this.current.element = this.elements[this.idx];
            return this.current;
        };
        ElementLocationIterator.prototype.advance = function () {
            if (this.idx < this.maxIdx) {
                this.idx++;
                if (this.idx === this.maxIdx)
                    this.hasNext = this.unitIndex + 1 < this.structure.units.length;
                return;
            }
            this.idx = 0;
            this.unitIndex++;
            if (this.unitIndex >= this.structure.units.length) {
                this.hasNext = false;
                return;
            }
            this.current.unit = this.structure.units[this.unitIndex];
            this.elements = this.current.unit.elements;
            this.maxIdx = this.elements.length - 1;
            if (this.maxIdx === 0) {
                this.hasNext = this.unitIndex + 1 < this.structure.units.length;
            }
        };
        return ElementLocationIterator;
    }());
    Structure.ElementLocationIterator = ElementLocationIterator;
    var distVec = linear_algebra["Vec3"].zero();
    function unitElementMinDistance(unit, p, eRadius) {
        var elements = unit.elements, _a = unit.conformation, position = _a.position, r = _a.r, dV = distVec;
        var minD = Number.MAX_VALUE;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            var d = linear_algebra["Vec3"].distance(p, position(e, dV)) - eRadius - r(e);
            if (d < minD)
                minD = d;
        }
        return minD;
    }
    function minDistanceToPoint(s, point, radius) {
        var units = s.units;
        var minD = Number.MAX_VALUE;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var unit = units[i];
            var d = unitElementMinDistance(unit, point, radius);
            if (d < minD)
                minD = d;
        }
        return minD;
    }
    Structure.minDistanceToPoint = minDistanceToPoint;
    var distPivot = linear_algebra["Vec3"].zero();
    function distance(a, b) {
        if (a.elementCount === 0 || b.elementCount === 0)
            return 0;
        var units = a.units;
        var minD = Number.MAX_VALUE;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var unit = units[i];
            var elements = unit.elements, _a = unit.conformation, position = _a.position, r = _a.r;
            for (var i_1 = 0, _i_1 = elements.length; i_1 < _i_1; i_1++) {
                var e = elements[i_1];
                var d = minDistanceToPoint(b, position(e, distPivot), r(e));
                if (d < minD)
                    minD = d;
            }
        }
        return minD;
    }
    Structure.distance = distance;
    function elementDescription(s) {
        return s.elementCount === 1 ? '1 element' : s.elementCount + " elements";
    }
    Structure.elementDescription = elementDescription;
    function validUnitPair(s, a, b) {
        return s.masterModel
            ? a.model === b.model || a.model === s.masterModel || b.model === s.masterModel
            : a.model === b.model;
    }
    Structure.validUnitPair = validUnitPair;
    /**
     * Iterate over all unit pairs of a structure and invokes callback for valid units
     * and unit pairs if within a max distance.
     */
    function eachUnitPair(structure, callback, props) {
        var maxRadius = props.maxRadius, validUnit = props.validUnit, validUnitPair = props.validUnitPair;
        if (!structure.units.some(function (u) { return validUnit(u); }))
            return;
        var lookup = structure.lookup3d;
        var imageCenter = linear_algebra["Vec3"].zero();
        for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
            var unit = _b[_a];
            if (!validUnit(unit))
                continue;
            var bs = unit.lookup3d.boundary.sphere;
            linear_algebra["Vec3"].transformMat4(imageCenter, bs.center, unit.conformation.operator.matrix);
            var closeUnits = lookup.findUnitIndices(imageCenter[0], imageCenter[1], imageCenter[2], bs.radius + maxRadius);
            for (var i = 0; i < closeUnits.count; i++) {
                var other = structure.units[closeUnits.indices[i]];
                if (!validUnit(other) || unit.id >= other.id || !validUnitPair(unit, other))
                    continue;
                if (other.elements.length >= unit.elements.length)
                    callback(unit, other);
                else
                    callback(other, unit);
            }
        }
    }
    Structure.eachUnitPair = eachUnitPair;
    //
    Structure.DefaultSizeThresholds = {
        /** Must be lower to be small */
        smallResidueCount: 10,
        /** Must be lower to be medium */
        mediumResidueCount: 3000,
        /** Must be lower to be large (big ribosomes like 4UG0 should still be `large`) */
        largeResidueCount: 20000,
        /**
         * Structures above `largeResidueCount` are consider huge when they have
         * a `highSymmetryUnitCount` or gigantic when not
         */
        highSymmetryUnitCount: 10,
        /** Fiber-like structure are consider small when below this */
        fiberResidueCount: 15,
    };
    function getPolymerSymmetryGroups(structure) {
        return structure.unitSymmetryGroups.filter(function (ug) { return ug.units[0].polymerElements.length > 0; });
    }
    /**
     * Try to match fiber-like structures like 6nk4
     */
    function isFiberLike(structure, thresholds) {
        var polymerSymmetryGroups = getPolymerSymmetryGroups(structure);
        return (polymerSymmetryGroups.length === 1 &&
            polymerSymmetryGroups[0].units.length > 2 &&
            polymerSymmetryGroups[0].units[0].polymerElements.length < thresholds.fiberResidueCount);
    }
    function hasHighSymmetry(structure, thresholds) {
        var polymerSymmetryGroups = getPolymerSymmetryGroups(structure);
        return (polymerSymmetryGroups.length >= 1 &&
            polymerSymmetryGroups[0].units.length > thresholds.highSymmetryUnitCount);
    }
    var Size;
    (function (Size) {
        Size[Size["Small"] = 0] = "Small";
        Size[Size["Medium"] = 1] = "Medium";
        Size[Size["Large"] = 2] = "Large";
        Size[Size["Huge"] = 3] = "Huge";
        Size[Size["Gigantic"] = 4] = "Gigantic";
    })(Size = Structure.Size || (Structure.Size = {}));
    /**
     * @param residueCountFactor - modifies the threshold counts, useful when estimating
     *                             the size of a structure comprised of multiple models
     */
    function getSize(structure, thresholds, residueCountFactor) {
        if (thresholds === void 0) { thresholds = {}; }
        if (residueCountFactor === void 0) { residueCountFactor = 1; }
        var t = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, Structure.DefaultSizeThresholds), thresholds);
        if (structure.polymerResidueCount >= t.largeResidueCount * residueCountFactor) {
            if (hasHighSymmetry(structure, t)) {
                return Size.Huge;
            }
            else {
                return Size.Gigantic;
            }
        }
        else if (isFiberLike(structure, t)) {
            return Size.Small;
        }
        else if (structure.polymerResidueCount < t.smallResidueCount * residueCountFactor) {
            return Size.Small;
        }
        else if (structure.polymerResidueCount < t.mediumResidueCount * residueCountFactor) {
            return Size.Medium;
        }
        else {
            return Size.Large;
        }
    }
    Structure.getSize = getSize;
    Structure.Index = custom_structure_property["a" /* CustomStructureProperty */].createSimple('index', 'root');
})(structure_Structure || (structure_Structure = {}));
/* harmony default export */ var structure_structure = __webpack_exports__["a"] = (structure_Structure);
//# sourceMappingURL=structure.js.map

/***/ }),
/* 113 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ symmetry_ModelSymmetry; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema/mmcif.js
var mmcif = __webpack_require__(57);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/symmetry-operator.js
var symmetry_operator = __webpack_require__(136);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/symmetry.js
var properties_symmetry = __webpack_require__(291);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var structure = __webpack_require__(4);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/assembly.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function createAssemblies(pdbx_struct_assembly, pdbx_struct_assembly_gen, pdbx_struct_oper_list) {
    if (!pdbx_struct_assembly._rowCount)
        return [];
    var matrices = getMatrices(pdbx_struct_oper_list);
    var assemblies = [];
    for (var i = 0; i < pdbx_struct_assembly._rowCount; i++) {
        assemblies[assemblies.length] = createAssembly(pdbx_struct_assembly, pdbx_struct_assembly_gen, i, matrices);
    }
    return assemblies;
}
function createAssembly(pdbx_struct_assembly, pdbx_struct_assembly_gen, index, matrices) {
    var id = pdbx_struct_assembly.id.value(index);
    var details = pdbx_struct_assembly.details.value(index);
    var generators = [];
    var assembly_id = pdbx_struct_assembly_gen.assembly_id, oper_expression = pdbx_struct_assembly_gen.oper_expression, asym_id_list = pdbx_struct_assembly_gen.asym_id_list;
    for (var i = 0, _i = pdbx_struct_assembly_gen._rowCount; i < _i; i++) {
        if (assembly_id.value(i) !== id)
            continue;
        generators[generators.length] = {
            assemblyId: id,
            expression: oper_expression.value(i),
            asymIds: asym_id_list.value(i)
        };
    }
    return properties_symmetry["a" /* Assembly */].create(id, details, operatorGroupsProvider(generators, matrices));
}
function operatorGroupsProvider(generators, matrices) {
    return function () {
        var groups = [];
        var operatorOffset = 0;
        for (var i = 0; i < generators.length; i++) {
            var gen = generators[i];
            var operatorList = parseOperatorList(gen.expression);
            var operatorNames = expandOperators(operatorList);
            var operators = getAssemblyOperators(matrices, operatorNames, operatorOffset, gen.assemblyId);
            var selector = structure["Queries"].generators.atoms({ chainTest: structure["Queries"].pred.and(structure["Queries"].pred.eq(function (ctx) { return structure["StructureProperties"].unit.operator_name(ctx.element); }, symmetry_operator["a" /* SymmetryOperator */].DefaultName), structure["Queries"].pred.inSet(function (ctx) { return structure["StructureProperties"].chain.label_asym_id(ctx.element); }, gen.asymIds)) });
            groups[groups.length] = { selector: selector, operators: operators };
            operatorOffset += operators.length;
        }
        return groups;
    };
}
function getMatrices(pdbx_struct_oper_list) {
    var id = pdbx_struct_oper_list.id, matrix = pdbx_struct_oper_list.matrix, vector = pdbx_struct_oper_list.vector, _schema = pdbx_struct_oper_list._schema;
    var matrices = new Map();
    for (var i = 0, _i = pdbx_struct_oper_list._rowCount; i < _i; i++) {
        var m = linear_algebra["Tensor"].toMat4(Object(linear_algebra["Mat4"])(), _schema.matrix.space, matrix.value(i));
        var t = linear_algebra["Tensor"].toVec3(Object(linear_algebra["Vec3"])(), _schema.vector.space, vector.value(i));
        linear_algebra["Mat4"].setTranslation(m, t);
        linear_algebra["Mat4"].setValue(m, 3, 3, 1);
        matrices.set(id.value(i), m);
    }
    return matrices;
}
function expandOperators(operatorList) {
    var ops = [];
    var currentOp = [];
    for (var i = 0; i < operatorList.length; i++)
        currentOp[i] = '';
    expandOperators1(operatorList, ops, operatorList.length - 1, currentOp);
    return ops;
}
function expandOperators1(operatorNames, list, i, current) {
    if (i < 0) {
        list[list.length] = current.slice(0);
        return;
    }
    var ops = operatorNames[i], len = ops.length;
    for (var j = 0; j < len; j++) {
        current[i] = ops[j];
        expandOperators1(operatorNames, list, i - 1, current);
    }
}
function getAssemblyOperators(matrices, operatorNames, startIndex, assemblyId) {
    var operators = [];
    var index = startIndex;
    for (var _a = 0, operatorNames_1 = operatorNames; _a < operatorNames_1.length; _a++) {
        var op = operatorNames_1[_a];
        var m = linear_algebra["Mat4"].identity();
        for (var i = 0; i < op.length; i++) {
            linear_algebra["Mat4"].mul(m, m, matrices.get(op[i]));
        }
        index++;
        operators[operators.length] = symmetry_operator["a" /* SymmetryOperator */].create("ASM_" + index, m, { assembly: { id: assemblyId, operId: index, operList: op } });
    }
    return operators;
}
function parseOperatorList(value) {
    // '(X0)(1-5)' becomes [['X0'], ['1', '2', '3', '4', '5']]
    // kudos to Glen van Ginkel.
    var oeRegex = /\(?([^\(\)]+)\)?]*/g, groups = [], ret = [];
    var g;
    while (g = oeRegex.exec(value))
        groups[groups.length] = g[1];
    groups.forEach(function (g) {
        var group = [];
        g.split(',').forEach(function (e) {
            var dashIndex = e.indexOf('-');
            if (dashIndex > 0) {
                var from = parseInt(e.substring(0, dashIndex)), to = parseInt(e.substr(dashIndex + 1));
                for (var i = from; i <= to; i++)
                    group[group.length] = i.toString();
            }
            else {
                group[group.length] = e.trim();
            }
        });
        ret[ret.length] = group;
    });
    return ret;
}
//# sourceMappingURL=assembly.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/common/property.js
var property = __webpack_require__(188);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var symmetry_ModelSymmetry;
(function (ModelSymmetry) {
    ModelSymmetry.Descriptor = {
        name: 'model_symmetry',
    };
    ModelSymmetry.Provider = property["a" /* FormatPropertyProvider */].create(ModelSymmetry.Descriptor);
    function fromData(data) {
        var assemblies = createAssemblies(data.pdbx_struct_assembly, data.pdbx_struct_assembly_gen, data.pdbx_struct_oper_list);
        var spacegroup = getSpacegroup(data.symmetry, data.cell);
        var isNonStandardCrystalFrame = checkNonStandardCrystalFrame(data.atom_sites, spacegroup);
        return { assemblies: assemblies, spacegroup: spacegroup, isNonStandardCrystalFrame: isNonStandardCrystalFrame, ncsOperators: getNcsOperators(data.struct_ncs_oper) };
    }
    ModelSymmetry.fromData = fromData;
})(symmetry_ModelSymmetry || (symmetry_ModelSymmetry = {}));
function checkNonStandardCrystalFrame(atom_sites, spacegroup) {
    if (atom_sites._rowCount === 0)
        return false;
    // TODO: parse atom_sites transform and check if it corresponds to the toFractional matrix
    return false;
}
function getSpacegroupNameOrNumber(symmetry) {
    var groupNumber = symmetry['Int_Tables_number'].value(0);
    var groupName = symmetry['space_group_name_H-M'].value(0);
    if (!symmetry['Int_Tables_number'].isDefined)
        return groupName;
    if (!symmetry['space_group_name_H-M'].isDefined)
        return groupNumber;
    return groupName;
}
function getSpacegroup(symmetry, cell) {
    if (symmetry._rowCount === 0 || cell._rowCount === 0)
        return geometry["e" /* Spacegroup */].ZeroP1;
    var nameOrNumber = getSpacegroupNameOrNumber(symmetry);
    var spaceCell = geometry["f" /* SpacegroupCell */].create(nameOrNumber, linear_algebra["Vec3"].create(cell.length_a.value(0), cell.length_b.value(0), cell.length_c.value(0)), linear_algebra["Vec3"].scale(linear_algebra["Vec3"].zero(), linear_algebra["Vec3"].create(cell.angle_alpha.value(0), cell.angle_beta.value(0), cell.angle_gamma.value(0)), Math.PI / 180));
    return geometry["e" /* Spacegroup */].create(spaceCell);
}
function getNcsOperators(struct_ncs_oper) {
    if (struct_ncs_oper._rowCount === 0)
        return void 0;
    var id = struct_ncs_oper.id, matrix = struct_ncs_oper.matrix, vector = struct_ncs_oper.vector;
    var matrixSpace = mmcif["a" /* mmCIF_Schema */].struct_ncs_oper.matrix.space, vectorSpace = mmcif["a" /* mmCIF_Schema */].struct_ncs_oper.vector.space;
    var opers = [];
    for (var i = 0; i < struct_ncs_oper._rowCount; i++) {
        var m = linear_algebra["Tensor"].toMat3(Object(linear_algebra["Mat3"])(), matrixSpace, matrix.value(i));
        var v = linear_algebra["Tensor"].toVec3(Object(linear_algebra["Vec3"])(), vectorSpace, vector.value(i));
        if (!geometry["h" /* SymmetryOperator */].checkIfRotationAndTranslation(m, v))
            continue;
        // ignore non-identity 'given' NCS operators
        if (struct_ncs_oper.code.value(i) === 'given' && !linear_algebra["Mat3"].isIdentity(m) && !linear_algebra["Vec3"].isZero(v))
            continue;
        var ncsId = id.value(i);
        opers[opers.length] = geometry["h" /* SymmetryOperator */].ofRotationAndOffset("ncs_" + ncsId, m, v, ncsId);
    }
    return opers;
}
//# sourceMappingURL=symmetry.js.map

/***/ }),
/* 114 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "AssetManager", function() { return AssetManager; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Asset", function() { return Asset; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _uuid__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(194);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _data_source__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(177);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(16);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var Asset;
(function (Asset) {
    function Url(url, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ kind: 'url', id: _uuid__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create22(), url: url }, options);
    }
    Asset.Url = Url;
    function File(file) {
        return { kind: 'file', id: _uuid__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create22(), name: file.name, file: file };
    }
    Asset.File = File;
    function isUrl(x) {
        return (x === null || x === void 0 ? void 0 : x.kind) === 'url';
    }
    Asset.isUrl = isUrl;
    function isFile(x) {
        return (x === null || x === void 0 ? void 0 : x.kind) === 'file';
    }
    Asset.isFile = isFile;
    function Wrapper(data, asset, manager) {
        return {
            data: data,
            dispose: function () {
                manager.release(asset);
            }
        };
    }
    Asset.Wrapper = Wrapper;
    function getUrl(url) {
        return typeof url === 'string' ? url : url.url;
    }
    Asset.getUrl = getUrl;
    function getUrlAsset(manager, url, body) {
        if (typeof url === 'string') {
            var asset = manager.tryFindUrl(url, body);
            return asset || Url(url, { body: body });
        }
        return url;
    }
    Asset.getUrlAsset = getUrlAsset;
})(Asset || (Asset = {}));
var AssetManager = /** @class */ (function () {
    function AssetManager() {
        // TODO: add URL based ref-counted cache?
        // TODO: when serializing, check for duplicates?
        this._assets = new Map();
    }
    Object.defineProperty(AssetManager.prototype, "assets", {
        get: function () {
            return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* iterableToArray */ "n"])(this._assets.values());
        },
        enumerable: false,
        configurable: true
    });
    AssetManager.prototype.tryFindUrl = function (url, body) {
        var assets = this.assets.values();
        while (true) {
            var v = assets.next();
            if (v.done)
                return;
            var asset = v.value.asset;
            if (Asset.isUrl(asset) && asset.url === url && (asset.body || '') === (body || ''))
                return asset;
        }
    };
    AssetManager.prototype.set = function (asset, file) {
        this._assets.set(asset.id, { asset: asset, file: file, refCount: 0 });
    };
    AssetManager.prototype.resolve = function (asset, type, store) {
        var _this = this;
        if (store === void 0) { store = true; }
        if (Asset.isUrl(asset)) {
            return _mol_task__WEBPACK_IMPORTED_MODULE_4__[/* Task */ "b"].create("Download " + (asset.title || asset.url), function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                var entry, _a, _b, _c, _d, data, file, _e, _f;
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                    switch (_g.label) {
                        case 0:
                            if (!this._assets.has(asset.id)) return [3 /*break*/, 2];
                            entry = this._assets.get(asset.id);
                            entry.refCount++;
                            _b = (_a = Asset).Wrapper;
                            return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* readFromFile */ "c"])(entry.file, type).runInContext(ctx)];
                        case 1: return [2 /*return*/, _b.apply(_a, [_g.sent(), asset, this])];
                        case 2:
                            if (!!store) return [3 /*break*/, 4];
                            _d = (_c = Asset).Wrapper;
                            return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* ajaxGet */ "a"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, asset), { type: type })).runInContext(ctx)];
                        case 3: return [2 /*return*/, _d.apply(_c, [_g.sent(), asset, this])];
                        case 4: return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* ajaxGet */ "a"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, asset), { type: 'binary' })).runInContext(ctx)];
                        case 5:
                            data = _g.sent();
                            file = new File([data], 'raw-data');
                            this._assets.set(asset.id, { asset: asset, file: file, refCount: 1 });
                            _f = (_e = Asset).Wrapper;
                            return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* readFromFile */ "c"])(file, type).runInContext(ctx)];
                        case 6: return [2 /*return*/, _f.apply(_e, [_g.sent(), asset, this])];
                    }
                });
            }); });
        }
        else {
            return _mol_task__WEBPACK_IMPORTED_MODULE_4__[/* Task */ "b"].create("Read " + asset.name, function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                var entry, _a, _b, _c, _d;
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_e) {
                    switch (_e.label) {
                        case 0:
                            if (!this._assets.has(asset.id)) return [3 /*break*/, 2];
                            entry = this._assets.get(asset.id);
                            entry.refCount++;
                            _b = (_a = Asset).Wrapper;
                            return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* readFromFile */ "c"])(entry.file, type).runInContext(ctx)];
                        case 1: return [2 /*return*/, _b.apply(_a, [_e.sent(), asset, this])];
                        case 2:
                            if (!(asset.file instanceof File)) {
                                throw new Error("Cannot resolve file asset '" + asset.name + "' (" + asset.id + ")");
                            }
                            if (store) {
                                this._assets.set(asset.id, { asset: asset, file: asset.file, refCount: 1 });
                            }
                            _d = (_c = Asset).Wrapper;
                            return [4 /*yield*/, Object(_data_source__WEBPACK_IMPORTED_MODULE_3__[/* readFromFile */ "c"])(asset.file, type).runInContext(ctx)];
                        case 3: return [2 /*return*/, _d.apply(_c, [_e.sent(), asset, this])];
                    }
                });
            }); });
        }
    };
    AssetManager.prototype.release = function (asset) {
        var entry = this._assets.get(asset.id);
        if (!entry)
            return;
        entry.refCount--;
        if (entry.refCount <= 0)
            this._assets.delete(asset.id);
    };
    return AssetManager;
}());
//# sourceMappingURL=assets.js.map

/***/ }),
/* 115 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ getNextMaterialId; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ createRenderObject; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ createRenderable; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/id-factory.js
var id_factory = __webpack_require__(96);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable.js
var renderable = __webpack_require__(98);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-item.js
var render_item = __webpack_require__(99);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/schema.js
var renderable_schema = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/direct-volume.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var DirectVolumeSchema = {
    uColor: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    uColorTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    tColor: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'rgb', 'ubyte', 'nearest'),
    dColorType: Object(renderable_schema["c" /* DefineSpec */])('string', ['uniform', 'instance', 'group', 'group_instance']),
    uMarkerTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    tMarker: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'nearest'),
    uOverpaintTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    tOverpaint: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'rgba', 'ubyte', 'nearest'),
    dOverpaint: Object(renderable_schema["c" /* DefineSpec */])('boolean'),
    uTransparencyTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    tTransparency: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'nearest'),
    dTransparency: Object(renderable_schema["c" /* DefineSpec */])('boolean'),
    dTransparencyVariant: Object(renderable_schema["c" /* DefineSpec */])('string', ['single', 'multi']),
    dClipObjectCount: Object(renderable_schema["c" /* DefineSpec */])('number'),
    dClipVariant: Object(renderable_schema["c" /* DefineSpec */])('string', ['instance', 'pixel']),
    uClippingTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    tClipping: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'nearest'),
    dClipping: Object(renderable_schema["c" /* DefineSpec */])('boolean'),
    uInstanceCount: Object(renderable_schema["i" /* UniformSpec */])('i'),
    uGroupCount: Object(renderable_schema["i" /* UniformSpec */])('i'),
    uInvariantBoundingSphere: Object(renderable_schema["i" /* UniformSpec */])('v4'),
    aInstance: Object(renderable_schema["a" /* AttributeSpec */])('float32', 1, 1),
    aTransform: Object(renderable_schema["a" /* AttributeSpec */])('float32', 16, 1),
    drawCount: Object(renderable_schema["j" /* ValueSpec */])('number'),
    instanceCount: Object(renderable_schema["j" /* ValueSpec */])('number'),
    alpha: Object(renderable_schema["j" /* ValueSpec */])('number'),
    matrix: Object(renderable_schema["j" /* ValueSpec */])('m4'),
    transform: Object(renderable_schema["j" /* ValueSpec */])('float32'),
    extraTransform: Object(renderable_schema["j" /* ValueSpec */])('float32'),
    boundingSphere: Object(renderable_schema["j" /* ValueSpec */])('sphere'),
    invariantBoundingSphere: Object(renderable_schema["j" /* ValueSpec */])('sphere'),
    aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0),
    elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'),
    uAlpha: Object(renderable_schema["i" /* UniformSpec */])('f'),
    uIsoValue: Object(renderable_schema["i" /* UniformSpec */])('f'),
    uBboxMin: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    uBboxMax: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    uBboxSize: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    dMaxSteps: Object(renderable_schema["c" /* DefineSpec */])('number'),
    uTransform: Object(renderable_schema["i" /* UniformSpec */])('m4'),
    uGridDim: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    dRenderMode: Object(renderable_schema["c" /* DefineSpec */])('string', ['isosurface', 'volume']),
    tTransferTex: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'rgba', 'ubyte', 'linear'),
    dGridTexType: Object(renderable_schema["c" /* DefineSpec */])('string', ['2d', '3d']),
    uGridTexDim: Object(renderable_schema["i" /* UniformSpec */])('v3'),
    tGridTex: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'),
};
function DirectVolumeRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), DirectVolumeSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["a" /* DirectVolumeShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=direct-volume.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/mesh.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var MeshSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), { aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), aNormal: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'), dFlatShaded: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dDoubleSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dFlipSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dIgnoreLight: Object(renderable_schema["c" /* DefineSpec */])('boolean') });
function MeshRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), MeshSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["d" /* MeshShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/points.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var PointsSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), renderable_schema["g" /* SizeSchema */]), { aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), dPointSizeAttenuation: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dPointFilledCircle: Object(renderable_schema["c" /* DefineSpec */])('boolean'), uPointEdgeBleach: Object(renderable_schema["i" /* UniformSpec */])('f') });
function PointsRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), PointsSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["e" /* PointsShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'points', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=points.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/lines.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var LinesSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), renderable_schema["g" /* SizeSchema */]), { aMapping: Object(renderable_schema["a" /* AttributeSpec */])('float32', 2, 0), aStart: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), aEnd: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'), dLineSizeAttenuation: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dDoubleSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dFlipSided: Object(renderable_schema["c" /* DefineSpec */])('boolean') });
function LinesRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), LinesSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["c" /* LinesShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=lines.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/spheres.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var SpheresSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), renderable_schema["g" /* SizeSchema */]), { aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), aMapping: Object(renderable_schema["a" /* AttributeSpec */])('float32', 2, 0), elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'), padding: Object(renderable_schema["j" /* ValueSpec */])('number'), dDoubleSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dIgnoreLight: Object(renderable_schema["c" /* DefineSpec */])('boolean') });
function SpheresRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), SpheresSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["g" /* SpheresShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=spheres.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/text.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var TextSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), renderable_schema["g" /* SizeSchema */]), { aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), aMapping: Object(renderable_schema["a" /* AttributeSpec */])('float32', 2, 0), aDepth: Object(renderable_schema["a" /* AttributeSpec */])('float32', 1, 0), elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'), aTexCoord: Object(renderable_schema["a" /* AttributeSpec */])('float32', 2, 0), tFont: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'linear'), padding: Object(renderable_schema["j" /* ValueSpec */])('number'), uBorderWidth: Object(renderable_schema["i" /* UniformSpec */])('f'), uBorderColor: Object(renderable_schema["i" /* UniformSpec */])('v3'), uOffsetX: Object(renderable_schema["i" /* UniformSpec */])('f'), uOffsetY: Object(renderable_schema["i" /* UniformSpec */])('f'), uOffsetZ: Object(renderable_schema["i" /* UniformSpec */])('f'), uBackgroundColor: Object(renderable_schema["i" /* UniformSpec */])('v3'), uBackgroundOpacity: Object(renderable_schema["i" /* UniformSpec */])('f') });
function TextRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), TextSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["h" /* TextShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=text.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/texture-mesh.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var TextureMeshSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), { uGeoTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'),
    /** texture has vertex positions in XYZ and group id in W */
    tPositionGroup: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'), tNormal: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'), dFlatShaded: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dDoubleSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dFlipSided: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dGeoTexture: Object(renderable_schema["c" /* DefineSpec */])('boolean') });
function TextureMeshRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), TextureMeshSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["d" /* MeshShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=texture-mesh.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/image/image.js
var image_image = __webpack_require__(218);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/renderable/image.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var ImageSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["b" /* BaseSchema */]), { aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0), aUv: Object(renderable_schema["a" /* AttributeSpec */])('float32', 2, 0), elements: Object(renderable_schema["d" /* ElementsSpec */])('uint32'), uImageTexDim: Object(renderable_schema["i" /* UniformSpec */])('v2'), tImageTex: Object(renderable_schema["h" /* TextureSpec */])('image-float32', 'rgba', 'float', 'nearest'), tGroupTex: Object(renderable_schema["h" /* TextureSpec */])('image-float32', 'alpha', 'float', 'nearest'), dInterpolation: Object(renderable_schema["c" /* DefineSpec */])('string', image_image["b" /* InterpolationTypeNames */]) });
function ImageRenderable(ctx, id, values, state, materialId) {
    var schema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderable_schema["e" /* GlobalUniformSchema */]), renderable_schema["f" /* InternalSchema */]), ImageSchema);
    var internalValues = {
        uObjectId: mol_util["e" /* ValueCell */].create(id),
    };
    var shaderCode = shader_code["b" /* ImageShaderCode */];
    var renderItem = Object(render_item["b" /* createGraphicsRenderItem */])(ctx, 'triangles', shaderCode, schema, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, values), internalValues), materialId);
    return Object(renderable["b" /* createRenderable */])(renderItem, values, state);
}
//# sourceMappingURL=image.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/render-object.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var getNextId = Object(id_factory["a" /* idFactory */])(0, 0x7FFFFFFF);
var getNextMaterialId = Object(id_factory["a" /* idFactory */])(0, 0x7FFFFFFF);
//
function createRenderObject(type, values, state, materialId) {
    return { id: getNextId(), type: type, values: values, state: state, materialId: materialId };
}
function createRenderable(ctx, o) {
    switch (o.type) {
        case 'mesh': return MeshRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'points': return PointsRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'spheres': return SpheresRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'text': return TextRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'lines': return LinesRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'direct-volume': return DirectVolumeRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'image': return ImageRenderable(ctx, o.id, o.values, o.state, o.materialId);
        case 'texture-mesh': return TextureMeshRenderable(ctx, o.id, o.values, o.state, o.materialId);
    }
    throw new Error('unsupported type');
}
//# sourceMappingURL=render-object.js.map

/***/ }),
/* 116 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return map; });
/* unused harmony export MapOperator */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function map(project, thisArg) {
    return function mapOperation(source) {
        if (typeof project !== 'function') {
            throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');
        }
        return source.lift(new MapOperator(project, thisArg));
    };
}
var MapOperator = /*@__PURE__*/ (function () {
    function MapOperator(project, thisArg) {
        this.project = project;
        this.thisArg = thisArg;
    }
    MapOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));
    };
    return MapOperator;
}());

var MapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](MapSubscriber, _super);
    function MapSubscriber(destination, project, thisArg) {
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.count = 0;
        _this.thisArg = thisArg || _this;
        return _this;
    }
    MapSubscriber.prototype._next = function (value) {
        var result;
        try {
            result = this.project.call(this.thisArg, value, this.count++);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(result);
    };
    return MapSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
//# sourceMappingURL=map.js.map


/***/ }),
/* 117 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createColors; });
/* unused harmony export createValueColor */
/* unused harmony export createUniformColor */
/* unused harmony export createTextureColor */
/* unused harmony export createInstanceColor */
/* unused harmony export createGroupColor */
/* unused harmony export createGroupInstanceColor */
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(53);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _mol_model_location__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(144);
/* harmony import */ var _geometry__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(145);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






function createColors(locationIt, colorTheme, colorData) {
    switch (_geometry__WEBPACK_IMPORTED_MODULE_5__[/* Geometry */ "a"].getGranularity(locationIt, colorTheme.granularity)) {
        case 'uniform': return createUniformColor(locationIt, colorTheme.color, colorData);
        case 'group': return createGroupColor(locationIt, colorTheme.color, colorData);
        case 'groupInstance': return createGroupInstanceColor(locationIt, colorTheme.color, colorData);
        case 'instance': return createInstanceColor(locationIt, colorTheme.color, colorData);
    }
}
function createValueColor(value, colorData) {
    if (colorData) {
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(colorData.uColor, _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(colorData.uColor.ref.value, value));
        if (colorData.dColorType.ref.value !== 'uniform') {
            _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(colorData.dColorType, 'uniform');
        }
        return colorData;
    }
    else {
        return {
            uColor: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])(), value)),
            tColor: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create({ array: new Uint8Array(3), width: 1, height: 1 }),
            uColorTexDim: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec2"].create(1, 1)),
            dColorType: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create('uniform'),
        };
    }
}
/** Creates color uniform */
function createUniformColor(locationIt, color, colorData) {
    return createValueColor(color(_mol_model_location__WEBPACK_IMPORTED_MODULE_4__[/* NullLocation */ "b"], false), colorData);
}
function createTextureColor(colors, type, colorData) {
    if (colorData) {
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(colorData.tColor, colors);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(colorData.uColorTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec2"].create(colors.width, colors.height));
        if (colorData.dColorType.ref.value !== type) {
            _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(colorData.dColorType, type);
        }
        return colorData;
    }
    else {
        return {
            uColor: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].zero()),
            tColor: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(colors),
            uColorTexDim: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec2"].create(colors.width, colors.height)),
            dColorType: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(type),
        };
    }
}
/** Creates color texture with color for each instance/unit */
function createInstanceColor(locationIt, color, colorData) {
    var instanceCount = locationIt.instanceCount;
    var colors = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_1__[/* createTextureImage */ "c"])(Math.max(1, instanceCount), 3, Uint8Array, colorData && colorData.tColor.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext) {
        var _a = locationIt.move(), location_1 = _a.location, isSecondary = _a.isSecondary, instanceIndex = _a.instanceIndex;
        _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toArray(color(location_1, isSecondary), colors.array, instanceIndex * 3);
        locationIt.skipInstance();
    }
    return createTextureColor(colors, 'instance', colorData);
}
/** Creates color texture with color for each group (i.e. shared across instances/units) */
function createGroupColor(locationIt, color, colorData) {
    var groupCount = locationIt.groupCount;
    var colors = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_1__[/* createTextureImage */ "c"])(Math.max(1, groupCount), 3, Uint8Array, colorData && colorData.tColor.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext && !locationIt.isNextNewInstance) {
        var _a = locationIt.move(), location_2 = _a.location, isSecondary = _a.isSecondary, groupIndex = _a.groupIndex;
        _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toArray(color(location_2, isSecondary), colors.array, groupIndex * 3);
    }
    return createTextureColor(colors, 'group', colorData);
}
/** Creates color texture with color for each group in each instance (i.e. for each unit) */
function createGroupInstanceColor(locationIt, color, colorData) {
    var groupCount = locationIt.groupCount, instanceCount = locationIt.instanceCount;
    var count = instanceCount * groupCount;
    var colors = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_1__[/* createTextureImage */ "c"])(Math.max(1, count), 3, Uint8Array, colorData && colorData.tColor.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext) {
        var _a = locationIt.move(), location_3 = _a.location, isSecondary = _a.isSecondary, index = _a.index;
        _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toArray(color(location_3, isSecondary), colors.array, index * 3);
    }
    return createTextureColor(colors, 'groupInstance', colorData);
}
//# sourceMappingURL=color-data.js.map

/***/ }),
/* 118 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PluginComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StatefulPluginComponent; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_object__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(85);
/* harmony import */ var _mol_util_rx_event_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(180);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(29);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var PluginComponent = /** @class */ (function () {
    function PluginComponent() {
        this.subs = void 0;
    }
    PluginComponent.prototype.subscribe = function (obs, action) {
        var _this = this;
        if (typeof this.subs === 'undefined')
            this.subs = [];
        var sub = obs.subscribe(action);
        this.subs.push(sub);
        return {
            unsubscribe: function () {
                if (sub && _this.subs && Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_3__["arraySetRemove"])(_this.subs, sub)) {
                    sub.unsubscribe();
                    sub = void 0;
                }
            }
        };
    };
    Object.defineProperty(PluginComponent.prototype, "ev", {
        get: function () {
            return this._ev || (this._ev = _mol_util_rx_event_helper__WEBPACK_IMPORTED_MODULE_2__["RxEventHelper"].create());
        },
        enumerable: false,
        configurable: true
    });
    PluginComponent.prototype.dispose = function () {
        if (this._ev)
            this._ev.dispose();
        if (this.subs) {
            for (var _i = 0, _a = this.subs; _i < _a.length; _i++) {
                var s = _a[_i];
                s.unsubscribe();
            }
            this.subs = void 0;
        }
    };
    return PluginComponent;
}());

var StatefulPluginComponent = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StatefulPluginComponent, _super);
    function StatefulPluginComponent(initialState) {
        var _this = _super.call(this) || this;
        _this._state = initialState;
        return _this;
    }
    StatefulPluginComponent.prototype.updateState = function () {
        var states = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            states[_i] = arguments[_i];
        }
        var latest = this.state;
        var s = Object(_mol_util_object__WEBPACK_IMPORTED_MODULE_1__[/* shallowMergeArray */ "e"])(latest, states);
        if (s !== latest) {
            this._state = s;
            return true;
        }
        return false;
    };
    Object.defineProperty(StatefulPluginComponent.prototype, "state", {
        get: function () {
            return this._state;
        },
        enumerable: false,
        configurable: true
    });
    return StatefulPluginComponent;
}(PluginComponent));

//# sourceMappingURL=component.js.map

/***/ }),
/* 119 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(399);
/* harmony import */ var _atomic_conformation__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "AtomNumber")) __webpack_require__.d(__webpack_exports__, "AtomNumber", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["AtomNumber"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "AtomWeight")) __webpack_require__.d(__webpack_exports__, "AtomWeight", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["AtomWeight"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "AtomicHierarchy")) __webpack_require__.d(__webpack_exports__, "AtomicHierarchy", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["AtomicHierarchy"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "AtomicNumbers")) __webpack_require__.d(__webpack_exports__, "AtomicNumbers", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["AtomicNumbers"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "AtomsSchema")) __webpack_require__.d(__webpack_exports__, "AtomsSchema", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["AtomsSchema"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "ChainsSchema")) __webpack_require__.d(__webpack_exports__, "ChainsSchema", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["ChainsSchema"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "ResiduesSchema")) __webpack_require__.d(__webpack_exports__, "ResiduesSchema", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["ResiduesSchema"]; });

/* harmony reexport (checked) */ if(__webpack_require__.o(_atomic_conformation__WEBPACK_IMPORTED_MODULE_0__, "VdwRadius")) __webpack_require__.d(__webpack_exports__, "VdwRadius", function() { return _atomic_conformation__WEBPACK_IMPORTED_MODULE_0__["VdwRadius"]; });

/* harmony import */ var _atomic_hierarchy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(304);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AtomicHierarchy", function() { return _atomic_hierarchy__WEBPACK_IMPORTED_MODULE_1__["a"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AtomsSchema", function() { return _atomic_hierarchy__WEBPACK_IMPORTED_MODULE_1__["c"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ChainsSchema", function() { return _atomic_hierarchy__WEBPACK_IMPORTED_MODULE_1__["d"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "ResiduesSchema", function() { return _atomic_hierarchy__WEBPACK_IMPORTED_MODULE_1__["e"]; });

/* harmony import */ var _atomic_measures__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(305);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AtomNumber", function() { return _atomic_measures__WEBPACK_IMPORTED_MODULE_2__["a"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AtomWeight", function() { return _atomic_measures__WEBPACK_IMPORTED_MODULE_2__["b"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "AtomicNumbers", function() { return _atomic_measures__WEBPACK_IMPORTED_MODULE_2__["c"]; });

/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "VdwRadius", function() { return _atomic_measures__WEBPACK_IMPORTED_MODULE_2__["d"]; });

/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



//# sourceMappingURL=atomic.js.map

/***/ }),
/* 120 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Script", function() { return /* binding */ script_Script; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/expression.js
var language_expression = __webpack_require__(132);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol.js
var language_symbol = __webpack_require__(18);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table.js + 1 modules
var symbol_table = __webpack_require__(12);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/type.js
var type = __webpack_require__(15);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table/structure-query.js
var structure_query = __webpack_require__(219);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/builder.js
var builder = __webpack_require__(10);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/script/mol-script/macro.js
/**
 * Copyright (c) 2018-2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function getPositionalArgs(args) {
    return Object.keys(args)
        .filter(function (k) { return !isNaN(k); })
        .map(function (k) { return +k; })
        .sort(function (a, b) { return a - b; })
        .map(function (k) { return args[k]; });
}
function tryGetArg(args, name, defaultValue) {
    return (args && args[name] !== void 0) ? args[name] : defaultValue;
}
function pickArgs(args) {
    var names = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        names[_i - 1] = arguments[_i];
    }
    var ret = Object.create(null);
    var count = 0;
    for (var _a = 0, _b = Object.keys(args); _a < _b.length; _a++) {
        var k = _b[_a];
        if (names.indexOf(k) >= 0) {
            ret[k] = args[k];
            count++;
        }
    }
    return count ? ret : void 0;
}
function aggregate(property, fn, initial) {
    return builder["MolScriptBuilder"].struct.atomSet.reduce({
        initial: initial !== void 0 ? initial : property,
        value: fn([builder["MolScriptBuilder"].struct.slot.elementSetReduce(), property])
    });
}
//# sourceMappingURL=macro.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/script/mol-script/symbols.js
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */









function Alias(symbol) {
    var aliases = [];
    for (var _a = 1; _a < arguments.length; _a++) {
        aliases[_a - 1] = arguments[_a];
    }
    return { kind: 'alias', aliases: aliases, symbol: symbol };
}
function Macro(symbol, translate) {
    var aliases = [];
    for (var _a = 2; _a < arguments.length; _a++) {
        aliases[_a - 2] = arguments[_a];
    }
    symbol.info.namespace = 'molscript-macro';
    symbol.id = "molscript-macro." + symbol.info.name;
    return { kind: 'macro', symbol: symbol, translate: translate, aliases: Object(tslib_es6["__spreadArrays"])([symbol.info.name], aliases) };
}
function isMolScriptSymbol(x) {
    return x.kind === 'alias' || x.kind === 'macro';
}
var SymbolTable = [
    [
        'Core symbols',
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.bool, 'bool'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.num, 'num'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.str, 'str'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.regex, 'regex'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.list, 'list'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.set, 'set'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.type.compositeKey, 'composite-key'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.logic.not, 'not'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.logic.and, 'and'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.logic.or, 'or'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.ctrl.if, 'if'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.ctrl.fn, 'fn'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.ctrl.eval, 'eval'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.add, 'add', '+'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.sub, 'sub', '-'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.mult, 'mult', '*'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.div, 'div', '/'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.pow, 'pow', '**'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.mod, 'mod'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.min, 'min'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.max, 'max'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.floor, 'floor'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.ceil, 'ceil'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.roundInt, 'round'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.abs, 'abs'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.sqrt, 'sqrt'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.cbrt, 'cbrt'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.sin, 'sin'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.cos, 'cos'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.tan, 'tan'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.asin, 'asin'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.acos, 'acos'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.atan, 'atan'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.sinh, 'sinh'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.cosh, 'cosh'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.tanh, 'tanh'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.exp, 'exp'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.log, 'log'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.log10, 'log10'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.math.atan2, 'atan2'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.eq, 'eq', '='),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.neq, 'neq', '!='),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.lt, 'lt', '<'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.lte, 'lte', '<='),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.gr, 'gr', '>'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.gre, 'gre', '>='),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.rel.inRange, 'in-range'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.str.concat, 'concat'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.str.match, 'regex.match'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.list.getAt, 'list.get'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.set.has, 'set.has'),
        Alias(symbol_table["a" /* MolScriptSymbolTable */].core.set.isSubset, 'set.subset'),
    ],
    [
        'Structure',
        [
            'Types',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.entityType, 'ent-type'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.authResidueId, 'auth-resid'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.labelResidueId, 'label-resid'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.ringFingerprint, 'ringfp'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.bondFlags, 'bond-flags'),
        ],
        [
            'Slots',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.slot.elementSetReduce, 'atom.set.reduce.value'),
        ],
        [
            'Generators',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.atomGroups, 'sel.atom.atom-groups'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.queryInSelection, 'sel.atom.query-in-selection'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.rings, 'sel.atom.rings'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.empty, 'sel.atom.empty'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.all, 'sel.atom.all'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.bondedAtomicPairs, 'sel.atom.bonded-pairs'),
            Macro(Object(language_symbol["d" /* MSymbol */])('sel.atom.atoms', language_symbol["b" /* Arguments */].Dictionary({
                0: Object(language_symbol["a" /* Argument */])(type["a" /* default */].Bool, { isOptional: true, defaultValue: true, description: 'Test applied to each atom.' })
            }), structure_query["a" /* Types */].ElementSelection, 'A selection of singleton atom sets.'), function (args) { return builder["MolScriptBuilder"].struct.generator.atomGroups({ 'atom-test': tryGetArg(args, 0, true) }); }),
            Macro(Object(language_symbol["d" /* MSymbol */])('sel.atom.res', language_symbol["b" /* Arguments */].Dictionary({
                0: Object(language_symbol["a" /* Argument */])(type["a" /* default */].Bool, { isOptional: true, defaultValue: true, description: 'Test applied to the 1st atom of each residue.' })
            }), structure_query["a" /* Types */].ElementSelection, 'A selection of atom sets grouped by residue.'), function (args) { return builder["MolScriptBuilder"].struct.generator.atomGroups({
                'residue-test': tryGetArg(args, 0, true),
                'group-by': builder["MolScriptBuilder"].ammp('residueKey')
            }); }),
            Macro(Object(language_symbol["d" /* MSymbol */])('sel.atom.chains', language_symbol["b" /* Arguments */].Dictionary({
                0: Object(language_symbol["a" /* Argument */])(type["a" /* default */].Bool, { isOptional: true, defaultValue: true, description: 'Test applied to the 1st atom of each chain.' })
            }), structure_query["a" /* Types */].ElementSelection, 'A selection of atom sets grouped by chain.'), function (args) { return builder["MolScriptBuilder"].struct.generator.atomGroups({
                'chain-test': tryGetArg(args, 0, true),
                'group-by': builder["MolScriptBuilder"].ammp('chainKey')
            }); }),
        ],
        [
            'Modifiers',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.queryEach, 'sel.atom.query-each'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.intersectBy, 'sel.atom.intersect-by'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.exceptBy, 'sel.atom.except-by'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.unionBy, 'sel.atom.union-by'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.union, 'sel.atom.union'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.cluster, 'sel.atom.cluster'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.includeSurroundings, 'sel.atom.include-surroundings'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.includeConnected, 'sel.atom.include-connected'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.expandProperty, 'sel.atom.expand-property'),
        ],
        [
            'Filters',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.pick, 'sel.atom.pick'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.first, 'sel.atom.first'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.withSameAtomProperties, 'sel.atom.with-same-atom-properties'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.intersectedBy, 'sel.atom.intersected-by'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.within, 'sel.atom.within'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.isConnectedTo, 'sel.atom.is-connected-to'),
        ],
        [
            'Combinators',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.combinator.intersect, 'sel.atom.intersect'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.combinator.merge, 'sel.atom.merge'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.combinator.distanceCluster, 'sel.atom.dist-cluster'),
        ],
        [
            'Atom Set Properties',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomSet.atomCount, 'atom.set.atom-count'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomSet.countQuery, 'atom.set.count-query'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomSet.reduce, 'atom.set.reduce'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomSet.propertySet, 'atom.set.property'),
        ],
        [
            'Atom Properties',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.elementSymbol, 'atom.el'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.vdw, 'atom.vdw'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.mass, 'atom.mass'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.atomicNumber, 'atom.atomic-number'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.x, 'atom.x'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.y, 'atom.y'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.z, 'atom.z'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.sourceIndex, 'atom.src-index'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.operatorName, 'atom.op-name'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.modelIndex, 'atom.model-index'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.modelLabel, 'atom.model-label'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.atomKey, 'atom.key'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.bondCount, 'atom.bond-count'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.topology.connectedComponentKey, 'atom.key.molecule'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.authResidueId, 'atom.auth-resid'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.labelResidueId, 'atom.label-resid'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.residueKey, 'atom.key.res'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.chainKey, 'atom.key.chain'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityKey, 'atom.key.entity'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.isHet, 'atom.is-het'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.id, 'atom.id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_atom_id, 'atom.label_atom_id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_alt_id, 'atom.label_alt_id', 'atom.altloc'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_comp_id, 'atom.label_comp_id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_asym_id, 'atom.label_asym_id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_entity_id, 'atom.label_entity_id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_seq_id, 'atom.label_seq_id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_atom_id, 'atom.auth_atom_id', 'atom.name'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_comp_id, 'atom.auth_comp_id', 'atom.resname'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_asym_id, 'atom.auth_asym_id', 'atom.chain'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_seq_id, 'atom.auth_seq_id', 'atom.resno'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.pdbx_PDB_ins_code, 'atom.pdbx_PDB_ins_code', 'atom.inscode'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.pdbx_formal_charge, 'atom.pdbx_formal_charge'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.occupancy, 'atom.occupancy'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.B_iso_or_equiv, 'atom.B_iso_or_equiv', 'atom.bfactor'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityType, 'atom.entity-type'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entitySubtype, 'atom.entity-subtype'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityPrdId, 'atom.entity-prd-id'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityDescription, 'atom.entity-description'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.objectPrimitive, 'atom.object-primitive'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.chemCompType, 'atom.chem-comp-type'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.secondaryStructureKey, 'atom.key.sec-struct'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.isModified, 'atom.is-modified'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.modifiedParentName, 'atom.modified-parent'),
        ],
        [
            'Bond Properties',
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.order, 'bond.order'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.length, 'bond.length'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.atomA, 'bond.atom-a'),
            Alias(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.atomB, 'bond.atom-b'),
            Macro(Object(language_symbol["d" /* MSymbol */])('bond.is', language_symbol["b" /* Arguments */].List(structure_query["a" /* Types */].BondFlag), type["a" /* default */].Bool, "Test if the current bond has at least one (or all if partial = false) of the specified flags: " + type["a" /* default */].oneOfValues(structure_query["a" /* Types */].BondFlag).join(', ')), function (args) { return builder["MolScriptBuilder"].core.flags.hasAny([builder["MolScriptBuilder"].struct.bondProperty.flags(), builder["MolScriptBuilder"].struct.type.bondFlags(getPositionalArgs(args))]); }),
        ]
    ]
];
var list = [];
function makeList(xs) {
    for (var _a = 0, xs_1 = xs; _a < xs_1.length; _a++) {
        var x = xs_1[_a];
        if (isMolScriptSymbol(x))
            list.push(x);
        else if (x instanceof Array)
            makeList(x);
    }
}
makeList(SymbolTable);
var normalized = (function () {
    var symbolList = [];
    var symbolMap = Object.create(null);
    var namedArgs = generic["c" /* UniqueArray */].create();
    var constants = generic["c" /* UniqueArray */].create();
    for (var _a = 0, list_1 = list; _a < list_1.length; _a++) {
        var s = list_1[_a];
        for (var _b = 0, _c = s.aliases; _b < _c.length; _b++) {
            var a = _c[_b];
            symbolList.push([a, s]);
            if (symbolMap[a])
                throw new Error("Alias '" + a + "' already in use.");
            symbolMap[a] = s;
        }
        var args = s.symbol.args;
        if (args.kind !== 'dictionary') {
            if (args.type.kind === 'oneof') {
                type["a" /* default */].oneOfValues(args.type).forEach(function (v) { return generic["c" /* UniqueArray */].add(constants, v, v); });
            }
            continue;
        }
        for (var _d = 0, _e = Object.keys(args.map); _d < _e.length; _d++) {
            var a = _e[_d];
            if (isNaN(a))
                generic["c" /* UniqueArray */].add(namedArgs, a, a);
            var arg = (args.map[a]);
            if (arg.type.kind === 'oneof') {
                type["a" /* default */].oneOfValues(arg.type).forEach(function (v) { return generic["c" /* UniqueArray */].add(constants, v, v); });
            }
        }
    }
    return { symbolList: symbolList, symbolMap: symbolMap, namedArgs: namedArgs.array, constants: constants.array };
})();
var MolScriptSymbols = list;
var Constants = normalized.constants;
var NamedArgs = normalized.namedArgs;
var SymbolMap = normalized.symbolMap;
var SymbolList = normalized.symbolList;
function substSymbols(expr) {
    if (language_expression["a" /* default */].isLiteral(expr)) {
        return expr;
    }
    if (language_expression["a" /* default */].isSymbol(expr)) {
        if (!SymbolMap[expr.name])
            return expr;
        var s = SymbolMap[expr.name];
        if (s.kind === 'alias')
            return language_expression["a" /* default */].Symbol(SymbolMap[expr.name].symbol.id);
        throw s.translate([]);
    }
    var isMacro = language_expression["a" /* default */].isSymbol(expr.head) && !!SymbolMap[expr.head.name] && SymbolMap[expr.head.name].kind === 'macro';
    var head = isMacro ? expr.head : substSymbols(expr.head);
    var headChanged = head !== expr.head;
    if (!expr.args) {
        if (isMacro)
            return substSymbols(expr.head); // TODO: is this correct?
        return headChanged ? language_expression["a" /* default */].Apply(head) : expr;
    }
    var argsChanged = false;
    var newArgs;
    if (language_expression["a" /* default */].isArgumentsArray(expr.args)) {
        newArgs = [];
        for (var i = 0, _i = expr.args.length; i < _i; i++) {
            var oldArg = expr.args[i];
            var newArg = substSymbols(oldArg);
            if (oldArg !== newArg)
                argsChanged = true;
            newArgs[newArgs.length] = newArg;
        }
        if (!argsChanged)
            newArgs = expr.args;
        if (!isMacro && !headChanged && !argsChanged)
            return expr;
    }
    else {
        newArgs = {};
        for (var _a = 0, _b = Object.keys(expr.args); _a < _b.length; _a++) {
            var key = _b[_a];
            var oldArg = expr.args[key];
            var newArg = substSymbols(oldArg);
            if (oldArg !== newArg)
                argsChanged = true;
            newArgs[key] = newArg;
        }
        if (!isMacro && !headChanged && !argsChanged)
            return expr;
        if (!argsChanged)
            newArgs = expr.args;
    }
    if (isMacro) {
        var macro = SymbolMap[expr.head.name];
        if (macro.kind !== 'macro')
            return language_expression["a" /* default */].Apply(head, newArgs);
        var ret = macro.translate(newArgs);
        return ret;
    }
    return language_expression["a" /* default */].Apply(head, newArgs);
}
function transpileMolScript(expr) {
    return substSymbols(expr);
}
// const sortedSymbols = SymbolList.map(s => s[0]).sort((a, b) => {
//     if (a.length === b.length) return (a < b) as any;
//     return a.length - b.length;
// });
// export default [...sortedSymbols, ...NamedArgs.map(a => ':' + a), ...Constants];
//# sourceMappingURL=symbols.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/monadic-parser.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

/**
 * Adapted from Parsimmon (https://github.com/jneen/parsimmon)
 * Copyright (c) 2011-present J. Adkisson (http://jneen.net).
 */
var monadic_parser_MonadicParser = /** @class */ (function () {
    function MonadicParser(_) {
        this._ = _;
    }
    MonadicParser.prototype.parse = function (input) {
        var result = this.skip(MonadicParser.eof)._(input, 0);
        if (result.status) {
            return { success: true, value: result.value };
        }
        return { success: false, index: makeLineColumnIndex(input, result.furthest), expected: result.expected };
    };
    ;
    MonadicParser.prototype.tryParse = function (str) {
        var result = this.parse(str);
        if (result.success) {
            return result.value;
        }
        else {
            var msg = formatError(str, result);
            var err = new Error(msg);
            throw err;
        }
    };
    MonadicParser.prototype.or = function (alternative) {
        return MonadicParser.alt(this, alternative);
    };
    MonadicParser.prototype.trim = function (parser) {
        return this.wrap(parser, parser);
    };
    MonadicParser.prototype.wrap = function (leftParser, rightParser) {
        return seqPick(1, typeof leftParser === 'string' ? MonadicParser.string(leftParser) : leftParser, this, typeof rightParser === 'string' ? MonadicParser.string(rightParser) : rightParser);
    };
    MonadicParser.prototype.thru = function (wrapper) {
        return wrapper(this);
    };
    MonadicParser.prototype.then = function (next) {
        return seqPick(1, this, next);
    };
    MonadicParser.prototype.many = function () {
        var _this = this;
        return new MonadicParser(function (input, i) {
            var accum = [];
            var result = void 0;
            while (true) {
                result = mergeReplies(_this._(input, i), result);
                if (result.status) {
                    if (i === result.index) {
                        throw new Error('infinite loop detected in .many() parser --- calling .many() on a parser which can accept zero characters is usually the cause');
                    }
                    i = result.index;
                    accum.push(result.value);
                }
                else {
                    return mergeReplies(makeSuccess(i, accum), result);
                }
            }
        });
    };
    ;
    MonadicParser.prototype.times = function (min, _max) {
        var _this = this;
        var max = typeof _max === 'undefined' ? min : _max;
        return new MonadicParser(function (input, i) {
            var accum = [];
            var result = void 0;
            var prevResult = void 0;
            var times;
            for (times = 0; times < min; times++) {
                result = _this._(input, i);
                prevResult = mergeReplies(result, prevResult);
                if (result.status) {
                    i = result.index;
                    accum.push(result.value);
                }
                else {
                    return prevResult;
                }
            }
            for (; times < max; times += 1) {
                result = _this._(input, i);
                prevResult = mergeReplies(result, prevResult);
                if (result.status) {
                    i = result.index;
                    accum.push(result.value);
                }
                else {
                    break;
                }
            }
            return mergeReplies(makeSuccess(i, accum), prevResult);
        });
    };
    ;
    MonadicParser.prototype.result = function (res) {
        return this.map(function () { return res; });
    };
    ;
    MonadicParser.prototype.atMost = function (n) {
        return this.times(0, n);
    };
    ;
    MonadicParser.prototype.atLeast = function (n) {
        return MonadicParser.seq(this.times(n), this.many()).map(function (r) { return Object(tslib_es6["__spreadArrays"])(r[0], r[1]); });
    };
    ;
    MonadicParser.prototype.map = function (f) {
        var _this = this;
        return new MonadicParser(function (input, i) {
            var result = _this._(input, i);
            if (!result.status) {
                return result;
            }
            return mergeReplies(makeSuccess(result.index, f(result.value)), result);
        });
    };
    MonadicParser.prototype.skip = function (next) {
        return seqPick(0, this, next);
    };
    MonadicParser.prototype.mark = function () {
        return MonadicParser.seq(MonadicParser.index, this, MonadicParser.index).map(function (r) { return ({ start: r[0], value: r[1], end: r[2] }); });
    };
    MonadicParser.prototype.node = function (name) {
        return MonadicParser.seq(MonadicParser.index, this, MonadicParser.index).map(function (r) { return ({ name: name, start: r[0], value: r[1], end: r[2] }); });
    };
    ;
    MonadicParser.prototype.sepBy = function (separator) {
        return MonadicParser.sepBy(this, separator);
    };
    MonadicParser.prototype.sepBy1 = function (separator) {
        return MonadicParser.sepBy1(this, separator);
    };
    MonadicParser.prototype.lookahead = function (x) {
        return this.skip(MonadicParser.lookahead(x));
    };
    ;
    MonadicParser.prototype.notFollowedBy = function (x) {
        return this.skip(MonadicParser.notFollowedBy(x));
    };
    ;
    MonadicParser.prototype.desc = function (expected) {
        var _this = this;
        return new MonadicParser(function (input, i) {
            var reply = _this._(input, i);
            if (!reply.status) {
                reply.expected = [expected];
            }
            return reply;
        });
    };
    ;
    MonadicParser.prototype.fallback = function (result) {
        return this.or(MonadicParser.succeed(result));
    };
    ;
    MonadicParser.prototype.ap = function (other) {
        return MonadicParser.seq(other, this).map(function (_a) {
            var f = _a[0], x = _a[1];
            return f(x);
        });
    };
    ;
    MonadicParser.prototype.chain = function (f) {
        var _this = this;
        return new MonadicParser(function (input, i) {
            var result = _this._(input, i);
            if (!result.status) {
                return result;
            }
            var nextParser = f(result.value);
            return mergeReplies(nextParser._(input, result.index), result);
        });
    };
    ;
    return MonadicParser;
}());

(function (MonadicParser) {
    function seq() {
        var parsers = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            parsers[_i] = arguments[_i];
        }
        var numParsers = parsers.length;
        return new MonadicParser(function (input, index) {
            var result;
            var accum = new Array(numParsers);
            var i = index;
            for (var j = 0; j < numParsers; j++) {
                result = mergeReplies(parsers[j]._(input, i), result);
                if (!result.status) {
                    return result;
                }
                accum[j] = result.value;
                i = result.index;
            }
            return mergeReplies(makeSuccess(i, accum), result);
        });
    }
    MonadicParser.seq = seq;
    function alt() {
        var parsers = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            parsers[_i] = arguments[_i];
        }
        var numParsers = parsers.length;
        if (numParsers === 0) {
            return fail('zero alternates');
        }
        return new MonadicParser(function (input, i) {
            var result;
            for (var j = 0; j < parsers.length; j++) {
                result = mergeReplies(parsers[j]._(input, i), result);
                if (result.status) {
                    return result;
                }
            }
            return result;
        });
    }
    MonadicParser.alt = alt;
    function sepBy(parser, separator) {
        return sepBy1(parser, separator).or(succeed([]));
    }
    MonadicParser.sepBy = sepBy;
    function sepBy1(parser, separator) {
        var pairs = separator.then(parser).many();
        return seq(parser, pairs).map(function (r) { return Object(tslib_es6["__spreadArrays"])([r[0]], r[1]); });
    }
    MonadicParser.sepBy1 = sepBy1;
    function string(str) {
        var expected = "'" + str + "'";
        if (str.length === 1) {
            var code_1 = str.charCodeAt(0);
            return new MonadicParser(function (input, i) { return input.charCodeAt(i) === code_1 ? makeSuccess(i + 1, str) : makeFailure(i, expected); });
        }
        return new MonadicParser(function (input, i) {
            var j = i + str.length;
            if (input.slice(i, j) === str)
                return makeSuccess(j, str);
            else
                return makeFailure(i, expected);
        });
    }
    MonadicParser.string = string;
    function flags(re) {
        var s = '' + re;
        return s.slice(s.lastIndexOf('/') + 1);
    }
    function anchoredRegexp(re) {
        return RegExp('^(?:' + re.source + ')', flags(re));
    }
    function regexp(re, group) {
        if (group === void 0) { group = 0; }
        var anchored = anchoredRegexp(re);
        var expected = '' + re;
        return new MonadicParser(function (input, i) {
            var match = anchored.exec(input.slice(i));
            if (match) {
                if (0 <= group && group <= match.length) {
                    var fullMatch = match[0];
                    var groupMatch = match[group];
                    return makeSuccess(i + fullMatch.length, groupMatch);
                }
                var message = "invalid match group (0 to " + match.length + ") in " + expected;
                return makeFailure(i, message);
            }
            return makeFailure(i, expected);
        });
    }
    MonadicParser.regexp = regexp;
    function succeed(value) {
        return new MonadicParser(function (input, i) { return makeSuccess(i, value); });
    }
    MonadicParser.succeed = succeed;
    function fail(expected) {
        return new MonadicParser(function (input, i) { return makeFailure(i, expected); });
    }
    MonadicParser.fail = fail;
    function lookahead(x) {
        if (isParser(x)) {
            return new MonadicParser(function (input, i) {
                var result = x._(input, i);
                if (result.status) {
                    result.index = i;
                    result.value = null;
                }
                return result;
            });
        }
        else if (typeof x === 'string') {
            return lookahead(string(x));
        }
        else if (x instanceof RegExp) {
            return lookahead(regexp(x));
        }
        throw new Error('not a string, regexp, or parser: ' + x);
    }
    MonadicParser.lookahead = lookahead;
    function notFollowedBy(parser) {
        return new MonadicParser(function (input, i) {
            var result = parser._(input, i);
            return result.status
                ? makeFailure(i, 'not "' + input.slice(i, result.index) + '"')
                : makeSuccess(i, null);
        });
    }
    MonadicParser.notFollowedBy = notFollowedBy;
    function test(predicate) {
        return new MonadicParser(function (input, i) {
            var char = input.charAt(i);
            if (i < input.length && predicate(char)) {
                return makeSuccess(i + 1, char);
            }
            else {
                return makeFailure(i, 'a character ' + predicate);
            }
        });
    }
    MonadicParser.test = test;
    function oneOf(str) {
        return test(function (ch) { return str.indexOf(ch) >= 0; });
    }
    MonadicParser.oneOf = oneOf;
    function noneOf(str) {
        return test(function (ch) { return str.indexOf(ch) < 0; });
    }
    MonadicParser.noneOf = noneOf;
    function range(begin, end) {
        return test(function (ch) { return begin <= ch && ch <= end; }).desc(begin + '-' + end);
    }
    MonadicParser.range = range;
    function takeWhile(predicate) {
        return new MonadicParser(function (input, i) {
            var j = i;
            while (j < input.length && predicate(input.charAt(j))) {
                j++;
            }
            return makeSuccess(j, input.slice(i, j));
        });
    }
    MonadicParser.takeWhile = takeWhile;
    function lazy(f) {
        var parser = new MonadicParser(function (input, i) {
            var a = f()._;
            parser._ = a;
            return a(input, i);
        });
        return parser;
    }
    MonadicParser.lazy = lazy;
    function empty() {
        return fail('empty');
    }
    MonadicParser.empty = empty;
    MonadicParser.index = new MonadicParser(function (input, i) {
        return makeSuccess(i, makeLineColumnIndex(input, i));
    });
    MonadicParser.anyChar = new MonadicParser(function (input, i) {
        if (i >= input.length) {
            return makeFailure(i, 'any character');
        }
        return makeSuccess(i + 1, input.charAt(i));
    });
    MonadicParser.all = new MonadicParser(function (input, i) {
        return makeSuccess(input.length, input.slice(i));
    });
    MonadicParser.eof = new MonadicParser(function (input, i) {
        if (i < input.length) {
            return makeFailure(i, 'EOF');
        }
        return makeSuccess(i, null);
    });
    MonadicParser.digit = regexp(/[0-9]/).desc('a digit');
    MonadicParser.digits = regexp(/[0-9]*/).desc('optional digits');
    MonadicParser.letter = regexp(/[a-z]/i).desc('a letter');
    MonadicParser.letters = regexp(/[a-z]*/i).desc('optional letters');
    MonadicParser.optWhitespace = regexp(/\s*/).desc('optional whitespace');
    MonadicParser.whitespace = regexp(/\s+/).desc('whitespace');
    MonadicParser.cr = string('\r');
    MonadicParser.lf = string('\n');
    MonadicParser.crlf = string('\r\n');
    MonadicParser.newline = alt(MonadicParser.crlf, MonadicParser.lf, MonadicParser.cr).desc('newline');
    MonadicParser.end = alt(MonadicParser.newline, MonadicParser.eof);
})(monadic_parser_MonadicParser || (monadic_parser_MonadicParser = {}));
function seqPick(idx) {
    var parsers = [];
    for (var _i = 1; _i < arguments.length; _i++) {
        parsers[_i - 1] = arguments[_i];
    }
    var numParsers = parsers.length;
    return new monadic_parser_MonadicParser(function (input, index) {
        var result;
        var picked;
        var i = index;
        for (var j = 0; j < numParsers; j++) {
            result = mergeReplies(parsers[j]._(input, i), result);
            if (!result.status) {
                return result;
            }
            if (idx === j)
                picked = result.value;
            i = result.index;
        }
        return mergeReplies(makeSuccess(i, picked), result);
    });
}
function makeSuccess(index, value) {
    return { status: true, index: index, value: value };
}
function makeFailure(index, expected) {
    return { status: false, furthest: index, expected: [expected] };
}
function mergeReplies(result, last) {
    if (!last || result.status || last.status || result.furthest > last.furthest) {
        return result;
    }
    var expected = result.furthest === last.furthest
        ? unsafeUnion(result.expected, last.expected)
        : last.expected;
    return { status: result.status, furthest: last.furthest, expected: expected };
}
function makeLineColumnIndex(input, i) {
    var lines = input.slice(0, i).split('\n');
    // Note that unlike the character offset, the line and column offsets are
    // 1-based.
    var lineWeAreUpTo = lines.length;
    var columnWeAreUpTo = lines[lines.length - 1].length + 1;
    return { offset: i, line: lineWeAreUpTo, column: columnWeAreUpTo };
}
function formatExpected(expected) {
    if (expected.length === 1) {
        return expected[0];
    }
    return 'one of ' + expected.join(', ');
}
function formatGot(input, error) {
    var index = error.index;
    var i = index.offset;
    if (i === input.length) {
        return ', got the end of the input';
    }
    var prefix = i > 0 ? '\'...' : '\'';
    var suffix = input.length - i > 12 ? '...\'' : '\'';
    return " at line " + index.line + " column " + index.column + ", got " + prefix + input.slice(i, i + 12) + suffix;
}
function formatError(input, error) {
    return "expected " + formatExpected(error.expected) + formatGot(input, error);
}
function unsafeUnion(xs, ys) {
    var xn = xs.length;
    var yn = ys.length;
    if (xn === 0)
        return ys;
    else if (yn === 0)
        return xs;
    var set = new Set();
    var ret = [];
    for (var i = 0; i < xn; i++) {
        if (!set.has(xs[i])) {
            ret[ret.length] = xs[i];
            set.add(xs[i]);
        }
    }
    for (var i = 0; i < yn; i++) {
        if (!set.has(ys[i])) {
            ret[ret.length] = ys[i];
            set.add(ys[i]);
        }
    }
    ret.sort();
    return ret;
}
function isParser(obj) {
    return obj instanceof monadic_parser_MonadicParser;
}
//# sourceMappingURL=monadic-parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/language/parser.js
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



function parseMolScript(input) {
    return parser_Language.parse(input);
}
var parser_Language;
(function (Language) {
    var ASTNode;
    (function (ASTNode) {
        function str(value) { return { kind: 'string', value: value }; }
        ASTNode.str = str;
        function symb(value) { return { kind: 'symbol', value: value }; }
        ASTNode.symb = symb;
        function list(bracket, nodes) { return { kind: 'list', bracket: bracket, nodes: nodes }; }
        ASTNode.list = list;
        function comment(value) { return { kind: 'comment', value: value }; }
        ASTNode.comment = comment;
    })(ASTNode || (ASTNode = {}));
    var ws = monadic_parser_MonadicParser.regexp(/[\n\r\s]*/);
    var Expr = monadic_parser_MonadicParser.lazy(function () { return (monadic_parser_MonadicParser.alt(Str, List, Symb, Comment).trim(ws)); });
    var Str = monadic_parser_MonadicParser.takeWhile(function (c) { return c !== '`'; }).trim('`').map(ASTNode.str);
    var Symb = monadic_parser_MonadicParser.regexp(/[^()\[\]{};`,\n\r\s]+/).map(ASTNode.symb);
    var Comment = monadic_parser_MonadicParser.regexp(/\s*;+([^\n\r]*)\n/, 1).map(ASTNode.comment);
    var Args = Expr.many();
    var List1 = Args.wrap('(', ')').map(function (args) { return ASTNode.list('(', args); });
    var List2 = Args.wrap('[', ']').map(function (args) { return ASTNode.list('[', args); });
    var List3 = Args.wrap('{', '}').map(function (args) { return ASTNode.list('{', args); });
    var List = monadic_parser_MonadicParser.alt(List1, List2, List3);
    var Expressions = Expr.many();
    function getAST(input) { return Expressions.tryParse(input); }
    function visitExpr(expr) {
        switch (expr.kind) {
            case 'string': return expr.value;
            case 'symbol': {
                var value = expr.value;
                if (value.length > 1) {
                    var fst = value.charAt(0);
                    switch (fst) {
                        case '.': return builder["MolScriptBuilder"].atomName(value.substr(1));
                        case '_': return builder["MolScriptBuilder"].struct.type.elementSymbol([value.substr(1)]);
                    }
                }
                if (value === 'true')
                    return true;
                if (value === 'false')
                    return false;
                if (isNumber(value))
                    return +value;
                return language_expression["a" /* default */].Symbol(value);
            }
            case 'list': {
                switch (expr.bracket) {
                    case '[': return builder["MolScriptBuilder"].core.type.list(withoutComments(expr.nodes).map(visitExpr));
                    case '{': return builder["MolScriptBuilder"].core.type.set(withoutComments(expr.nodes).map(visitExpr));
                    case '(': {
                        var head = visitExpr(expr.nodes[0]);
                        return language_expression["a" /* default */].Apply(head, getArgs(expr.nodes));
                    }
                }
                return 0;
            }
            default: {
                throw new Error('should not happen');
            }
        }
    }
    function getArgs(nodes) {
        if (nodes.length <= 1)
            return void 0;
        if (!hasNamedArgs(nodes)) {
            var args_1 = [];
            for (var i = 1, _i = nodes.length; i < _i; i++) {
                var n = nodes[i];
                if (n.kind === 'comment')
                    continue;
                args_1[args_1.length] = visitExpr(n);
            }
            return args_1;
        }
        var args = {};
        var allNumeric = true;
        var pos = 0;
        for (var i = 1, _i = nodes.length; i < _i; i++) {
            var n = nodes[i];
            if (n.kind === 'comment')
                continue;
            if (n.kind === 'symbol' && n.value.length > 1 && n.value.charAt(0) === ':') {
                var name_1 = n.value.substr(1);
                ++i;
                while (i < _i && nodes[i].kind === 'comment') {
                    i++;
                }
                if (i >= _i)
                    throw new Error("There must be a value foolowed a named arg ':" + name_1 + "'.");
                args[name_1] = visitExpr(nodes[i]);
                if (isNaN(+name_1))
                    allNumeric = false;
            }
            else {
                args[pos++] = visitExpr(n);
            }
        }
        if (allNumeric) {
            var keys = Object.keys(args).map(function (a) { return +a; }).sort(function (a, b) { return a - b; });
            var isArray = true;
            for (var i = 0, _i = keys.length; i < _i; i++) {
                if (keys[i] !== i) {
                    isArray = false;
                    break;
                }
            }
            if (isArray) {
                var arrayArgs = [];
                for (var i = 0, _i = keys.length; i < _i; i++) {
                    arrayArgs[i] = args[i];
                }
                return arrayArgs;
            }
        }
        return args;
    }
    function hasNamedArgs(nodes) {
        for (var i = 1, _i = nodes.length; i < _i; i++) {
            var n = nodes[i];
            if (n.kind === 'symbol' && n.value.length > 1 && n.value.charAt(0) === ':')
                return true;
        }
        return false;
    }
    function withoutComments(nodes) {
        var hasComment = false;
        for (var i = 0, _i = nodes.length; i < _i; i++) {
            if (nodes[i].kind === 'comment') {
                hasComment = true;
                break;
            }
        }
        if (!hasComment)
            return nodes;
        return nodes.filter(function (n) { return n.kind !== 'comment'; });
    }
    function isNumber(value) {
        return /-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][+-]?[0-9]+)?/.test(value) && !isNaN(+value);
    }
    function parse(input) {
        var ast = getAST(input);
        var ret = [];
        for (var _a = 0, ast_1 = ast; _a < ast_1.length; _a++) {
            var expr = ast_1[_a];
            if (expr.kind === 'comment')
                continue;
            ret[ret.length] = visitExpr(expr);
        }
        return ret;
    }
    Language.parse = parse;
})(parser_Language || (parser_Language = {}));
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/compiler.js + 2 modules
var compiler = __webpack_require__(163);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/script.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






function script_Script(expression, language) {
    return { expression: expression, language: language };
}
(function (Script) {
    function is(x) {
        return !!x && typeof x.expression === 'string' && !!x.language;
    }
    Script.is = is;
    function areEqual(a, b) {
        return a.language === b.language && a.expression === b.expression;
    }
    Script.areEqual = areEqual;
    function toExpression(script) {
        switch (script.language) {
            case 'mol-script':
                var parsed = parseMolScript(script.expression);
                if (parsed.length === 0)
                    throw new Error('No query');
                return transpileMolScript(parsed[0]);
        }
        throw new Error('unsupported script language');
    }
    Script.toExpression = toExpression;
    function toQuery(script) {
        var expression = toExpression(script);
        return Object(compiler["compile"])(expression);
    }
    Script.toQuery = toQuery;
    function toLoci(script, structure) {
        var query = toQuery(script);
        var result = query(new mol_model_structure["QueryContext"](structure));
        return mol_model_structure["StructureSelection"].toLociWithSourceUnits(result);
    }
    Script.toLoci = toLoci;
    function getStructureSelection(expr, structure, options) {
        var e = typeof expr === 'function' ? expr(builder["MolScriptBuilder"]) : expr;
        var query = Object(compiler["compile"])(e);
        return query(new mol_model_structure["QueryContext"](structure, options));
    }
    Script.getStructureSelection = getStructureSelection;
})(script_Script || (script_Script = {}));
//# sourceMappingURL=script.js.map

/***/ }),
/* 121 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ encoding["b" /* VERSION */]; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ array_encoder["a" /* ArrayEncoder */]; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ array_encoder["b" /* ArrayEncoding */]; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ decode; });

// UNUSED EXPORTS: Encoding, ArrayEncoderImpl, classifyIntArray, classifyFloatArray

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary.js
var binary = __webpack_require__(324);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif/decoder.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * From CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 */

/**
 * Fixed point, delta, RLE, integer packing adopted from https://github.com/rcsb/mmtf-javascript/
 * by Alexander Rose <alexander.rose@weirdbyte.de>, MIT License, Copyright (c) 2016
 */
function decode(data) {
    var current = data.data;
    for (var i = data.encoding.length - 1; i >= 0; i--) {
        current = decodeStep(current, data.encoding[i]);
    }
    return current;
}
function decodeStep(data, encoding) {
    switch (encoding.kind) {
        case 'ByteArray': {
            switch (encoding.type) {
                case 4 /* Uint8 */: return data;
                case 1 /* Int8 */: return int8(data);
                case 2 /* Int16 */: return int16(data);
                case 5 /* Uint16 */: return uint16(data);
                case 3 /* Int32 */: return int32(data);
                case 6 /* Uint32 */: return uint32(data);
                case 32 /* Float32 */: return float32(data);
                case 33 /* Float64 */: return float64(data);
                default: throw new Error('Unsupported ByteArray type.');
            }
        }
        case 'FixedPoint': return fixedPoint(data, encoding);
        case 'IntervalQuantization': return intervalQuantization(data, encoding);
        case 'RunLength': return runLength(data, encoding);
        case 'Delta': return delta(data, encoding);
        case 'IntegerPacking': return integerPacking(data, encoding);
        case 'StringArray': return stringArray(data, encoding);
    }
}
function getIntArray(type, size) {
    switch (type) {
        case 1 /* Int8 */: return new Int8Array(size);
        case 2 /* Int16 */: return new Int16Array(size);
        case 3 /* Int32 */: return new Int32Array(size);
        case 4 /* Uint8 */: return new Uint8Array(size);
        case 5 /* Uint16 */: return new Uint16Array(size);
        case 6 /* Uint32 */: return new Uint32Array(size);
        default: throw new Error('Unsupported integer data type.');
    }
}
function getFloatArray(type, size) {
    switch (type) {
        case 32 /* Float32 */: return new Float32Array(size);
        case 33 /* Float64 */: return new Float64Array(size);
        default: throw new Error('Unsupported floating data type.');
    }
}
function int8(data) { return new Int8Array(data.buffer, data.byteOffset); }
function view(data, byteSize, c) {
    if (binary["a" /* IsNativeEndianLittle */])
        return new c(data.buffer);
    return new c(Object(binary["b" /* flipByteOrder */])(data, byteSize));
}
function int16(data) { return view(data, 2, Int16Array); }
function uint16(data) { return view(data, 2, Uint16Array); }
function int32(data) { return view(data, 4, Int32Array); }
function uint32(data) { return view(data, 4, Uint32Array); }
function float32(data) { return view(data, 4, Float32Array); }
function float64(data) { return view(data, 8, Float64Array); }
function fixedPoint(data, encoding) {
    var n = data.length;
    var output = getFloatArray(encoding.srcType, n);
    var f = 1 / encoding.factor;
    for (var i = 0; i < n; i++) {
        output[i] = f * data[i];
    }
    return output;
}
function intervalQuantization(data, encoding) {
    var n = data.length;
    var output = getFloatArray(encoding.srcType, n);
    var delta = (encoding.max - encoding.min) / (encoding.numSteps - 1);
    var min = encoding.min;
    for (var i = 0; i < n; i++) {
        output[i] = min + delta * data[i];
    }
    return output;
}
function runLength(data, encoding) {
    var output = getIntArray(encoding.srcType, encoding.srcSize);
    var dataOffset = 0;
    for (var i = 0, il = data.length; i < il; i += 2) {
        var value = data[i]; // value to be repeated
        var length_1 = data[i + 1]; // number of repeats
        for (var j = 0; j < length_1; ++j) {
            output[dataOffset++] = value;
        }
    }
    return output;
}
function delta(data, encoding) {
    var n = data.length;
    var output = getIntArray(encoding.srcType, n);
    if (!n)
        return data;
    output[0] = data[0] + (encoding.origin | 0);
    for (var i = 1; i < n; ++i) {
        output[i] = data[i] + output[i - 1];
    }
    return output;
}
function integerPackingSigned(data, encoding) {
    var upperLimit = encoding.byteCount === 1 ? 0x7F : 0x7FFF;
    var lowerLimit = -upperLimit - 1;
    var n = data.length;
    var output = new Int32Array(encoding.srcSize);
    var i = 0;
    var j = 0;
    while (i < n) {
        var value = 0, t = data[i];
        while (t === upperLimit || t === lowerLimit) {
            value += t;
            i++;
            t = data[i];
        }
        value += t;
        output[j] = value;
        i++;
        j++;
    }
    return output;
}
function integerPackingUnsigned(data, encoding) {
    var upperLimit = encoding.byteCount === 1 ? 0xFF : 0xFFFF;
    var n = data.length;
    var output = new Int32Array(encoding.srcSize);
    var i = 0;
    var j = 0;
    while (i < n) {
        var value = 0, t = data[i];
        while (t === upperLimit) {
            value += t;
            i++;
            t = data[i];
        }
        value += t;
        output[j] = value;
        i++;
        j++;
    }
    return output;
}
function integerPacking(data, encoding) {
    if (data.length === encoding.srcSize)
        return data;
    return encoding.isUnsigned ? integerPackingUnsigned(data, encoding) : integerPackingSigned(data, encoding);
}
function stringArray(data, encoding) {
    var offsets = decode({ encoding: encoding.offsetEncoding, data: encoding.offsets });
    var indices = decode({ encoding: encoding.dataEncoding, data: data });
    var str = encoding.stringData;
    var strings = new Array(offsets.length);
    strings[0] = '';
    for (var i = 1, _i = offsets.length; i < _i; i++) {
        strings[i] = str.substring(offsets[i - 1], offsets[i]);
    }
    var offset = 0;
    var result = new Array(indices.length);
    for (var i = 0, _i = indices.length; i < _i; i++) {
        result[offset++] = strings[indices[i] + 1];
    }
    return result;
}
//# sourceMappingURL=decoder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif/encoding.js
var encoding = __webpack_require__(250);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif/array-encoder.js
var array_encoder = __webpack_require__(107);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif/classifier.js
var classifier = __webpack_require__(260);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/common/binary-cif.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





//# sourceMappingURL=binary-cif.js.map

/***/ }),
/* 122 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isScheduler; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isScheduler(value) {
    return value && typeof value.schedule === 'function';
}
//# sourceMappingURL=isScheduler.js.map


/***/ }),
/* 123 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Text; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(117);
/* harmony import */ var _size_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(146);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(125);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(47);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(11);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(53);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(24);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1);
/* harmony import */ var _font_atlas__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(381);
/* harmony import */ var _mol_math_interpolate__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(78);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(142);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(9);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(124);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(143);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



















var Text;
(function (Text) {
    function create(fontTexture, centers, mappings, depths, indices, groups, tcoords, charCount, text) {
        return text ?
            update(fontTexture, centers, mappings, depths, indices, groups, tcoords, charCount, text) :
            fromData(fontTexture, centers, mappings, depths, indices, groups, tcoords, charCount);
    }
    Text.create = create;
    function createEmpty(text) {
        var ft = text ? text.fontTexture.ref.value : Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* createTextureImage */ "c"])(0, 1, Uint8Array);
        var cb = text ? text.centerBuffer.ref.value : new Float32Array(0);
        var mb = text ? text.mappingBuffer.ref.value : new Float32Array(0);
        var db = text ? text.depthBuffer.ref.value : new Float32Array(0);
        var ib = text ? text.indexBuffer.ref.value : new Uint32Array(0);
        var gb = text ? text.groupBuffer.ref.value : new Float32Array(0);
        var tb = text ? text.tcoordBuffer.ref.value : new Float32Array(0);
        return create(ft, cb, mb, db, ib, gb, tb, 0, text);
    }
    Text.createEmpty = createEmpty;
    function hashCode(text) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_16__[/* hashFnv32a */ "l"])([
            text.charCount, text.fontTexture.ref.version,
            text.centerBuffer.ref.version, text.mappingBuffer.ref.version,
            text.depthBuffer.ref.version, text.indexBuffer.ref.version,
            text.groupBuffer.ref.version, text.tcoordBuffer.ref.version
        ]);
    }
    function fromData(fontTexture, centers, mappings, depths, indices, groups, tcoords, charCount) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"])();
        var groupMapping;
        var currentHash = -1;
        var currentGroup = -1;
        var text = {
            kind: 'text',
            charCount: charCount,
            fontTexture: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(fontTexture),
            centerBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(centers),
            mappingBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(mappings),
            depthBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(depths),
            indexBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(indices),
            groupBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(groups),
            tcoordBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(tcoords),
            get boundingSphere() {
                var newHash = hashCode(text);
                if (newHash !== currentHash) {
                    var b = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateInvariantBoundingSphere */ "a"])(text.centerBuffer.ref.value, text.charCount * 4, 4);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
            get groupMapping() {
                if (text.groupBuffer.ref.version !== currentGroup) {
                    groupMapping = Object(_util__WEBPACK_IMPORTED_MODULE_17__[/* createGroupMapping */ "c"])(text.groupBuffer.ref.value, text.charCount, 4);
                    currentGroup = text.groupBuffer.ref.version;
                }
                return groupMapping;
            },
            setBoundingSphere: function (sphere) {
                _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].copy(boundingSphere, sphere);
                currentHash = hashCode(text);
            }
        };
        return text;
    }
    function update(fontTexture, centers, mappings, depths, indices, groups, tcoords, charCount, text) {
        text.charCount = charCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.fontTexture, fontTexture);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.centerBuffer, centers);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.mappingBuffer, mappings);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.depthBuffer, depths);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.indexBuffer, indices);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.groupBuffer, groups);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(text.tcoordBuffer, tcoords);
        return text;
    }
    Text.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].Params), _font_atlas__WEBPACK_IMPORTED_MODULE_11__[/* FontAtlasParams */ "a"]), { sizeFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), borderWidth: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0, { min: 0, max: 0.5, step: 0.01 }), borderColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].grey), offsetX: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0, { min: 0, max: 10, step: 0.1 }), offsetY: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0, { min: 0, max: 10, step: 0.1 }), offsetZ: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0, { min: 0, max: 10, step: 0.1 }), background: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false), backgroundMargin: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0.2, { min: 0, max: 1, step: 0.01 }), backgroundColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].grey), backgroundOpacity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(1, { min: 0, max: 1, step: 0.01 }), tether: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false), tetherLength: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(1, { min: 0, max: 5, step: 0.1 }), tetherBaseWidth: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(0.3, { min: 0, max: 1, step: 0.01 }), attachment: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Select('middle-center', [
            ['bottom-left', 'bottom-left'], ['bottom-center', 'bottom-center'], ['bottom-right', 'bottom-right'],
            ['middle-left', 'middle-left'], ['middle-center', 'middle-center'], ['middle-right', 'middle-right'],
            ['top-left', 'top-left'], ['top-center', 'top-center'], ['top-right', 'top-right'],
        ]) });
    Text.Utils = {
        Params: Text.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: createRenderableState,
        updateRenderableState: updateRenderableState,
    };
    function createValues(text, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        if (instanceCount !== transform.instanceCount.ref.value) {
            throw new Error('instanceCount values in TransformData and LocationIterator differ');
        }
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_3__[/* createColors */ "a"])(locationIt, theme.color);
        var size = Object(_size_data__WEBPACK_IMPORTED_MODULE_4__[/* createSizes */ "a"])(locationIt, theme.size);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_5__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_14__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_15__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_18__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: text.charCount * 2 * 3, groupCount: groupCount, instanceCount: instanceCount };
        var padding = getPadding(text.mappingBuffer.ref.value, text.depthBuffer.ref.value, text.charCount, Object(_size_data__WEBPACK_IMPORTED_MODULE_4__[/* getMaxSize */ "b"])(size));
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].expand(Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"])(), text.boundingSphere, padding);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ aPosition: text.centerBuffer, aMapping: text.mappingBuffer, aDepth: text.depthBuffer, aGroup: text.groupBuffer, elements: text.indexBuffer, boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec4"].ofSphere(invariantBoundingSphere)) }, color), size), marker), overpaint), transparency), clipping), transform), { aTexCoord: text.tcoordBuffer, tFont: text.fontTexture, padding: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(padding) }), _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].createValues(props, counts)), { uSizeFactor: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(props.sizeFactor), uBorderWidth: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_12__[/* clamp */ "a"])(props.borderWidth / 2, 0, 0.5)), uBorderColor: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].toArrayNormalized(props.borderColor, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec3"].zero(), 0)), uOffsetX: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(props.offsetX), uOffsetY: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(props.offsetY), uOffsetZ: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(props.offsetZ), uBackgroundColor: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].toArrayNormalized(props.backgroundColor, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec3"].zero(), 0)), uBackgroundOpacity: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].create(props.backgroundOpacity) });
    }
    function createValuesSimple(text, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(Text.Params)), props);
        return createValues(text, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uSizeFactor, props.sizeFactor);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uBorderWidth, props.borderWidth);
        if (_mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].fromNormalizedArray(values.uBorderColor.ref.value, 0) !== props.borderColor) {
            _mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].toArrayNormalized(props.borderColor, values.uBorderColor.ref.value, 0);
            _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.uBorderColor, values.uBorderColor.ref.value);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uOffsetX, props.offsetX);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uOffsetY, props.offsetY);
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uOffsetZ, props.offsetZ);
        if (_mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].fromNormalizedArray(values.uBackgroundColor.ref.value, 0) !== props.backgroundColor) {
            _mol_util_color__WEBPACK_IMPORTED_MODULE_9__["Color"].toArrayNormalized(props.backgroundColor, values.uBackgroundColor.ref.value, 0);
            _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.uBackgroundColor, values.uBackgroundColor.ref.value);
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].updateIfChanged(values.uBackgroundOpacity, props.backgroundOpacity);
    }
    function updateBoundingSphere(values, text) {
        var padding = getPadding(values.aMapping.ref.value, values.aDepth.ref.value, text.charCount, Object(_size_data__WEBPACK_IMPORTED_MODULE_4__[/* getMaxSize */ "b"])(values));
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].expand(Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"])(), text.boundingSphere, padding);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueCell */ "e"].update(values.padding, padding);
    }
    function createRenderableState(props) {
        var state = _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].createRenderableState(props);
        updateRenderableState(state, props);
        return state;
    }
    function updateRenderableState(state, props) {
        _base__WEBPACK_IMPORTED_MODULE_13__[/* BaseGeometry */ "a"].updateRenderableState(state, props);
        state.pickable = false;
        state.opaque = false;
        state.writeDepth = true;
    }
})(Text || (Text = {}));
function getPadding(mappings, depths, charCount, maxSize) {
    var maxOffset = 0;
    var maxDepth = 0;
    for (var i = 0, il = charCount * 4; i < il; ++i) {
        var i2 = 2 * i;
        var ox = Math.abs(mappings[i2]);
        if (ox > maxOffset)
            maxOffset = ox;
        var oy = Math.abs(mappings[i2 + 1]);
        if (oy > maxOffset)
            maxOffset = oy;
        var d = Math.abs(depths[i]);
        if (d > maxDepth)
            maxDepth = d;
    }
    // console.log(maxDepth + maxSize, maxDepth, maxSize, maxSize + maxSize * maxOffset, depths)
    return Math.max(maxDepth, maxSize + maxSize * maxOffset);
    // return maxSize + maxSize * maxOffset + maxDepth
}
//# sourceMappingURL=text.js.map

/***/ }),
/* 124 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export normalizeVec3Array */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return transformPositionArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return transformDirectionArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return appplyRadius; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return computeIndexedVertexNormals; });
/* unused harmony export computeVertexNormals */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createGroupMapping; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(29);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function normalizeVec3Array(a, count) {
    for (var i = 0, il = count * 3; i < il; i += 3) {
        var x = a[i];
        var y = a[i + 1];
        var z = a[i + 2];
        var s = 1 / Math.sqrt(x * x + y * y + z * z);
        a[i] = x * s;
        a[i + 1] = y * s;
        a[i + 2] = z * s;
    }
    return a;
}
var tmpV3 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
function transformPositionArray(t, array, offset, count) {
    for (var i = 0, il = count * 3; i < il; i += 3) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV3, array, offset + i);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpV3, tmpV3, t);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV3, array, offset + i);
    }
}
function transformDirectionArray(n, array, offset, count) {
    for (var i = 0, il = count * 3; i < il; i += 3) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV3, array, offset + i);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat3(tmpV3, tmpV3, n);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV3, array, offset + i);
    }
}
/** iterate over the entire array and apply the radius to each vertex */
function appplyRadius(vertices, radius) {
    for (var i = 0, il = vertices.length; i < il; i += 3) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV3, vertices, i);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].normalize(tmpV3, tmpV3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(tmpV3, tmpV3, radius);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV3, vertices, i);
    }
}
var a = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var b = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var c = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var cb = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
var ab = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
/**
 * indexed vertex normals weighted by triangle areas
 *      http://www.iquilezles.org/www/articles/normals/normals.htm
 * - normals array must contain only zeros
 */
function computeIndexedVertexNormals(vertices, indices, normals, vertexCount, triangleCount) {
    for (var i = 0, il = triangleCount * 3; i < il; i += 3) {
        var ai = indices[i] * 3;
        var bi = indices[i + 1] * 3;
        var ci = indices[i + 2] * 3;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(a, vertices, ai);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(b, vertices, bi);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(c, vertices, ci);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(cb, c, b);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(ab, a, b);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].cross(cb, cb, ab);
        normals[ai] += cb[0];
        normals[ai + 1] += cb[1];
        normals[ai + 2] += cb[2];
        normals[bi] += cb[0];
        normals[bi + 1] += cb[1];
        normals[bi + 2] += cb[2];
        normals[ci] += cb[0];
        normals[ci + 1] += cb[1];
        normals[ci + 2] += cb[2];
    }
    return normalizeVec3Array(normals, vertexCount);
}
/**
 * vertex normals for unindexed triangle soup
 * - normals array must contain only zeros
 */
function computeVertexNormals(vertices, normals, vertexCount) {
    for (var i = 0, il = vertexCount * 3; i < il; i += 9) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(a, vertices, i);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(b, vertices, i + 3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(c, vertices, i + 6);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(cb, c, b);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(ab, a, b);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].cross(cb, cb, ab);
        normals[i] = cb[0];
        normals[i + 1] = cb[1];
        normals[i + 2] = cb[2];
        normals[i + 3] = cb[0];
        normals[i + 4] = cb[1];
        normals[i + 5] = cb[2];
        normals[i + 6] = cb[0];
        normals[i + 7] = cb[1];
        normals[i + 8] = cb[2];
    }
    return normalizeVec3Array(normals, vertexCount);
}
/**
 * The `step` parameter allows to skip over repeated values in `groups`
 */
function createGroupMapping(groups, dataCount, step) {
    if (step === void 0) { step = 1; }
    var maxId = Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_1__["arrayMax"])(groups);
    var offsets = new Int32Array(maxId + 2);
    var bucketFill = new Int32Array(dataCount);
    var bucketSizes = new Int32Array(dataCount);
    for (var i = 0, il = dataCount * step; i < il; i += step)
        ++bucketSizes[groups[i]];
    var offset = 0;
    for (var i = 0; i < dataCount; i++) {
        offsets[i] = offset;
        offset += bucketSizes[i];
    }
    offsets[dataCount] = offset;
    var indices = new Int32Array(offset);
    for (var i = 0, il = dataCount * step; i < il; i += step) {
        var g = groups[i];
        var og = offsets[g] + bucketFill[g];
        indices[og] = i;
        ++bucketFill[g];
    }
    return { indices: indices, offsets: offsets };
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 125 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createMarkers; });
/* unused harmony export createEmptyMarkers */
/* harmony import */ var _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function createMarkers(count, markerData) {
    var markers = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* createTextureImage */ "c"])(Math.max(1, count), 1, Uint8Array, markerData && markerData.tMarker.ref.value.array);
    if (markerData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(markerData.tMarker, markers);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(markerData.uMarkerTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(markers.width, markers.height));
        return markerData;
    }
    else {
        return {
            tMarker: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(markers),
            uMarkerTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(markers.width, markers.height)),
        };
    }
}
var emptyMarkerTexture = { array: new Uint8Array(1), width: 1, height: 1 };
function createEmptyMarkers(markerData) {
    if (markerData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(markerData.tMarker, emptyMarkerTexture);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(markerData.uMarkerTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1));
        return markerData;
    }
    else {
        return {
            tMarker: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(emptyMarkerTexture),
            uMarkerTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1)),
        };
    }
}
//# sourceMappingURL=marker-data.js.map

/***/ }),
/* 126 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BoundaryHelper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(25);
/* harmony import */ var _centroid_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(195);
/* harmony import */ var _geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _primitives_box3d__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(230);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





// implementing http://www.ep.liu.se/ecp/034/009/ecp083409.pdf
var BoundaryHelper = /** @class */ (function () {
    function BoundaryHelper(quality) {
        this.minDist = [];
        this.maxDist = [];
        this.extrema = [];
        this.centroidHelper = new _centroid_helper__WEBPACK_IMPORTED_MODULE_2__[/* CentroidHelper */ "a"]();
        this.dir = getEposDir(quality);
        this.reset();
    }
    BoundaryHelper.prototype.computeExtrema = function (i, p) {
        var d = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].dot(this.dir[i], p);
        if (d < this.minDist[i]) {
            this.minDist[i] = d;
            _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].copy(this.extrema[i * 2], p);
        }
        if (d > this.maxDist[i]) {
            this.maxDist[i] = d;
            _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].copy(this.extrema[i * 2 + 1], p);
        }
    };
    BoundaryHelper.prototype.computeSphereExtrema = function (i, center, radius) {
        var d = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].dot(this.dir[i], center);
        if (d - radius < this.minDist[i]) {
            this.minDist[i] = d - radius;
            _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].scaleAndSub(this.extrema[i * 2], center, this.dir[i], radius);
        }
        if (d + radius > this.maxDist[i]) {
            this.maxDist[i] = d + radius;
            _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].scaleAndAdd(this.extrema[i * 2 + 1], center, this.dir[i], radius);
        }
    };
    BoundaryHelper.prototype.includeSphere = function (s) {
        if (_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].hasExtrema(s)) {
            for (var _i = 0, _a = s.extrema; _i < _a.length; _i++) {
                var e = _a[_i];
                this.includePosition(e);
            }
        }
        else {
            this.includePositionRadius(s.center, s.radius);
        }
    };
    BoundaryHelper.prototype.includePosition = function (p) {
        for (var i = 0, il = this.dir.length; i < il; ++i) {
            this.computeExtrema(i, p);
        }
    };
    BoundaryHelper.prototype.includePositionRadius = function (center, radius) {
        for (var i = 0, il = this.dir.length; i < il; ++i) {
            this.computeSphereExtrema(i, center, radius);
        }
    };
    BoundaryHelper.prototype.finishedIncludeStep = function () {
        for (var i = 0; i < this.extrema.length; i++) {
            this.centroidHelper.includeStep(this.extrema[i]);
        }
        this.centroidHelper.finishedIncludeStep();
    };
    BoundaryHelper.prototype.radiusSphere = function (s) {
        if (_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].hasExtrema(s)) {
            for (var _i = 0, _a = s.extrema; _i < _a.length; _i++) {
                var e = _a[_i];
                this.radiusPosition(e);
            }
        }
        else {
            this.radiusPositionRadius(s.center, s.radius);
        }
    };
    BoundaryHelper.prototype.radiusPosition = function (p) {
        this.centroidHelper.radiusStep(p);
    };
    BoundaryHelper.prototype.radiusPositionRadius = function (center, radius) {
        this.centroidHelper.radiusSphereStep(center, radius);
    };
    BoundaryHelper.prototype.getSphere = function (sphere) {
        return _geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].setExtrema(this.centroidHelper.getSphere(sphere), this.extrema);
    };
    BoundaryHelper.prototype.getBox = function (box) {
        if (!box)
            box = Object(_primitives_box3d__WEBPACK_IMPORTED_MODULE_4__[/* Box3D */ "a"])();
        _primitives_box3d__WEBPACK_IMPORTED_MODULE_4__[/* Box3D */ "a"].setEmpty(box);
        for (var i = 0; i < this.extrema.length; i++) {
            _primitives_box3d__WEBPACK_IMPORTED_MODULE_4__[/* Box3D */ "a"].add(box, this.extrema[i]);
        }
        return box;
    };
    BoundaryHelper.prototype.reset = function () {
        for (var i = 0, il = this.dir.length; i < il; ++i) {
            this.minDist[i] = Infinity;
            this.maxDist[i] = -Infinity;
            this.extrema[i * 2] = Object(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"])();
            this.extrema[i * 2 + 1] = Object(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"])();
        }
        this.centroidHelper.reset();
    };
    return BoundaryHelper;
}());

function getEposDir(quality) {
    var dir;
    switch (quality) {
        case '6':
            dir = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(Type001);
            break;
        case '14':
            dir = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(Type001, Type111);
            break;
        case '26':
            dir = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(Type001, Type111, Type011);
            break;
        case '98':
            dir = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(Type001, Type111, Type011, Type012, Type112, Type122);
            break;
    }
    return dir.map(function (a) {
        var v = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].create(a[0], a[1], a[2]);
        return _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_1__[/* Vec3 */ "f"].normalize(v, v);
    });
}
var Type001 = [
    [1, 0, 0], [0, 1, 0], [0, 0, 1]
];
var Type111 = [
    [1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1]
];
var Type011 = [
    [1, 1, 0], [1, -1, 0], [1, 0, 1], [1, 0, -1], [0, 1, 1], [0, 1, -1]
];
var Type012 = [
    [0, 1, 2], [0, 2, 1], [1, 0, 2], [2, 0, 1], [1, 2, 0], [2, 1, 0],
    [0, 1, -2], [0, 2, -1], [1, 0, -2], [2, 0, -1], [1, -2, 0], [2, -1, 0]
];
var Type112 = [
    [1, 1, 2], [2, 1, 1], [1, 2, 1], [1, -1, 2], [1, 1, -2], [1, -1, -2],
    [2, -1, 1], [2, 1, -1], [2, -1, -1], [1, -2, 1], [1, 2, -1], [1, -2, -1]
];
var Type122 = [
    [2, 2, 1], [1, 2, 2], [2, 1, 2], [2, -2, 1], [2, 2, -1], [2, -2, -1],
    [1, -2, 2], [1, 2, -2], [1, -2, -2], [2, -1, 2], [2, 1, -2], [2, -1, -2]
];
//# sourceMappingURL=boundary-helper.js.map

/***/ }),
/* 127 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createPrimitive; });
/* unused harmony export copyPrimitive */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PrimitiveBuilder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return transformPrimitive; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var a = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), b = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), c = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
/** Create primitive with face normals from vertices and indices */
function createPrimitive(vertices, indices) {
    var count = indices.length;
    var builder = PrimitiveBuilder(count / 3);
    for (var i = 0; i < count; i += 3) {
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(a, vertices, indices[i] * 3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(b, vertices, indices[i + 1] * 3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(c, vertices, indices[i + 2] * 3);
        builder.add(a, b, c);
    }
    return builder.getPrimitive();
}
function copyPrimitive(primitive) {
    return {
        vertices: new Float32Array(primitive.vertices),
        normals: new Float32Array(primitive.normals),
        indices: new Uint32Array(primitive.indices)
    };
}
var vn = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
/** Builder to create primitive with face normals */
function PrimitiveBuilder(triangleCount) {
    var vertices = new Float32Array(triangleCount * 3 * 3);
    var normals = new Float32Array(triangleCount * 3 * 3);
    var indices = new Uint32Array(triangleCount * 3);
    var offset = 0;
    return {
        add: function (a, b, c) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(a, vertices, offset);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(b, vertices, offset + 3);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(c, vertices, offset + 6);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].triangleNormal(vn, a, b, c);
            for (var j = 0; j < 3; ++j) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(vn, normals, offset + 3 * j);
                indices[offset / 3 + j] = offset / 3 + j;
            }
            offset += 9;
        },
        getPrimitive: function () { return ({ vertices: vertices, normals: normals, indices: indices }); }
    };
}
var tmpV = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var tmpMat3 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat3"].zero();
/** Transform primitive in-place */
function transformPrimitive(primitive, t) {
    var vertices = primitive.vertices, normals = primitive.normals;
    var n = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat3"].directionTransform(tmpMat3, t);
    for (var i = 0, il = vertices.length; i < il; i += 3) {
        // position
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, vertices, i), t);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV, vertices, i);
        // normal
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat3(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, normals, i), n);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV, normals, i);
    }
    return primitive;
}
//# sourceMappingURL=primitive.js.map

/***/ }),
/* 128 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return CifFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CifBlock; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return CifSaveFrame; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CifCategory; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return CifField; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return tensorFieldNameGetter; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return getTensor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getCifFieldType; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
/* harmony import */ var _common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(97);
/* harmony import */ var _common_text_column_token__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(73);
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function CifFile(blocks, name) {
    return { name: name, blocks: blocks };
}
function CifBlock(categoryNames, categories, header, saveFrames) {
    if (saveFrames === void 0) { saveFrames = []; }
    return {
        categoryNames: categoryNames, header: header, categories: categories, saveFrames: saveFrames,
        getField: function (name) {
            var _a = name.split('.'), category = _a[0], field = _a[1];
            return categories[category].getField(field || '');
        }
    };
}
function CifSaveFrame(categoryNames, categories, header) {
    return { categoryNames: categoryNames, header: header, categories: categories };
}
function CifCategory(name, rowCount, fieldNames, fields) {
    return { rowCount: rowCount, name: name, fieldNames: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(fieldNames), getField: function (name) { return fields[name]; } };
}
(function (CifCategory) {
    function empty(name) {
        return { rowCount: 0, name: name, fieldNames: [], getField: function (name) { return void 0; } };
    }
    CifCategory.empty = empty;
    ;
    function ofFields(name, fields) {
        var fieldNames = Object.keys(fields);
        return {
            rowCount: fieldNames.length > 0 ? fields[fieldNames[0]].rowCount : 0,
            name: name,
            fieldNames: fieldNames,
            getField: function (name) { return fields[name]; }
        };
    }
    CifCategory.ofFields = ofFields;
    function ofTable(name, table) {
        var fields = {};
        for (var _a = 0, _b = table._columns; _a < _b.length; _a++) {
            var name_1 = _b[_a];
            fields[name_1] = CifField.ofColumn(table[name_1]);
        }
        return ofFields(name, fields);
    }
    CifCategory.ofTable = ofTable;
})(CifCategory || (CifCategory = {}));
var CifField;
(function (CifField) {
    function ofString(value) {
        return ofStrings([value]);
    }
    CifField.ofString = ofString;
    function ofStrings(values) {
        var rowCount = values.length;
        var str = function (row) { var ret = values[row]; if (!ret || ret === '.' || ret === '?')
            return ''; return ret; };
        var int = function (row) { var v = values[row]; return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseInt */ "d"])(v, 0, v.length) || 0; };
        var float = function (row) { var v = values[row]; return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseFloat */ "b"])(v, 0, v.length) || 0; };
        var valueKind = function (row) {
            var v = values[row], l = v.length;
            if (l > 1)
                return 0 /* Present */;
            if (l === 0)
                return 1 /* NotPresent */;
            var c = v.charCodeAt(0);
            if (c === 46 /* . */)
                return 1 /* NotPresent */;
            if (c === 63 /* ? */)
                return 2 /* Unknown */;
            return 0 /* Present */;
        };
        return {
            __array: void 0,
            binaryEncoding: void 0,
            isDefined: true,
            rowCount: rowCount,
            str: str,
            int: int,
            float: float,
            valueKind: valueKind,
            areValuesEqual: function (rowA, rowB) { return values[rowA] === values[rowB]; },
            toStringArray: function (params) { return params ? _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, str, params) : values; },
            toIntArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, int, params); },
            toFloatArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, float, params); }
        };
    }
    CifField.ofStrings = ofStrings;
    function ofNumbers(values) {
        var rowCount = values.length;
        var str = function (row) { return '' + values[row]; };
        var float = function (row) { return values[row]; };
        var valueKind = function (row) { return 0 /* Present */; };
        var toFloatArray = function (params) {
            if (!params || params.array && values instanceof params.array) {
                return values;
            }
            else {
                return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, float, params);
            }
        };
        return {
            __array: void 0,
            binaryEncoding: void 0,
            isDefined: true,
            rowCount: rowCount,
            str: str,
            int: float,
            float: float,
            valueKind: valueKind,
            areValuesEqual: function (rowA, rowB) { return values[rowA] === values[rowB]; },
            toStringArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, str, params); },
            toIntArray: toFloatArray,
            toFloatArray: toFloatArray
        };
    }
    CifField.ofNumbers = ofNumbers;
    function ofTokens(tokens) {
        var data = tokens.data, indices = tokens.indices, rowCount = tokens.count;
        var str = function (row) {
            var ret = data.substring(indices[2 * row], indices[2 * row + 1]);
            if (ret === '.' || ret === '?')
                return '';
            return ret;
        };
        var int = function (row) {
            return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseInt */ "d"])(data, indices[2 * row], indices[2 * row + 1]) || 0;
        };
        var float = function (row) {
            return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseFloat */ "b"])(data, indices[2 * row], indices[2 * row + 1]) || 0;
        };
        var valueKind = function (row) {
            var s = indices[2 * row], l = indices[2 * row + 1] - s;
            if (l > 1)
                return 0 /* Present */;
            if (l === 0)
                return 1 /* NotPresent */;
            var v = data.charCodeAt(s);
            if (v === 46 /* . */)
                return 1 /* NotPresent */;
            if (v === 63 /* ? */)
                return 2 /* Unknown */;
            return 0 /* Present */;
        };
        return {
            __array: void 0,
            binaryEncoding: void 0,
            isDefined: true,
            rowCount: rowCount,
            str: str,
            int: int,
            float: float,
            valueKind: valueKind,
            areValuesEqual: Object(_common_text_column_token__WEBPACK_IMPORTED_MODULE_3__[/* areValuesEqualProvider */ "b"])(tokens),
            toStringArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, str, params); },
            toIntArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, int, params); },
            toFloatArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, float, params); }
        };
    }
    CifField.ofTokens = ofTokens;
    function ofColumn(column) {
        var rowCount = column.rowCount, valueKind = column.valueKind, areValuesEqual = column.areValuesEqual, isDefined = column.isDefined;
        var str;
        var int;
        var float;
        switch (column.schema.valueType) {
            case 'float':
            case 'int':
                str = function (row) { return '' + column.value(row); };
                int = column.value;
                float = column.value;
                break;
            case 'str':
                str = column.value;
                int = function (row) { var v = column.value(row); return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseInt */ "d"])(v, 0, v.length) || 0; };
                float = function (row) { var v = column.value(row); return Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* parseFloat */ "b"])(v, 0, v.length) || 0; };
                break;
            case 'list':
                var separator_1 = column.schema.separator;
                str = function (row) { return column.value(row).join(separator_1); };
                int = function (row) { return NaN; };
                float = function (row) { return NaN; };
                break;
            default:
                throw new Error("unsupported valueType '" + column.schema.valueType + "'");
        }
        return {
            __array: void 0,
            binaryEncoding: void 0,
            isDefined: isDefined,
            rowCount: rowCount,
            str: str,
            int: int,
            float: float,
            valueKind: valueKind,
            areValuesEqual: areValuesEqual,
            toStringArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, str, params); },
            toIntArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, int, params); },
            toFloatArray: function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(rowCount, float, params); }
        };
    }
    CifField.ofColumn = ofColumn;
})(CifField || (CifField = {}));
function tensorFieldNameGetter(field, rank, zeroIndexed, namingVariant) {
    var offset = zeroIndexed ? 0 : 1;
    switch (rank) {
        case 1:
            return namingVariant === 'brackets'
                ? function (i) { return field + "[" + (i + offset) + "]"; }
                : function (i) { return field + "_" + (i + offset); };
        case 2:
            return namingVariant === 'brackets'
                ? function (i, j) { return field + "[" + (i + offset) + "][" + (j + offset) + "]"; }
                : function (i, j) { return field + "_" + (i + offset) + (j + offset); };
        case 3:
            return namingVariant === 'brackets'
                ? function (i, j, k) { return field + "[" + (i + offset) + "][" + (j + offset) + "][" + (k + offset) + "]"; }
                : function (i, j, k) { return field + "_" + (i + offset) + (j + offset) + (k + offset); };
        default:
            throw new Error('Tensors with rank > 3 or rank 0 are currently not supported.');
    }
}
function getTensor(category, space, row, getName) {
    var ret = space.create();
    if (space.rank === 1) {
        var rows = space.dimensions[0];
        for (var i = 0; i < rows; i++) {
            var f = category.getField(getName(i));
            space.set(ret, i, !!f ? f.float(row) : 0.0);
        }
    }
    else if (space.rank === 2) {
        var rows = space.dimensions[0], cols = space.dimensions[1];
        for (var i = 0; i < rows; i++) {
            for (var j = 0; j < cols; j++) {
                var f = category.getField(getName(i, j));
                space.set(ret, i, j, !!f ? f.float(row) : 0.0);
            }
        }
    }
    else if (space.rank === 3) {
        var d0 = space.dimensions[0], d1 = space.dimensions[1], d2 = space.dimensions[2];
        for (var i = 0; i < d0; i++) {
            for (var j = 0; j < d1; j++) {
                for (var k = 0; k < d2; k++) {
                    var f = category.getField(getName(i, j, k));
                    space.set(ret, i, j, k, !!f ? f.float(row) : 0.0);
                }
            }
        }
    }
    else {
        throw new Error('Tensors with rank > 3 or rank 0 are currently not supported.');
    }
    return ret;
}
function getCifFieldType(field) {
    var floatCount = 0, hasStringOrScientific = false, undefinedCount = 0;
    for (var i = 0, _i = field.rowCount; i < _i; i++) {
        var k = field.valueKind(i);
        if (k !== 0 /* Present */) {
            undefinedCount++;
            continue;
        }
        var type = Object(_common_text_number_parser__WEBPACK_IMPORTED_MODULE_2__[/* getNumberType */ "a"])(field.str(i));
        if (type === 0 /* Int */)
            continue;
        else if (type === 1 /* Float */)
            floatCount++;
        else {
            hasStringOrScientific = true;
            break;
        }
    }
    // numbers in scientific notation and plain text are not distinguishable
    if (hasStringOrScientific || undefinedCount === field.rowCount)
        return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.str;
    if (floatCount > 0)
        return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.float;
    return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.int;
}
//# sourceMappingURL=data-model.js.map

/***/ }),
/* 129 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-model/structure/structure/element/index.js
var structure_element_namespaceObject = {};
__webpack_require__.r(structure_element_namespaceObject);
__webpack_require__.d(structure_element_namespaceObject, "Location", function() { return element_location["a" /* Location */]; });
__webpack_require__.d(structure_element_namespaceObject, "Loci", function() { return element_loci["a" /* Loci */]; });
__webpack_require__.d(structure_element_namespaceObject, "Bundle", function() { return bundle["a" /* Bundle */]; });
__webpack_require__.d(structure_element_namespaceObject, "Stats", function() { return stats_Stats; });
__webpack_require__.d(structure_element_namespaceObject, "property", function() { return property; });
__webpack_require__.d(structure_element_namespaceObject, "atomicProperty", function() { return atomicProperty; });
__webpack_require__.d(structure_element_namespaceObject, "coarseProperty", function() { return coarseProperty; });
__webpack_require__.d(structure_element_namespaceObject, "residueIndex", function() { return residueIndex; });
__webpack_require__.d(structure_element_namespaceObject, "chainIndex", function() { return chainIndex; });
__webpack_require__.d(structure_element_namespaceObject, "entityIndex", function() { return entityIndex; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/location.js
var element_location = __webpack_require__(87);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/loci.js
var element_loci = __webpack_require__(275);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/bundle.js
var bundle = __webpack_require__(342);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit.js + 2 modules
var structure_unit = __webpack_require__(37);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/stats.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var stats_Stats;
(function (Stats) {
    function create() {
        return {
            elementCount: 0,
            conformationCount: 0,
            residueCount: 0,
            chainCount: 0,
            unitCount: 0,
            structureCount: 0,
            firstElementLoc: element_location["a" /* Location */].create(void 0),
            firstConformationLoc: element_location["a" /* Location */].create(void 0),
            firstResidueLoc: element_location["a" /* Location */].create(void 0),
            firstChainLoc: element_location["a" /* Location */].create(void 0),
            firstUnitLoc: element_location["a" /* Location */].create(void 0),
            firstStructureLoc: element_location["a" /* Location */].create(void 0),
        };
    }
    Stats.create = create;
    function addCountHelper(map, key, inc) {
        var count = map.get(key) || 0;
        map.set(key, count + inc);
    }
    function handleElement(stats, structure, element) {
        var indices = element.indices, unit = element.unit;
        var elements = unit.elements;
        var size = mol_data_int["OrderedSet"].size(indices);
        var lociResidueAltIdCounts = new Map();
        var residueAltIdCounts = new Map();
        if (size > 0) {
            element_location["a" /* Location */].set(stats.firstElementLoc, structure, unit, elements[mol_data_int["OrderedSet"].start(indices)]);
        }
        // count single element unit as unit not element
        if (size === elements.length) {
            stats.unitCount += 1;
            if (stats.unitCount === 1) {
                element_location["a" /* Location */].set(stats.firstUnitLoc, structure, unit, elements[mol_data_int["OrderedSet"].start(indices)]);
            }
        }
        else if (size === 1) {
            if (structure_unit["a" /* default */].Traits.is(unit.traits, 1 /* MultiChain */)) {
                return;
            }
            else {
                stats.elementCount += 1;
                if (stats.elementCount === 1) {
                    element_location["a" /* Location */].set(stats.firstElementLoc, structure, unit, elements[mol_data_int["OrderedSet"].start(indices)]);
                }
            }
        }
        else {
            if (structure_unit["a" /* default */].isAtomic(unit)) {
                var _a = unit.model.atomicHierarchy.residueAtomSegments, index = _a.index, offsets_1 = _a.offsets;
                var label_alt_id_1 = unit.model.atomicHierarchy.atoms.label_alt_id;
                var i = 0;
                var _loop_1 = function () {
                    lociResidueAltIdCounts.clear();
                    var j = 0;
                    var eI = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                    var rI = index[eI];
                    addCountHelper(lociResidueAltIdCounts, label_alt_id_1.value(eI), 1);
                    ++i;
                    ++j;
                    while (i < size) {
                        var eI_1 = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                        if (index[eI_1] !== rI)
                            break;
                        addCountHelper(lociResidueAltIdCounts, label_alt_id_1.value(eI_1), 1);
                        ++i;
                        ++j;
                    }
                    if (offsets_1[rI + 1] - offsets_1[rI] === j) {
                        // full residue
                        stats.residueCount += 1;
                        if (stats.residueCount === 1) {
                            element_location["a" /* Location */].set(stats.firstResidueLoc, structure, unit, offsets_1[rI]);
                        }
                    }
                    else {
                        // partial residue
                        residueAltIdCounts.clear();
                        for (var l = offsets_1[rI], _l = offsets_1[rI + 1]; l < _l; ++l) {
                            addCountHelper(residueAltIdCounts, label_alt_id_1.value(l), 1);
                        }
                        // check if shared atom count match
                        if (residueAltIdCounts.get('') === lociResidueAltIdCounts.get('')) {
                            lociResidueAltIdCounts.forEach(function (v, k) {
                                if (residueAltIdCounts.get(k) !== v)
                                    return;
                                if (k !== '') {
                                    stats.conformationCount += 1;
                                    if (stats.conformationCount === 1) {
                                        for (var l = offsets_1[rI], _l = offsets_1[rI + 1]; l < _l; ++l) {
                                            if (k === label_alt_id_1.value(l)) {
                                                element_location["a" /* Location */].set(stats.firstConformationLoc, structure, unit, l);
                                                break;
                                            }
                                        }
                                    }
                                }
                                j -= v;
                            });
                        }
                        stats.elementCount += j;
                    }
                };
                while (i < size) {
                    _loop_1();
                }
            }
            else {
                stats.elementCount += size;
                if (stats.elementCount === 1) {
                    element_location["a" /* Location */].set(stats.firstElementLoc, structure, unit, elements[mol_data_int["OrderedSet"].start(indices)]);
                }
            }
        }
    }
    function handleUnitChainsSimple(stats, structure, element) {
        var indices = element.indices, unit = element.unit;
        var size = mol_data_int["OrderedSet"].size(indices);
        if (size === 0)
            return;
        var elements = unit.elements;
        if (!structure_unit["a" /* default */].Traits.is(unit.traits, 1 /* MultiChain */)) {
            if (size === elements.length) {
                stats.chainCount += 1;
                if (stats.chainCount === 1) {
                    element_location["a" /* Location */].set(stats.firstChainLoc, structure, unit, elements[mol_data_int["OrderedSet"].start(indices)]);
                }
            }
            return;
        }
        var segments = structure_unit["a" /* default */].isAtomic(unit)
            ? unit.model.atomicHierarchy.chainAtomSegments
            : structure_unit["a" /* default */].isSpheres(unit)
                ? unit.model.coarseHierarchy.spheres.chainElementSegments
                : structure_unit["a" /* default */].isGaussians(unit)
                    ? unit.model.coarseHierarchy.gaussians.chainElementSegments
                    : void 0;
        if (!segments) {
            console.warn('StructureElement loci stats: unknown unit type');
            return;
        }
        var index = segments.index, offsets = segments.offsets;
        var i = 0;
        while (i < size) {
            var j = 0;
            var eI = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
            var cI = index[eI];
            ++i;
            ++j;
            while (i < size) {
                var eI_2 = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                if (index[eI_2] !== cI)
                    break;
                ++i;
                ++j;
            }
            if (offsets[cI + 1] - offsets[cI] === j) {
                // full chain
                stats.chainCount += 1;
                if (stats.chainCount === 1) {
                    element_location["a" /* Location */].set(stats.firstChainLoc, structure, unit, offsets[cI]);
                }
            }
        }
    }
    function handleUnitChainsPartitioned(stats, structure, lociElements, start, end) {
        var element = lociElements[start];
        // all the elements have the same model since they are part of the same group so this is ok.
        var segments = structure_unit["a" /* default */].isAtomic(element.unit)
            ? element.unit.model.atomicHierarchy.chainAtomSegments
            : structure_unit["a" /* default */].isSpheres(element.unit)
                ? element.unit.model.coarseHierarchy.spheres.chainElementSegments
                : structure_unit["a" /* default */].isGaussians(element.unit)
                    ? element.unit.model.coarseHierarchy.gaussians.chainElementSegments
                    : void 0;
        if (!segments) {
            console.warn('StructureElement loci stats: unknown unit type');
            return;
        }
        var index = segments.index, offsets = segments.offsets;
        var chainCounts = new Map();
        for (var elIndex = start; elIndex < end; elIndex++) {
            element = lociElements[elIndex];
            var indices = element.indices, unit = element.unit;
            var size = mol_data_int["OrderedSet"].size(indices);
            if (size === 0)
                continue;
            var elements = unit.elements;
            if (!structure_unit["a" /* default */].Traits.is(unit.traits, 1 /* MultiChain */)) {
                var eI = elements[mol_data_int["OrderedSet"].start(indices)];
                addCountHelper(chainCounts, index[eI], elements.length);
                continue;
            }
            var i = 0;
            while (i < size) {
                var j = 0;
                var eI = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                var cI = index[eI];
                ++i;
                ++j;
                while (i < size) {
                    var eI_3 = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                    if (index[eI_3] !== cI)
                        break;
                    ++i;
                    ++j;
                }
                addCountHelper(chainCounts, cI, j);
            }
        }
        var firstCI = -1;
        chainCounts.forEach(function (count, cI) {
            if (offsets[cI + 1] - offsets[cI] === count) {
                // full chain
                stats.chainCount += 1;
                if (stats.chainCount === 1) {
                    firstCI = cI;
                }
            }
        });
        if (firstCI < 0)
            return;
        for (var elIndex = start; elIndex < end; elIndex++) {
            element = lociElements[elIndex];
            var indices = element.indices, unit = element.unit;
            var size = mol_data_int["OrderedSet"].size(indices);
            if (size === 0)
                continue;
            var elements = unit.elements;
            var i = 0;
            while (i < size) {
                var eI = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
                var cI = index[eI];
                if (cI === firstCI) {
                    element_location["a" /* Location */].set(stats.firstChainLoc, structure, unit, eI);
                    return;
                }
            }
        }
    }
    function ofLoci(loci) {
        var stats = create();
        if (element_loci["a" /* Loci */].isEmpty(loci))
            return stats;
        var hasPartitions = false;
        if (element_loci["a" /* Loci */].isWholeStructure(loci)) {
            stats.structureCount += 1;
            if (stats.structureCount === 1) {
                var _a = loci.elements[0], unit = _a.unit, indices = _a.indices;
                element_location["a" /* Location */].set(stats.firstStructureLoc, loci.structure, unit, unit.elements[mol_data_int["OrderedSet"].min(indices)]);
            }
        }
        else {
            for (var _i = 0, _b = loci.elements; _i < _b.length; _i++) {
                var e = _b[_i];
                handleElement(stats, loci.structure, e);
                if (!structure_unit["a" /* default */].Traits.is(e.unit.traits, 2 /* Partitioned */)) {
                    handleUnitChainsSimple(stats, loci.structure, e);
                }
                else {
                    hasPartitions = true;
                }
            }
        }
        if (hasPartitions) {
            for (var i = 0, len = loci.elements.length; i < len; i++) {
                var e = loci.elements[i];
                if (!structure_unit["a" /* default */].Traits.is(e.unit.traits, 2 /* Partitioned */))
                    continue;
                var start = i;
                while (i < len && structure_unit["a" /* default */].areSameChainOperatorGroup(loci.elements[i].unit, e.unit)) {
                    i++;
                }
                var end = i;
                i--;
                if (end - start === 1) {
                    handleUnitChainsSimple(stats, loci.structure, e);
                }
                else {
                    handleUnitChainsPartitioned(stats, loci.structure, loci.elements, start, end);
                }
            }
        }
        return stats;
    }
    Stats.ofLoci = ofLoci;
    /** Adds counts of two Stats objects together, assumes they describe different structures */
    function add(out, a, b) {
        if (a.elementCount === 1 && b.elementCount === 0) {
            element_location["a" /* Location */].copy(out.firstElementLoc, a.firstElementLoc);
        }
        else if (a.elementCount === 0 && b.elementCount === 1) {
            element_location["a" /* Location */].copy(out.firstElementLoc, b.firstElementLoc);
        }
        if (a.conformationCount === 1 && b.conformationCount === 0) {
            element_location["a" /* Location */].copy(out.firstConformationLoc, a.firstConformationLoc);
        }
        else if (a.conformationCount === 0 && b.conformationCount === 1) {
            element_location["a" /* Location */].copy(out.firstConformationLoc, b.firstConformationLoc);
        }
        if (a.residueCount === 1 && b.residueCount === 0) {
            element_location["a" /* Location */].copy(out.firstResidueLoc, a.firstResidueLoc);
        }
        else if (a.residueCount === 0 && b.residueCount === 1) {
            element_location["a" /* Location */].copy(out.firstResidueLoc, b.firstResidueLoc);
        }
        if (a.chainCount === 1 && b.chainCount === 0) {
            element_location["a" /* Location */].copy(out.firstChainLoc, a.firstChainLoc);
        }
        else if (a.chainCount === 0 && b.chainCount === 1) {
            element_location["a" /* Location */].copy(out.firstChainLoc, b.firstChainLoc);
        }
        if (a.unitCount === 1 && b.unitCount === 0) {
            element_location["a" /* Location */].copy(out.firstUnitLoc, a.firstUnitLoc);
        }
        else if (a.unitCount === 0 && b.unitCount === 1) {
            element_location["a" /* Location */].copy(out.firstUnitLoc, b.firstUnitLoc);
        }
        if (a.structureCount === 1 && b.structureCount === 0) {
            element_location["a" /* Location */].copy(out.firstStructureLoc, a.firstStructureLoc);
        }
        else if (a.structureCount === 0 && b.structureCount === 1) {
            element_location["a" /* Location */].copy(out.firstStructureLoc, b.firstStructureLoc);
        }
        out.elementCount = a.elementCount + b.elementCount;
        out.conformationCount = a.conformationCount + b.conformationCount;
        out.residueCount = a.residueCount + b.residueCount;
        out.chainCount = a.chainCount + b.chainCount;
        out.unitCount = a.unitCount + b.unitCount;
        out.structureCount = a.structureCount + b.structureCount;
        return out;
    }
    Stats.add = add;
})(stats_Stats || (stats_Stats = {}));
//# sourceMappingURL=stats.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/properties.js
var properties = __webpack_require__(168);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/element.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function property(p) { return p; }
function _wrongUnitKind(kind) { throw new Error("Property only available for " + kind + " models."); }
function atomicProperty(p) {
    return property(function (l) { return structure_unit["a" /* default */].isAtomic(l.unit) ? p(l) : _wrongUnitKind('atomic'); });
}
function coarseProperty(p) {
    return property(function (l) { return structure_unit["a" /* default */].isCoarse(l.unit) ? p(l) : _wrongUnitKind('coarse'); });
}
function residueIndex(e) {
    if (structure_unit["a" /* default */].isAtomic(e.unit)) {
        return e.unit.residueIndex[e.element];
    }
    else {
        // TODO: throw error instead?
        return -1;
    }
}
function chainIndex(e) {
    if (structure_unit["a" /* default */].isAtomic(e.unit)) {
        return e.unit.chainIndex[e.element];
    }
    else {
        // TODO: throw error instead?
        return -1;
    }
}
function entityIndex(l) {
    return properties["a" /* default */].entity.key(l);
}
//# sourceMappingURL=element.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element/index.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





//# sourceMappingURL=index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/* harmony default export */ var structure_element = __webpack_exports__["a"] = (structure_element_namespaceObject);
//# sourceMappingURL=element.js.map

/***/ }),
/* 130 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Overpaint; });
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(24);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _mol_script_script__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(120);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function Overpaint(layers) {
    return { layers: layers };
}
(function (Overpaint) {
    Overpaint.Empty = { layers: [] };
    function areEqual(oA, oB) {
        if (oA.layers.length === 0 && oB.layers.length === 0)
            return true;
        if (oA.layers.length !== oB.layers.length)
            return false;
        for (var i = 0, il = oA.layers.length; i < il; ++i) {
            if (oA.layers[i].clear !== oB.layers[i].clear)
                return false;
            if (oA.layers[i].color !== oB.layers[i].color)
                return false;
            if (!_mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["Loci"].areEqual(oA.layers[i].loci, oB.layers[i].loci))
                return false;
        }
        return true;
    }
    Overpaint.areEqual = areEqual;
    function isEmpty(overpaint) {
        return overpaint.layers.length === 0;
    }
    Overpaint.isEmpty = isEmpty;
    function remap(overpaint, structure) {
        var layers = [];
        for (var _i = 0, _a = overpaint.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, color = layer.color, clear = layer.clear;
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.remap(loci, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, color: color, clear: clear });
            }
        }
        return { layers: layers };
    }
    Overpaint.remap = remap;
    function merge(overpaint) {
        if (isEmpty(overpaint))
            return overpaint;
        var structure = overpaint.layers[0].loci.structure;
        var map = new Map();
        var shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.none(structure);
        for (var i = 0, il = overpaint.layers.length; i < il; ++i) {
            var _a = overpaint.layers[il - i - 1], loci = _a.loci, color = _a.color, clear = _a.clear; // process from end
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.subtract(loci, shadowed);
            shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.union(loci, shadowed);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.isEmpty(loci)) {
                var colorOrClear = clear ? -1 : color;
                if (map.has(colorOrClear)) {
                    loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.union(loci, map.get(colorOrClear));
                }
                map.set(colorOrClear, loci);
            }
        }
        var layers = [];
        map.forEach(function (loci, colorOrClear) {
            var clear = colorOrClear === -1;
            var color = colorOrClear === -1 ? Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_1__["Color"])(0) : colorOrClear;
            layers.push({ loci: loci, color: color, clear: clear });
        });
        return { layers: layers };
    }
    Overpaint.merge = merge;
    function filter(overpaint, filter) {
        if (isEmpty(overpaint))
            return overpaint;
        var structure = overpaint.layers[0].loci.structure;
        var layers = [];
        for (var _i = 0, _a = overpaint.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, color = layer.color, clear = layer.clear;
            // filter by first map to the `filter` structure and
            // then map back to the original structure of the overpaint loci
            var filtered = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.remap(loci, filter);
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.remap(filtered, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, color: color, clear: clear });
            }
        }
        return { layers: layers };
    }
    Overpaint.filter = filter;
    function ofScript(scriptLayers, structure) {
        var layers = [];
        for (var i = 0, il = scriptLayers.length; i < il; ++i) {
            var _a = scriptLayers[i], script = _a.script, color = _a.color, clear = _a.clear;
            var loci = _mol_script_script__WEBPACK_IMPORTED_MODULE_3__["Script"].toLoci(script, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, color: color, clear: clear });
            }
        }
        return { layers: layers };
    }
    Overpaint.ofScript = ofScript;
    function ofBundle(bundleLayers, structure) {
        var layers = [];
        for (var i = 0, il = bundleLayers.length; i < il; ++i) {
            var _a = bundleLayers[i], bundle = _a.bundle, color = _a.color, clear = _a.clear;
            var loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Bundle.toLoci(bundle, structure.root);
            layers.push({ loci: loci, color: color, clear: clear });
        }
        return { layers: layers };
    }
    Overpaint.ofBundle = ofBundle;
    function toBundle(overpaint) {
        var layers = [];
        for (var i = 0, il = overpaint.layers.length; i < il; ++i) {
            var _a = overpaint.layers[i], loci = _a.loci, color = _a.color, clear = _a.clear;
            var bundle = _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Bundle.fromLoci(loci);
            layers.push({ bundle: bundle, color: color, clear: clear });
        }
        return { layers: layers };
    }
    Overpaint.toBundle = toBundle;
})(Overpaint || (Overpaint = {}));
//# sourceMappingURL=overpaint.js.map

/***/ }),
/* 131 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Transparency; });
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_script_script__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(120);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function Transparency(layers) {
    return { layers: layers };
}
(function (Transparency) {
    Transparency.Empty = { layers: [] };
    function areEqual(tA, tB) {
        if (tA.layers.length === 0 && tB.layers.length === 0)
            return true;
        if (tA.layers.length !== tB.layers.length)
            return false;
        for (var i = 0, il = tA.layers.length; i < il; ++i) {
            if (tA.layers[i].value !== tB.layers[i].value)
                return false;
            if (!_mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["Loci"].areEqual(tA.layers[i].loci, tB.layers[i].loci))
                return false;
        }
        return true;
    }
    Transparency.areEqual = areEqual;
    function isEmpty(transparency) {
        return transparency.layers.length === 0;
    }
    Transparency.isEmpty = isEmpty;
    function remap(transparency, structure) {
        var layers = [];
        for (var _i = 0, _a = transparency.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, value = layer.value;
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(loci, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, value: value });
            }
        }
        return { layers: layers };
    }
    Transparency.remap = remap;
    function merge(transparency) {
        if (isEmpty(transparency))
            return transparency;
        var structure = transparency.layers[0].loci.structure;
        var map = new Map();
        var shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.none(structure);
        for (var i = 0, il = transparency.layers.length; i < il; ++i) {
            var _a = transparency.layers[il - i - 1], loci = _a.loci, value = _a.value; // process from end
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.subtract(loci, shadowed);
            shadowed = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.union(loci, shadowed);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                if (map.has(value)) {
                    loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.union(loci, map.get(value));
                }
                map.set(value, loci);
            }
        }
        var layers = [];
        map.forEach(function (loci, value) {
            layers.push({ loci: loci, value: value });
        });
        return { layers: layers };
    }
    Transparency.merge = merge;
    function filter(transparency, filter) {
        if (isEmpty(transparency))
            return transparency;
        var structure = transparency.layers[0].loci.structure;
        var layers = [];
        for (var _i = 0, _a = transparency.layers; _i < _a.length; _i++) {
            var layer = _a[_i];
            var loci = layer.loci, value = layer.value;
            // filter by first map to the `filter` structure and
            // then map back to the original structure of the transparency loci
            var filtered = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(loci, filter);
            loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.remap(filtered, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, value: value });
            }
        }
        return { layers: layers };
    }
    Transparency.filter = filter;
    function ofScript(scriptLayers, structure) {
        var layers = [];
        for (var i = 0, il = scriptLayers.length; i < il; ++i) {
            var _a = scriptLayers[i], script = _a.script, value = _a.value;
            var loci = _mol_script_script__WEBPACK_IMPORTED_MODULE_2__["Script"].toLoci(script, structure);
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.isEmpty(loci)) {
                layers.push({ loci: loci, value: value });
            }
        }
        return { layers: layers };
    }
    Transparency.ofScript = ofScript;
    function ofBundle(bundleLayers, structure) {
        var layers = [];
        for (var i = 0, il = bundleLayers.length; i < il; ++i) {
            var _a = bundleLayers[i], bundle = _a.bundle, value = _a.value;
            var loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Bundle.toLoci(bundle, structure.root);
            layers.push({ loci: loci, value: value });
        }
        return { layers: layers };
    }
    Transparency.ofBundle = ofBundle;
    function toBundle(transparency) {
        var layers = [];
        for (var i = 0, il = transparency.layers.length; i < il; ++i) {
            var _a = transparency.layers[i], loci = _a.loci, value = _a.value;
            var bundle = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Bundle.fromLoci(loci);
            layers.push({ bundle: bundle, value: value });
        }
        return { layers: layers };
    }
    Transparency.toBundle = toBundle;
})(Transparency || (Transparency = {}));
//# sourceMappingURL=transparency.js.map

/***/ }),
/* 132 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/*
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var Expression;
(function (Expression) {
    function Symbol(name) { return { name: name }; }
    Expression.Symbol = Symbol;
    function Apply(head, args) { return args ? { head: head, args: args } : { head: head }; }
    Expression.Apply = Apply;
    function isArgumentsArray(e) { return !!e && Array.isArray(e); }
    Expression.isArgumentsArray = isArgumentsArray;
    function isArgumentsMap(e) { return !!e && !Array.isArray(e); }
    Expression.isArgumentsMap = isArgumentsMap;
    function isLiteral(e) { return !isApply(e) && !isSymbol(e); }
    Expression.isLiteral = isLiteral;
    function isApply(e) { return !!e && !!e.head && typeof e === 'object'; }
    Expression.isApply = isApply;
    function isSymbol(e) { return !!e && typeof e.name === 'string'; }
    Expression.isSymbol = isSymbol;
})(Expression || (Expression = {}));
/* harmony default export */ __webpack_exports__["a"] = (Expression);
//# sourceMappingURL=expression.js.map

/***/ }),
/* 133 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return EMPTY; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return empty; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */

var EMPTY = /*@__PURE__*/ new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) { return subscriber.complete(); });
function empty(scheduler) {
    return scheduler ? emptyScheduled(scheduler) : EMPTY;
}
function emptyScheduled(scheduler) {
    return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); });
}
//# sourceMappingURL=empty.js.map


/***/ }),
/* 134 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyOverpaintColor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return clearOverpaint; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return createOverpaint; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createEmptyOverpaint; });
/* harmony import */ var _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(24);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function applyOverpaintColor(array, start, end, color) {
    for (var i = start; i < end; ++i) {
        _mol_util_color__WEBPACK_IMPORTED_MODULE_3__["Color"].toArray(color, array, i * 4);
        array[i * 4 + 3] = 255;
    }
    return true;
}
function clearOverpaint(array, start, end) {
    array.fill(0, start * 4, end * 4);
    return true;
}
function createOverpaint(count, overpaintData) {
    var overpaint = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* createTextureImage */ "c"])(Math.max(1, count), 4, Uint8Array, overpaintData && overpaintData.tOverpaint.ref.value.array);
    if (overpaintData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(overpaintData.tOverpaint, overpaint);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(overpaintData.uOverpaintTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(overpaint.width, overpaint.height));
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(overpaintData.dOverpaint, count > 0);
        return overpaintData;
    }
    else {
        return {
            tOverpaint: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(overpaint),
            uOverpaintTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(overpaint.width, overpaint.height)),
            dOverpaint: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(count > 0),
        };
    }
}
var emptyOverpaintTexture = { array: new Uint8Array(4), width: 1, height: 1 };
function createEmptyOverpaint(overpaintData) {
    if (overpaintData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(overpaintData.tOverpaint, emptyOverpaintTexture);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(overpaintData.uOverpaintTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1));
        return overpaintData;
    }
    else {
        return {
            tOverpaint: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(emptyOverpaintTexture),
            uOverpaintTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1)),
            dOverpaint: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(false),
        };
    }
}
//# sourceMappingURL=overpaint-data.js.map

/***/ }),
/* 135 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FieldPath", function() { return FieldPath; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDatabaseCollection", function() { return toDatabaseCollection; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toDatabase", function() { return toDatabase; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toTable", function() { return toTable; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/* harmony import */ var _data_model__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(128);
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var FieldPath;
(function (FieldPath) {
    function canonical(path) {
        return path.replace('.', '_').replace(/\[/, '_').replace(/(\[|\])/g, '');
    }
    FieldPath.canonical = canonical;
    function equal(pathA, pathB) {
        return canonical(pathA) === canonical(pathB);
    }
    FieldPath.equal = equal;
    function create(category, field, asCanonical) {
        if (asCanonical === void 0) { asCanonical = false; }
        var p = "" + category + (field ? "." + field : '');
        return asCanonical ? canonical(p) : p;
    }
    FieldPath.create = create;
})(FieldPath || (FieldPath = {}));
function toDatabaseCollection(schema, file, aliases) {
    var dbc = {};
    for (var _i = 0, _a = file.blocks; _i < _a.length; _i++) {
        var data = _a[_i];
        dbc[data.header] = toDatabase(schema, data, aliases);
    }
    return dbc;
}
function toDatabase(schema, frame, aliases) {
    return createDatabase(schema, frame, aliases);
}
function toTable(schema, category) {
    return new CategoryTable(category, schema, true);
}
function getColumnCtor(t) {
    switch (t.valueType) {
        case 'str': return function (f, c, k) { return createColumn(t, f, f.str, f.toStringArray); };
        case 'int': return function (f, c, k) { return createColumn(t, f, f.int, f.toIntArray); };
        case 'float': return function (f, c, k) { return createColumn(t, f, f.float, f.toFloatArray); };
        case 'list': throw new Error('Use createListColumn instead.');
        case 'tensor': throw new Error('Use createTensorColumn instead.');
    }
}
function createColumn(schema, field, value, toArray) {
    return {
        schema: schema,
        __array: field.__array,
        isDefined: field.isDefined,
        rowCount: field.rowCount,
        value: value,
        valueKind: field.valueKind,
        areValuesEqual: field.areValuesEqual,
        toArray: toArray
    };
}
function createListColumn(schema, category, key) {
    var separator = schema.separator;
    var itemParse = schema.itemParse;
    var f = category.getField(key);
    var value = f ? function (row) { return f.str(row).split(separator).map(function (x) { return itemParse(x.trim()); }).filter(function (x) { return !!x; }); } : function (row) { return []; };
    var toArray = function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(category.rowCount, value, params); };
    return {
        schema: schema,
        __array: void 0,
        isDefined: !!f,
        rowCount: category.rowCount,
        value: value,
        valueKind: f ? f.valueKind : function () { return 1 /* NotPresent */; },
        areValuesEqual: function (rowA, rowB) { return Object(_mol_util__WEBPACK_IMPORTED_MODULE_3__[/* arrayEqual */ "g"])(value(rowA), value(rowB)); },
        toArray: toArray
    };
}
function createTensorColumn(schema, category, key) {
    var space = schema.space;
    var zeroOffset = (category.fieldNames.includes(key + "[0]") ||
        category.fieldNames.includes(key + "[0][0]") ||
        category.fieldNames.includes(key + "[0][0][0]"));
    var fst = zeroOffset ? 0 : 1;
    var namingVariant = (category.fieldNames.includes(key + "_1") ||
        category.fieldNames.includes(key + "_11") ||
        category.fieldNames.includes(key + "_111")) ? 'underscore' : 'brackets';
    var getName = _data_model__WEBPACK_IMPORTED_MODULE_4__[/* tensorFieldNameGetter */ "h"](key, space.rank, zeroOffset, namingVariant);
    var first = category.getField(getName(fst, fst, fst)) || _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Undefined(category.rowCount, schema);
    var value = function (row) { return _data_model__WEBPACK_IMPORTED_MODULE_4__[/* getTensor */ "g"](category, space, row, getName); };
    var toArray = function (params) { return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["ColumnHelpers"].createAndFillArray(category.rowCount, value, params); };
    return {
        schema: schema,
        __array: void 0,
        isDefined: first.isDefined,
        rowCount: category.rowCount,
        value: value,
        valueKind: first.valueKind,
        areValuesEqual: function (rowA, rowB) { return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Tensor"].areEqualExact(value(rowA), value(rowB)); },
        toArray: toArray
    };
}
var CategoryTable = /** @class */ (function () {
    function CategoryTable(category, schema, _isDefined) {
        this._isDefined = _isDefined;
        var fieldKeys = Object.keys(schema);
        this._rowCount = category.rowCount;
        this._columns = fieldKeys;
        this._schema = schema;
        var cache = Object.create(null);
        var _loop_1 = function (k) {
            Object.defineProperty(this_1, k, {
                get: function () {
                    if (cache[k])
                        return cache[k];
                    var fType = schema[k];
                    if (fType.valueType === 'list') {
                        cache[k] = createListColumn(fType, category, k);
                    }
                    else if (fType.valueType === 'tensor') {
                        cache[k] = createTensorColumn(fType, category, k);
                    }
                    else {
                        var ctor = getColumnCtor(fType);
                        var field = category.getField(k);
                        cache[k] = !!field ? ctor(field, category, k) : _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Undefined(category.rowCount, fType);
                    }
                    return cache[k];
                },
                enumerable: true,
                configurable: false
            });
        };
        var this_1 = this;
        for (var _i = 0, fieldKeys_1 = fieldKeys; _i < fieldKeys_1.length; _i++) {
            var k = fieldKeys_1[_i];
            _loop_1(k);
        }
    }
    return CategoryTable;
}());
function createDatabase(schema, frame, aliases) {
    var tables = Object.create(null);
    for (var _i = 0, _a = Object.keys(schema); _i < _a.length; _i++) {
        var k = _a[_i];
        tables[k] = createTable(k, schema[k], frame, aliases);
    }
    return _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Database"].ofTables(frame.header, schema, tables);
}
function flattenFrame(frame) {
    var flatFrame = Object.create(null);
    for (var _i = 0, _a = Object.keys(frame.categories); _i < _a.length; _i++) {
        var c = _a[_i];
        for (var _b = 0, _c = frame.categories[c].fieldNames; _b < _c.length; _b++) {
            var f = _c[_b];
            var p = FieldPath.create(c, f, true);
            flatFrame[p] = frame.categories[c].getField(f);
        }
    }
    return flatFrame;
}
function getField(field, category, flatFrame, aliases) {
    var path = FieldPath.create(category, field);
    var canonicalPath = FieldPath.canonical(path);
    if (canonicalPath in flatFrame)
        return flatFrame[canonicalPath];
    if (aliases && path in aliases) {
        for (var _i = 0, _a = aliases[path]; _i < _a.length; _i++) {
            var aliased = _a[_i];
            var canonicalAliased = FieldPath.canonical(aliased);
            if (canonicalAliased in flatFrame)
                return flatFrame[canonicalAliased];
        }
    }
}
function createTable(key, schema, frame, aliases) {
    var cat = frame.categories[key];
    if (aliases) {
        var flatFrame = flattenFrame(frame);
        var fields_1 = Object.create(null);
        var fieldNames = [];
        var rowCount = 0;
        for (var _i = 0, _a = Object.keys(schema); _i < _a.length; _i++) {
            var k = _a[_i];
            var field = getField(k, key, flatFrame, aliases);
            if (field) {
                fields_1[k] = field;
                fieldNames.push(k);
                rowCount = field.rowCount;
            }
        }
        cat = {
            rowCount: rowCount,
            name: key,
            fieldNames: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(fieldNames),
            getField: function (name) {
                return fields_1[name];
            }
        };
    }
    return new CategoryTable(cat || _data_model__WEBPACK_IMPORTED_MODULE_4__[/* CifCategory */ "b"].empty(key), schema, !!cat);
}
//# sourceMappingURL=schema.js.map

/***/ }),
/* 136 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SymmetryOperator; });
/* harmony import */ var _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25);
/* harmony import */ var _mol_math_interpolate__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(78);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var SymmetryOperator;
(function (SymmetryOperator) {
    SymmetryOperator.DefaultName = '1_555';
    SymmetryOperator.Default = create(SymmetryOperator.DefaultName, _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].identity());
    SymmetryOperator.RotationTranslationEpsilon = 0.005;
    function create(name, matrix, info) {
        var _a = info || {}, assembly = _a.assembly, ncsId = _a.ncsId, hkl = _a.hkl, spgrOp = _a.spgrOp;
        var _hkl = hkl ? _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].clone(hkl) : _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].zero();
        spgrOp = Object(_mol_util__WEBPACK_IMPORTED_MODULE_2__[/* defaults */ "i"])(spgrOp, -1);
        ncsId = ncsId || '';
        var suffix = getSuffix(info);
        if (_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].isIdentity(matrix))
            return { name: name, assembly: assembly, matrix: matrix, inverse: _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].identity(), isIdentity: true, hkl: _hkl, spgrOp: spgrOp, ncsId: ncsId, suffix: suffix };
        if (!_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].isRotationAndTranslation(matrix, SymmetryOperator.RotationTranslationEpsilon))
            throw new Error("Symmetry operator (" + name + ") must be a composition of rotation and translation.");
        return { name: name, assembly: assembly, matrix: matrix, inverse: _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].invert(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].zero(), matrix), isIdentity: false, hkl: _hkl, spgrOp: spgrOp, ncsId: ncsId, suffix: suffix };
    }
    SymmetryOperator.create = create;
    function getSuffix(info) {
        if (!info)
            return '';
        if (info.assembly) {
            return "_" + info.assembly.operId;
        }
        if (typeof info.spgrOp !== 'undefined' && typeof info.hkl !== 'undefined' && info.spgrOp !== -1) {
            var _a = info.hkl, i = _a[0], j = _a[1], k = _a[2];
            return "-" + (info.spgrOp + 1) + "_" + (5 + i) + (5 + j) + (5 + k);
        }
        if (info.ncsId) {
            return "_" + info.ncsId;
        }
        return '';
    }
    function checkIfRotationAndTranslation(rot, offset) {
        var matrix = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].identity();
        for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 3; j++) {
                _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(matrix, i, j, _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat3 */ "b"].getValue(rot, i, j));
            }
        }
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setTranslation(matrix, offset);
        return _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].isRotationAndTranslation(matrix, SymmetryOperator.RotationTranslationEpsilon);
    }
    SymmetryOperator.checkIfRotationAndTranslation = checkIfRotationAndTranslation;
    function ofRotationAndOffset(name, rot, offset, ncsId) {
        var t = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].identity();
        for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 3; j++) {
                _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(t, i, j, _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat3 */ "b"].getValue(rot, i, j));
            }
        }
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setTranslation(t, offset);
        return create(name, t, { ncsId: ncsId });
    }
    SymmetryOperator.ofRotationAndOffset = ofRotationAndOffset;
    var _q1 = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].identity(), _q2 = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].zero(), _q3 = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].zero(), _axis = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].zero();
    function lerpFromIdentity(out, op, t) {
        var m = op.inverse;
        if (op.isIdentity)
            return _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].copy(out, m);
        var _t = 1 - t;
        // interpolate rotation
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getRotation(_q2, m);
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].slerp(_q2, _q1, _q2, _t);
        var angle = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].getAxisAngle(_axis, _q2);
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].fromRotation(out, angle, _axis);
        // interpolate translation
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 0, 3, _t * _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(m, 0, 3));
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 1, 3, _t * _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(m, 1, 3));
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 2, 3, _t * _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(m, 2, 3));
        return out;
    }
    SymmetryOperator.lerpFromIdentity = lerpFromIdentity;
    function slerp(out, src, tar, t) {
        if (Math.abs(t) <= 0.00001)
            return _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].copy(out, src);
        if (Math.abs(t - 1) <= 0.00001)
            return _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].copy(out, tar);
        // interpolate rotation
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getRotation(_q2, src);
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getRotation(_q3, tar);
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].slerp(_q3, _q2, _q3, t);
        var angle = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Quat */ "d"].getAxisAngle(_axis, _q3);
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].fromRotation(out, angle, _axis);
        // interpolate translation
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 0, 3, Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_1__[/* lerp */ "b"])(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(src, 0, 3), _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(tar, 0, 3), t));
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 1, 3, Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_1__[/* lerp */ "b"])(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(src, 1, 3), _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(tar, 1, 3), t));
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].setValue(out, 2, 3, Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_1__[/* lerp */ "b"])(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(src, 2, 3), _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].getValue(tar, 2, 3), t));
        return out;
    }
    SymmetryOperator.slerp = slerp;
    /**
     * Apply the 1st and then 2nd operator. ( = second.matrix * first.matrix).
     * Keep `name`, `assembly`, `ncsId`, `hkl` and `spgrOpId` properties from second.
     */
    function compose(first, second) {
        var matrix = _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].mul(_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Mat4 */ "c"].zero(), second.matrix, first.matrix);
        return create(second.name, matrix, second);
    }
    SymmetryOperator.compose = compose;
    function createMapping(operator, coords, radius) {
        var invariantPosition = SymmetryOperator.createCoordinateMapper(SymmetryOperator.Default, coords);
        var position = operator.isIdentity ? invariantPosition : SymmetryOperator.createCoordinateMapper(operator, coords);
        var _a = createProjections(operator, coords), x = _a.x, y = _a.y, z = _a.z;
        return { operator: operator, invariantPosition: invariantPosition, position: position, x: x, y: y, z: z, r: radius ? radius : _zeroRadius };
    }
    SymmetryOperator.createMapping = createMapping;
    function createCoordinateMapper(t, coords) {
        if (t.isIdentity)
            return identityPosition(coords);
        return generalPosition(t, coords);
    }
    SymmetryOperator.createCoordinateMapper = createCoordinateMapper;
})(SymmetryOperator || (SymmetryOperator = {}));

function _zeroRadius(i) { return 0; }
function createProjections(t, coords) {
    if (t.isIdentity)
        return { x: projectCoord(coords.x), y: projectCoord(coords.y), z: projectCoord(coords.z) };
    return { x: projectX(t, coords), y: projectY(t, coords), z: projectZ(t, coords) };
}
function projectCoord(xs) {
    return function (i) { return xs[i]; };
}
function isW1(m) {
    return m[3] === 0 && m[7] === 0 && m[11] === 0 && m[15] === 1;
}
function projectX(_a, _b) {
    var m = _a.matrix;
    var xs = _b.x, ys = _b.y, zs = _b.z;
    var xx = m[0], yy = m[4], zz = m[8], tx = m[12];
    if (isW1(m)) {
        // this should always be the case.
        return function (i) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + tx; };
    }
    return function (i) {
        var x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0;
        return (xx * x + yy * y + zz * z + tx) / w;
    };
}
function projectY(_a, _b) {
    var m = _a.matrix;
    var xs = _b.x, ys = _b.y, zs = _b.z;
    var xx = m[1], yy = m[5], zz = m[9], ty = m[13];
    if (isW1(m)) {
        // this should always be the case.
        return function (i) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + ty; };
    }
    return function (i) {
        var x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0;
        return (xx * x + yy * y + zz * z + ty) / w;
    };
}
function projectZ(_a, _b) {
    var m = _a.matrix;
    var xs = _b.x, ys = _b.y, zs = _b.z;
    var xx = m[2], yy = m[6], zz = m[10], tz = m[14];
    if (isW1(m)) {
        // this should always be the case.
        return function (i) { return xx * xs[i] + yy * ys[i] + zz * zs[i] + tz; };
    }
    return function (i) {
        var x = xs[i], y = ys[i], z = zs[i], w = (m[3] * x + m[7] * y + m[11] * z + m[15]) || 1.0;
        return (xx * x + yy * y + zz * z + tz) / w;
    };
}
function identityPosition(_a) {
    var x = _a.x, y = _a.y, z = _a.z;
    return function (i, s) {
        s[0] = x[i];
        s[1] = y[i];
        s[2] = z[i];
        return s;
    };
}
function generalPosition(_a, _b) {
    var m = _a.matrix;
    var xs = _b.x, ys = _b.y, zs = _b.z;
    if (isW1(m)) {
        // this should always be the case.
        return function (i, r) {
            var x = xs[i], y = ys[i], z = zs[i];
            r[0] = m[0] * x + m[4] * y + m[8] * z + m[12];
            r[1] = m[1] * x + m[5] * y + m[9] * z + m[13];
            r[2] = m[2] * x + m[6] * y + m[10] * z + m[14];
            return r;
        };
    }
    return function (i, r) {
        r[0] = xs[i];
        r[1] = ys[i];
        r[2] = zs[i];
        _linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].transformMat4(r, r, m);
        return r;
    };
}
//# sourceMappingURL=symmetry-operator.js.map

/***/ }),
/* 137 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _mat4__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(105);
/* harmony import */ var _3d__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(25);
/* harmony import */ var _interpolate__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(78);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/*
 * This code has been modified from https://github.com/toji/gl-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:
 */



function Vec3() {
    return Vec3.zero();
}
(function (Vec3) {
    function zero() {
        var out = [0.1, 0.0, 0.0];
        out[0] = 0;
        return out;
    }
    Vec3.zero = zero;
    function clone(a) {
        var out = zero();
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        return out;
    }
    Vec3.clone = clone;
    function hasNaN(a) {
        return isNaN(a[0]) || isNaN(a[1]) || isNaN(a[2]);
    }
    Vec3.hasNaN = hasNaN;
    function setNaN(out) {
        out[0] = NaN;
        out[1] = NaN;
        out[2] = NaN;
        return out;
    }
    Vec3.setNaN = setNaN;
    function fromObj(v) {
        return create(v.x, v.y, v.z);
    }
    Vec3.fromObj = fromObj;
    function toObj(v) {
        return { x: v[0], y: v[1], z: v[2] };
    }
    Vec3.toObj = toObj;
    function fromArray(v, array, offset) {
        v[0] = array[offset + 0];
        v[1] = array[offset + 1];
        v[2] = array[offset + 2];
        return v;
    }
    Vec3.fromArray = fromArray;
    function toArray(v, out, offset) {
        out[offset + 0] = v[0];
        out[offset + 1] = v[1];
        out[offset + 2] = v[2];
        return out;
    }
    Vec3.toArray = toArray;
    function create(x, y, z) {
        var out = zero();
        out[0] = x;
        out[1] = y;
        out[2] = z;
        return out;
    }
    Vec3.create = create;
    function ofArray(array) {
        var out = zero();
        out[0] = array[0];
        out[1] = array[1];
        out[2] = array[2];
        return out;
    }
    Vec3.ofArray = ofArray;
    function set(out, x, y, z) {
        out[0] = x;
        out[1] = y;
        out[2] = z;
        return out;
    }
    Vec3.set = set;
    function copy(out, a) {
        out[0] = a[0];
        out[1] = a[1];
        out[2] = a[2];
        return out;
    }
    Vec3.copy = copy;
    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;
    }
    Vec3.add = add;
    function sub(out, a, b) {
        out[0] = a[0] - b[0];
        out[1] = a[1] - b[1];
        out[2] = a[2] - b[2];
        return out;
    }
    Vec3.sub = sub;
    function mul(out, a, b) {
        out[0] = a[0] * b[0];
        out[1] = a[1] * b[1];
        out[2] = a[2] * b[2];
        return out;
    }
    Vec3.mul = mul;
    function div(out, a, b) {
        out[0] = a[0] / b[0];
        out[1] = a[1] / b[1];
        out[2] = a[2] / b[2];
        return out;
    }
    Vec3.div = div;
    function scale(out, a, b) {
        out[0] = a[0] * b;
        out[1] = a[1] * b;
        out[2] = a[2] * b;
        return out;
    }
    Vec3.scale = scale;
    /** Scales b, then adds a and b together */
    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;
    }
    Vec3.scaleAndAdd = scaleAndAdd;
    /** Scales b, then subtracts b from a */
    function scaleAndSub(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;
    }
    Vec3.scaleAndSub = scaleAndSub;
    /**
     * Math.round the components of a Vec3
     */
    function round(out, a) {
        out[0] = Math.round(a[0]);
        out[1] = Math.round(a[1]);
        out[2] = Math.round(a[2]);
        return out;
    }
    Vec3.round = round;
    /**
     * Math.ceil the components of a Vec3
     */
    function ceil(out, a) {
        out[0] = Math.ceil(a[0]);
        out[1] = Math.ceil(a[1]);
        out[2] = Math.ceil(a[2]);
        return out;
    }
    Vec3.ceil = ceil;
    /**
     * Math.floor the components of a Vec3
     */
    function floor(out, a) {
        out[0] = Math.floor(a[0]);
        out[1] = Math.floor(a[1]);
        out[2] = Math.floor(a[2]);
        return out;
    }
    Vec3.floor = floor;
    /**
     * Returns the minimum of two Vec3's
     */
    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;
    }
    Vec3.min = min;
    /**
     * Returns the maximum of two Vec3's
     */
    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;
    }
    Vec3.max = max;
    function distance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
        return Math.sqrt(x * x + y * y + z * z);
    }
    Vec3.distance = distance;
    function squaredDistance(a, b) {
        var x = b[0] - a[0], y = b[1] - a[1], z = b[2] - a[2];
        return x * x + y * y + z * z;
    }
    Vec3.squaredDistance = squaredDistance;
    function magnitude(a) {
        var x = a[0], y = a[1], z = a[2];
        return Math.sqrt(x * x + y * y + z * z);
    }
    Vec3.magnitude = magnitude;
    function squaredMagnitude(a) {
        var x = a[0], y = a[1], z = a[2];
        return x * x + y * y + z * z;
    }
    Vec3.squaredMagnitude = squaredMagnitude;
    function setMagnitude(out, a, l) {
        return Vec3.scale(out, Vec3.normalize(out, a), l);
    }
    Vec3.setMagnitude = setMagnitude;
    /**
     * Negates the components of a vec3
     */
    function negate(out, a) {
        out[0] = -a[0];
        out[1] = -a[1];
        out[2] = -a[2];
        return out;
    }
    Vec3.negate = negate;
    /**
     * Returns the inverse of the components of a Vec3
     */
    function inverse(out, a) {
        out[0] = 1.0 / a[0];
        out[1] = 1.0 / a[1];
        out[2] = 1.0 / a[2];
        return out;
    }
    Vec3.inverse = inverse;
    function normalize(out, a) {
        var x = a[0], y = a[1], z = a[2];
        var len = x * x + y * y + z * z;
        if (len > 0) {
            len = 1 / Math.sqrt(len);
            out[0] = a[0] * len;
            out[1] = a[1] * len;
            out[2] = a[2] * len;
        }
        return out;
    }
    Vec3.normalize = normalize;
    function dot(a, b) {
        return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
    }
    Vec3.dot = dot;
    function cross(out, a, b) {
        var ax = a[0], ay = a[1], az = a[2], bx = b[0], by = b[1], bz = b[2];
        out[0] = ay * bz - az * by;
        out[1] = az * bx - ax * bz;
        out[2] = ax * by - ay * bx;
        return out;
    }
    Vec3.cross = cross;
    /**
     * Performs a linear interpolation between two Vec3's
     */
    function lerp(out, a, b, t) {
        var ax = a[0], ay = a[1], az = a[2];
        out[0] = ax + t * (b[0] - ax);
        out[1] = ay + t * (b[1] - ay);
        out[2] = az + t * (b[2] - az);
        return out;
    }
    Vec3.lerp = lerp;
    var slerpRelVec = Vec3.zero();
    function slerp(out, a, b, t) {
        var dot = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* clamp */ "a"])(Vec3.dot(a, b), -1, 1);
        var theta = Math.acos(dot) * t;
        Vec3.scaleAndAdd(slerpRelVec, b, a, -dot);
        Vec3.normalize(slerpRelVec, slerpRelVec);
        return Vec3.add(out, Vec3.scale(out, a, Math.cos(theta)), Vec3.scale(slerpRelVec, slerpRelVec, Math.sin(theta)));
    }
    Vec3.slerp = slerp;
    /**
     * Performs a hermite interpolation with two control points
     */
    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;
    }
    Vec3.hermite = hermite;
    /**
     * Performs a bezier interpolation with two control points
     */
    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;
    }
    Vec3.bezier = bezier;
    function quadraticBezier(out, a, b, c, t) {
        out[0] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* quadraticBezier */ "c"])(a[0], b[0], c[0], t);
        out[1] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* quadraticBezier */ "c"])(a[1], b[1], c[1], t);
        out[2] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* quadraticBezier */ "c"])(a[2], b[2], c[2], t);
        return out;
    }
    Vec3.quadraticBezier = quadraticBezier;
    /**
     * Performs a spline interpolation with two control points and a tension parameter
     */
    function spline(out, a, b, c, d, t, tension) {
        out[0] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* spline */ "d"])(a[0], b[0], c[0], d[0], t, tension);
        out[1] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* spline */ "d"])(a[1], b[1], c[1], d[1], t, tension);
        out[2] = Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* spline */ "d"])(a[2], b[2], c[2], d[2], t, tension);
        return out;
    }
    Vec3.spline = spline;
    /**
     * Generates a random vector with the given scale
     */
    function random(out, scale) {
        var r = Math.random() * 2.0 * Math.PI;
        var z = (Math.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;
    }
    Vec3.random = random;
    /**
     * Transforms the Vec3 with a Mat4. 4th vector component is implicitly '1'
     */
    function transformMat4(out, a, m) {
        var x = a[0], y = a[1], z = a[2], w = 1 / ((m[3] * x + m[7] * y + m[11] * z + m[15]) || 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;
    }
    Vec3.transformMat4 = transformMat4;
    /**
     * Like `transformMat4` but with offsets into arrays
     */
    function transformMat4Offset(out, a, m, outO, aO, oM) {
        var x = a[0 + aO], y = a[1 + aO], z = a[2 + aO], w = 1 / ((m[3 + oM] * x + m[7 + oM] * y + m[11 + oM] * z + m[15 + oM]) || 1.0);
        out[0 + outO] = (m[0 + oM] * x + m[4 + oM] * y + m[8 + oM] * z + m[12 + oM]) * w;
        out[1 + outO] = (m[1 + oM] * x + m[5 + oM] * y + m[9 + oM] * z + m[13 + oM]) * w;
        out[2 + outO] = (m[2 + oM] * x + m[6 + oM] * y + m[10 + oM] * z + m[14 + oM]) * w;
        return out;
    }
    Vec3.transformMat4Offset = transformMat4Offset;
    /**
     * Transforms the Vec3 with a Mat3.
     */
    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;
    }
    Vec3.transformMat3 = transformMat3;
    /** Transforms the Vec3 with a quat */
    function transformQuat(out, a, q) {
        // benchmarks: http://jsperf.com/quaternion-transform-vec3-implementations
        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;
        return out;
    }
    Vec3.transformQuat = transformQuat;
    /** Computes the angle between 2 vectors, reports in radians. */
    function angle(a, b) {
        var theta = dot(a, b) / Math.sqrt(squaredMagnitude(a) * squaredMagnitude(b));
        return Math.acos(Object(_interpolate__WEBPACK_IMPORTED_MODULE_2__[/* clamp */ "a"])(theta, -1, 1)); // clamp to avoid numerical problems
    }
    Vec3.angle = angle;
    var tmp_dh_ab = zero();
    var tmp_dh_cb = zero();
    var tmp_dh_bc = zero();
    var tmp_dh_dc = zero();
    var tmp_dh_abc = zero();
    var tmp_dh_bcd = zero();
    var tmp_dh_cross = zero();
    /**
     * Computes the dihedral angles of 4 points, reports in radians.
     */
    function dihedralAngle(a, b, c, d) {
        sub(tmp_dh_ab, a, b);
        sub(tmp_dh_cb, c, b);
        sub(tmp_dh_bc, b, c);
        sub(tmp_dh_dc, d, c);
        cross(tmp_dh_abc, tmp_dh_ab, tmp_dh_cb);
        cross(tmp_dh_bcd, tmp_dh_bc, tmp_dh_dc);
        var _angle = angle(tmp_dh_abc, tmp_dh_bcd);
        cross(tmp_dh_cross, tmp_dh_abc, tmp_dh_bcd);
        return dot(tmp_dh_cb, tmp_dh_cross) > 0 ? _angle : -_angle;
    }
    Vec3.dihedralAngle = dihedralAngle;
    /**
     * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===)
     */
    function exactEquals(a, b) {
        return a[0] === b[0] && a[1] === b[1] && a[2] === b[2];
    }
    Vec3.exactEquals = exactEquals;
    /**
     * Returns whether or not the vectors have approximately the same elements in the same position.
     */
    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) <= _3d__WEBPACK_IMPORTED_MODULE_1__[/* EPSILON */ "a"] * Math.max(1.0, Math.abs(a0), Math.abs(b0)) &&
            Math.abs(a1 - b1) <= _3d__WEBPACK_IMPORTED_MODULE_1__[/* EPSILON */ "a"] * Math.max(1.0, Math.abs(a1), Math.abs(b1)) &&
            Math.abs(a2 - b2) <= _3d__WEBPACK_IMPORTED_MODULE_1__[/* EPSILON */ "a"] * Math.max(1.0, Math.abs(a2), Math.abs(b2)));
    }
    Vec3.equals = equals;
    var rotTemp = zero();
    function makeRotation(mat, a, b) {
        var by = angle(a, b);
        if (Math.abs(by) < 0.0001)
            return _mat4__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].setIdentity(mat);
        if (Math.abs(by - Math.PI) < _3d__WEBPACK_IMPORTED_MODULE_1__[/* EPSILON */ "a"]) {
            // here, axis can be [0,0,0] but the rotation is a simple flip
            return _mat4__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].fromScaling(mat, Vec3.negUnit);
        }
        var axis = cross(rotTemp, a, b);
        return _mat4__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].fromRotation(mat, by, axis);
    }
    Vec3.makeRotation = makeRotation;
    function isZero(v) {
        return v[0] === 0 && v[1] === 0 && v[2] === 0;
    }
    Vec3.isZero = isZero;
    /** Project `point` onto `vector` starting from `origin` */
    function projectPointOnVector(out, point, vector, origin) {
        sub(out, copy(out, point), origin);
        var scalar = dot(vector, out) / squaredMagnitude(vector);
        return add(out, scale(out, copy(out, vector), scalar), origin);
    }
    Vec3.projectPointOnVector = projectPointOnVector;
    function projectOnVector(out, p, vector) {
        var scalar = dot(vector, p) / squaredMagnitude(vector);
        return scale(out, vector, scalar);
    }
    Vec3.projectOnVector = projectOnVector;
    var tmpProject = Vec3();
    function projectOnPlane(out, p, normal) {
        projectOnVector(tmpProject, p, normal);
        return sub(out, p, tmpProject);
    }
    Vec3.projectOnPlane = projectOnPlane;
    /** Get a vector that is similar to `b` but orthogonal to `a` */
    function orthogonalize(out, a, b) {
        return normalize(out, cross(out, cross(out, a, b), a));
    }
    Vec3.orthogonalize = orthogonalize;
    /**
     * Get a vector like `a` that point into the same general direction as `b`,
     * i.e. where the dot product is > 0
     */
    function matchDirection(out, a, b) {
        if (Vec3.dot(a, b) > 0)
            Vec3.copy(out, a);
        else
            Vec3.negate(out, Vec3.copy(out, a));
        return out;
    }
    Vec3.matchDirection = matchDirection;
    var triangleNormalTmpAB = zero();
    var triangleNormalTmpAC = zero();
    /** Calculate normal for the triangle defined by `a`, `b` and `c` */
    function triangleNormal(out, a, b, c) {
        sub(triangleNormalTmpAB, b, a);
        sub(triangleNormalTmpAC, c, a);
        return normalize(out, cross(out, triangleNormalTmpAB, triangleNormalTmpAC));
    }
    Vec3.triangleNormal = triangleNormal;
    function toString(a, precision) {
        return "[" + a[0].toPrecision(precision) + " " + a[1].toPrecision(precision) + " " + a[2].toPrecision(precision) + "]";
    }
    Vec3.toString = toString;
    Vec3.origin = Vec3.create(0, 0, 0);
    Vec3.unit = Vec3.create(1, 1, 1);
    Vec3.negUnit = Vec3.create(-1, -1, -1);
    Vec3.unitX = Vec3.create(1, 0, 0);
    Vec3.unitY = Vec3.create(0, 1, 0);
    Vec3.unitZ = Vec3.create(0, 0, 1);
})(Vec3 || (Vec3 = {}));
/* harmony default export */ __webpack_exports__["a"] = (Vec3);
//# sourceMappingURL=vec3.js.map

/***/ }),
/* 138 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Volume; });
/* harmony import */ var _grid__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(249);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(126);
/* harmony import */ var _mol_model_formats_volume_cube__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(354);
/* harmony import */ var _mol_math_linear_algebra_3d_common__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(82);
/* harmony import */ var _custom_property__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(65);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var Volume;
(function (Volume) {
    var IsoValue;
    (function (IsoValue) {
        function areSame(a, b, stats) {
            return Object(_mol_math_linear_algebra_3d_common__WEBPACK_IMPORTED_MODULE_6__[/* equalEps */ "b"])(toAbsolute(a, stats).absoluteValue, toAbsolute(b, stats).absoluteValue, stats.sigma / 100);
        }
        IsoValue.areSame = areSame;
        function absolute(value) { return { kind: 'absolute', absoluteValue: value }; }
        IsoValue.absolute = absolute;
        function relative(value) { return { kind: 'relative', relativeValue: value }; }
        IsoValue.relative = relative;
        function calcAbsolute(stats, relativeValue) {
            return relativeValue * stats.sigma + stats.mean;
        }
        IsoValue.calcAbsolute = calcAbsolute;
        function calcRelative(stats, absoluteValue) {
            return stats.sigma === 0 ? 0 : ((absoluteValue - stats.mean) / stats.sigma);
        }
        IsoValue.calcRelative = calcRelative;
        function toAbsolute(value, stats) {
            return value.kind === 'absolute' ? value : { kind: 'absolute', absoluteValue: IsoValue.calcAbsolute(stats, value.relativeValue) };
        }
        IsoValue.toAbsolute = toAbsolute;
        function toRelative(value, stats) {
            return value.kind === 'relative' ? value : { kind: 'relative', relativeValue: IsoValue.calcRelative(stats, value.absoluteValue) };
        }
        IsoValue.toRelative = toRelative;
        function toString(value) {
            return value.kind === 'relative'
                ? value.relativeValue.toFixed(2) + " \u03C3"
                : "" + value.absoluteValue.toPrecision(4);
        }
        IsoValue.toString = toString;
    })(IsoValue = Volume.IsoValue || (Volume.IsoValue = {}));
    Volume.One = {
        label: '',
        grid: _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].One,
        sourceData: { kind: '', name: '', data: {} },
        customProperties: new _custom_property__WEBPACK_IMPORTED_MODULE_7__["CustomProperties"](),
        _propertyData: Object.create(null),
    };
    function areEquivalent(volA, volB) {
        return _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].areEquivalent(volA.grid, volB.grid);
    }
    Volume.areEquivalent = areEquivalent;
    function isEmpty(vol) {
        return _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].isEmpty(vol.grid);
    }
    Volume.isEmpty = isEmpty;
    function isOrbitals(volume) {
        if (!_mol_model_formats_volume_cube__WEBPACK_IMPORTED_MODULE_5__[/* CubeFormat */ "a"].is(volume.sourceData))
            return false;
        return volume.sourceData.data.header.orbitals;
    }
    Volume.isOrbitals = isOrbitals;
    function Loci(volume) { return { kind: 'volume-loci', volume: volume }; }
    Volume.Loci = Loci;
    function isLoci(x) { return !!x && x.kind === 'volume-loci'; }
    Volume.isLoci = isLoci;
    function areLociEqual(a, b) { return a.volume === b.volume; }
    Volume.areLociEqual = areLociEqual;
    function isLociEmpty(loci) { return _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].isEmpty(loci.volume.grid); }
    Volume.isLociEmpty = isLociEmpty;
    function getBoundingSphere(volume, boundingSphere) {
        if (!boundingSphere)
            boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"])();
        var transform = _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].getGridToCartesianTransform(volume.grid);
        var _a = volume.grid.cells.space.dimensions, x = _a[0], y = _a[1], z = _a[2];
        var cpA = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(0, 0, 0);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpA, cpA, transform);
        var cpB = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(x, y, z);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpB, cpB, transform);
        var cpC = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(x, 0, 0);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpC, cpC, transform);
        var cpD = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(0, y, z);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpD, cpC, transform);
        var cpE = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(0, 0, z);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpE, cpE, transform);
        var cpF = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(x, 0, z);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpF, cpF, transform);
        var cpG = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(x, y, 0);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpG, cpG, transform);
        var cpH = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(0, y, 0);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(cpH, cpH, transform);
        var center = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])();
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].add(center, cpA, cpB);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].scale(center, center, 0.5);
        var d = Math.max(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].distance(cpA, cpB), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].distance(cpC, cpD));
        _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].set(boundingSphere, center, d / 2);
        _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].setExtrema(boundingSphere, [cpA, cpB, cpC, cpD, cpE, cpF, cpG, cpH]);
        return boundingSphere;
    }
    Volume.getBoundingSphere = getBoundingSphere;
    var Isosurface;
    (function (Isosurface) {
        function Loci(volume, isoValue) { return { kind: 'isosurface-loci', volume: volume, isoValue: isoValue }; }
        Isosurface.Loci = Loci;
        function isLoci(x) { return !!x && x.kind === 'isosurface-loci'; }
        Isosurface.isLoci = isLoci;
        function areLociEqual(a, b) { return a.volume === b.volume && Volume.IsoValue.areSame(a.isoValue, b.isoValue, a.volume.grid.stats); }
        Isosurface.areLociEqual = areLociEqual;
        function isLociEmpty(loci) { return loci.volume.grid.cells.data.length === 0; }
        Isosurface.isLociEmpty = isLociEmpty;
        function getBoundingSphere(volume, isoValue, boundingSphere) {
            // TODO get bounding sphere for subgrid with values >= isoValue
            return Volume.getBoundingSphere(volume, boundingSphere);
        }
        Isosurface.getBoundingSphere = getBoundingSphere;
    })(Isosurface = Volume.Isosurface || (Volume.Isosurface = {}));
    var Cell;
    (function (Cell) {
        function Loci(volume, indices) { return { kind: 'cell-loci', volume: volume, indices: indices }; }
        Cell.Loci = Loci;
        function isLoci(x) { return !!x && x.kind === 'cell-loci'; }
        Cell.isLoci = isLoci;
        function areLociEqual(a, b) { return a.volume === b.volume && _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].areEqual(a.indices, b.indices); }
        Cell.areLociEqual = areLociEqual;
        function isLociEmpty(loci) { return _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(loci.indices) === 0; }
        Cell.isLociEmpty = isLociEmpty;
        var boundaryHelper = new _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_4__[/* BoundaryHelper */ "a"]('98');
        var tmpBoundaryPos = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])();
        function getBoundingSphere(volume, indices, boundingSphere) {
            boundaryHelper.reset();
            var transform = _grid__WEBPACK_IMPORTED_MODULE_0__[/* Grid */ "a"].getGridToCartesianTransform(volume.grid);
            var getCoords = volume.grid.cells.space.getCoords;
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                var o = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i);
                getCoords(o, tmpBoundaryPos);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(tmpBoundaryPos, tmpBoundaryPos, transform);
                boundaryHelper.includePosition(tmpBoundaryPos);
            }
            boundaryHelper.finishedIncludeStep();
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                var o = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i);
                getCoords(o, tmpBoundaryPos);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].transformMat4(tmpBoundaryPos, tmpBoundaryPos, transform);
                boundaryHelper.radiusPosition(tmpBoundaryPos);
            }
            var bs = boundaryHelper.getSphere(boundingSphere);
            return _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].expand(bs, bs, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Mat4"].getMaxScaleOnAxis(transform) * 10);
        }
        Cell.getBoundingSphere = getBoundingSphere;
    })(Cell = Volume.Cell || (Volume.Cell = {}));
})(Volume || (Volume = {}));
//# sourceMappingURL=volume.js.map

/***/ }),
/* 139 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Observable", function() { return /* reexport */ Observable["a" /* Observable */]; });
__webpack_require__.d(__webpack_exports__, "ConnectableObservable", function() { return /* reexport */ ConnectableObservable["a" /* ConnectableObservable */]; });
__webpack_require__.d(__webpack_exports__, "GroupedObservable", function() { return /* reexport */ groupBy["a" /* GroupedObservable */]; });
__webpack_require__.d(__webpack_exports__, "observable", function() { return /* reexport */ observable["a" /* observable */]; });
__webpack_require__.d(__webpack_exports__, "Subject", function() { return /* reexport */ Subject["a" /* Subject */]; });
__webpack_require__.d(__webpack_exports__, "BehaviorSubject", function() { return /* reexport */ BehaviorSubject["a" /* BehaviorSubject */]; });
__webpack_require__.d(__webpack_exports__, "ReplaySubject", function() { return /* reexport */ ReplaySubject["a" /* ReplaySubject */]; });
__webpack_require__.d(__webpack_exports__, "AsyncSubject", function() { return /* reexport */ AsyncSubject["a" /* AsyncSubject */]; });
__webpack_require__.d(__webpack_exports__, "asapScheduler", function() { return /* reexport */ asap["a" /* asap */]; });
__webpack_require__.d(__webpack_exports__, "asyncScheduler", function() { return /* reexport */ scheduler_async["a" /* async */]; });
__webpack_require__.d(__webpack_exports__, "queueScheduler", function() { return /* reexport */ queue["a" /* queue */]; });
__webpack_require__.d(__webpack_exports__, "animationFrameScheduler", function() { return /* reexport */ animationFrame; });
__webpack_require__.d(__webpack_exports__, "VirtualTimeScheduler", function() { return /* reexport */ VirtualTimeScheduler_VirtualTimeScheduler; });
__webpack_require__.d(__webpack_exports__, "VirtualAction", function() { return /* reexport */ VirtualTimeScheduler_VirtualAction; });
__webpack_require__.d(__webpack_exports__, "Scheduler", function() { return /* reexport */ Scheduler["a" /* Scheduler */]; });
__webpack_require__.d(__webpack_exports__, "Subscription", function() { return /* reexport */ Subscription["a" /* Subscription */]; });
__webpack_require__.d(__webpack_exports__, "Subscriber", function() { return /* reexport */ Subscriber["a" /* Subscriber */]; });
__webpack_require__.d(__webpack_exports__, "Notification", function() { return /* reexport */ Notification["a" /* Notification */]; });
__webpack_require__.d(__webpack_exports__, "NotificationKind", function() { return /* reexport */ Notification["b" /* NotificationKind */]; });
__webpack_require__.d(__webpack_exports__, "pipe", function() { return /* reexport */ pipe["a" /* pipe */]; });
__webpack_require__.d(__webpack_exports__, "noop", function() { return /* reexport */ noop["a" /* noop */]; });
__webpack_require__.d(__webpack_exports__, "identity", function() { return /* reexport */ identity["a" /* identity */]; });
__webpack_require__.d(__webpack_exports__, "isObservable", function() { return /* reexport */ isObservable; });
__webpack_require__.d(__webpack_exports__, "ArgumentOutOfRangeError", function() { return /* reexport */ ArgumentOutOfRangeError["a" /* ArgumentOutOfRangeError */]; });
__webpack_require__.d(__webpack_exports__, "EmptyError", function() { return /* reexport */ EmptyError["a" /* EmptyError */]; });
__webpack_require__.d(__webpack_exports__, "ObjectUnsubscribedError", function() { return /* reexport */ ObjectUnsubscribedError["a" /* ObjectUnsubscribedError */]; });
__webpack_require__.d(__webpack_exports__, "UnsubscriptionError", function() { return /* reexport */ UnsubscriptionError["a" /* UnsubscriptionError */]; });
__webpack_require__.d(__webpack_exports__, "TimeoutError", function() { return /* reexport */ TimeoutError["a" /* TimeoutError */]; });
__webpack_require__.d(__webpack_exports__, "bindCallback", function() { return /* reexport */ bindCallback; });
__webpack_require__.d(__webpack_exports__, "bindNodeCallback", function() { return /* reexport */ bindNodeCallback; });
__webpack_require__.d(__webpack_exports__, "combineLatest", function() { return /* reexport */ combineLatest["b" /* combineLatest */]; });
__webpack_require__.d(__webpack_exports__, "concat", function() { return /* reexport */ concat["a" /* concat */]; });
__webpack_require__.d(__webpack_exports__, "defer", function() { return /* reexport */ defer["a" /* defer */]; });
__webpack_require__.d(__webpack_exports__, "empty", function() { return /* reexport */ empty["b" /* empty */]; });
__webpack_require__.d(__webpack_exports__, "forkJoin", function() { return /* reexport */ forkJoin; });
__webpack_require__.d(__webpack_exports__, "from", function() { return /* reexport */ from["a" /* from */]; });
__webpack_require__.d(__webpack_exports__, "fromEvent", function() { return /* reexport */ fromEvent; });
__webpack_require__.d(__webpack_exports__, "fromEventPattern", function() { return /* reexport */ fromEventPattern; });
__webpack_require__.d(__webpack_exports__, "generate", function() { return /* reexport */ generate; });
__webpack_require__.d(__webpack_exports__, "iif", function() { return /* reexport */ iif; });
__webpack_require__.d(__webpack_exports__, "interval", function() { return /* reexport */ interval; });
__webpack_require__.d(__webpack_exports__, "merge", function() { return /* reexport */ merge["a" /* merge */]; });
__webpack_require__.d(__webpack_exports__, "never", function() { return /* reexport */ never; });
__webpack_require__.d(__webpack_exports__, "of", function() { return /* reexport */ of["a" /* of */]; });
__webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return /* reexport */ onErrorResumeNext; });
__webpack_require__.d(__webpack_exports__, "pairs", function() { return /* reexport */ pairs; });
__webpack_require__.d(__webpack_exports__, "partition", function() { return /* reexport */ partition; });
__webpack_require__.d(__webpack_exports__, "race", function() { return /* reexport */ race["a" /* race */]; });
__webpack_require__.d(__webpack_exports__, "range", function() { return /* reexport */ range; });
__webpack_require__.d(__webpack_exports__, "throwError", function() { return /* reexport */ throwError["a" /* throwError */]; });
__webpack_require__.d(__webpack_exports__, "timer", function() { return /* reexport */ timer["a" /* timer */]; });
__webpack_require__.d(__webpack_exports__, "using", function() { return /* reexport */ using; });
__webpack_require__.d(__webpack_exports__, "zip", function() { return /* reexport */ zip["b" /* zip */]; });
__webpack_require__.d(__webpack_exports__, "scheduled", function() { return /* reexport */ scheduled["a" /* scheduled */]; });
__webpack_require__.d(__webpack_exports__, "EMPTY", function() { return /* reexport */ empty["a" /* EMPTY */]; });
__webpack_require__.d(__webpack_exports__, "NEVER", function() { return /* reexport */ NEVER; });
__webpack_require__.d(__webpack_exports__, "config", function() { return /* reexport */ config["a" /* config */]; });

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Observable.js + 1 modules
var Observable = __webpack_require__(44);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js
var ConnectableObservable = __webpack_require__(346);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/groupBy.js
var groupBy = __webpack_require__(336);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/observable.js
var observable = __webpack_require__(203);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/BehaviorSubject.js
var BehaviorSubject = __webpack_require__(279);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/ReplaySubject.js
var ReplaySubject = __webpack_require__(297);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/AsyncSubject.js
var AsyncSubject = __webpack_require__(226);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/asap.js + 3 modules
var asap = __webpack_require__(312);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/async.js
var scheduler_async = __webpack_require__(103);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/queue.js + 2 modules
var queue = __webpack_require__(351);

// EXTERNAL MODULE: ./node_modules/rxjs/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(21);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules
var AsyncAction = __webpack_require__(229);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AnimationFrameAction.js
/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */


var AnimationFrameAction_AnimationFrameAction = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AnimationFrameAction, _super);
    function AnimationFrameAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (delay !== null && delay > 0) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        scheduler.actions.push(this);
        return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); }));
    };
    AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
            return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
        }
        if (scheduler.actions.length === 0) {
            cancelAnimationFrame(id);
            scheduler.scheduled = undefined;
        }
        return undefined;
    };
    return AnimationFrameAction;
}(AsyncAction["a" /* AsyncAction */]));

//# sourceMappingURL=AnimationFrameAction.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js
var AsyncScheduler = __webpack_require__(225);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AnimationFrameScheduler.js
/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */


var AnimationFrameScheduler_AnimationFrameScheduler = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AnimationFrameScheduler, _super);
    function AnimationFrameScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AnimationFrameScheduler.prototype.flush = function (action) {
        this.active = true;
        this.scheduled = undefined;
        var actions = this.actions;
        var error;
        var index = -1;
        var count = actions.length;
        action = action || actions.shift();
        do {
            if (error = action.execute(action.state, action.delay)) {
                break;
            }
        } while (++index < count && (action = actions.shift()));
        this.active = false;
        if (error) {
            while (++index < count && (action = actions.shift())) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AnimationFrameScheduler;
}(AsyncScheduler["a" /* AsyncScheduler */]));

//# sourceMappingURL=AnimationFrameScheduler.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/animationFrame.js
/** PURE_IMPORTS_START _AnimationFrameAction,_AnimationFrameScheduler PURE_IMPORTS_END */


var animationFrame = /*@__PURE__*/ new AnimationFrameScheduler_AnimationFrameScheduler(AnimationFrameAction_AnimationFrameAction);
//# sourceMappingURL=animationFrame.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/VirtualTimeScheduler.js
/** PURE_IMPORTS_START tslib,_AsyncAction,_AsyncScheduler PURE_IMPORTS_END */



var VirtualTimeScheduler_VirtualTimeScheduler = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](VirtualTimeScheduler, _super);
    function VirtualTimeScheduler(SchedulerAction, maxFrames) {
        if (SchedulerAction === void 0) {
            SchedulerAction = VirtualTimeScheduler_VirtualAction;
        }
        if (maxFrames === void 0) {
            maxFrames = Number.POSITIVE_INFINITY;
        }
        var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this;
        _this.maxFrames = maxFrames;
        _this.frame = 0;
        _this.index = -1;
        return _this;
    }
    VirtualTimeScheduler.prototype.flush = function () {
        var _a = this, actions = _a.actions, maxFrames = _a.maxFrames;
        var error, action;
        while ((action = actions[0]) && action.delay <= maxFrames) {
            actions.shift();
            this.frame = action.delay;
            if (error = action.execute(action.state, action.delay)) {
                break;
            }
        }
        if (error) {
            while (action = actions.shift()) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    VirtualTimeScheduler.frameTimeFactor = 10;
    return VirtualTimeScheduler;
}(AsyncScheduler["a" /* AsyncScheduler */]));

var VirtualTimeScheduler_VirtualAction = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](VirtualAction, _super);
    function VirtualAction(scheduler, work, index) {
        if (index === void 0) {
            index = scheduler.index += 1;
        }
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        _this.index = index;
        _this.active = true;
        _this.index = scheduler.index = index;
        return _this;
    }
    VirtualAction.prototype.schedule = function (state, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (!this.id) {
            return _super.prototype.schedule.call(this, state, delay);
        }
        this.active = false;
        var action = new VirtualAction(this.scheduler, this.work);
        this.add(action);
        return action.schedule(state, delay);
    };
    VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        this.delay = scheduler.frame + delay;
        var actions = scheduler.actions;
        actions.push(this);
        actions.sort(VirtualAction.sortActions);
        return true;
    };
    VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        return undefined;
    };
    VirtualAction.prototype._execute = function (state, delay) {
        if (this.active === true) {
            return _super.prototype._execute.call(this, state, delay);
        }
    };
    VirtualAction.sortActions = function (a, b) {
        if (a.delay === b.delay) {
            if (a.index === b.index) {
                return 0;
            }
            else if (a.index > b.index) {
                return 1;
            }
            else {
                return -1;
            }
        }
        else if (a.delay > b.delay) {
            return 1;
        }
        else {
            return -1;
        }
    };
    return VirtualAction;
}(AsyncAction["a" /* AsyncAction */]));

//# sourceMappingURL=VirtualTimeScheduler.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Scheduler.js
var Scheduler = __webpack_require__(321);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscription.js
var Subscription = __webpack_require__(70);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscriber.js
var Subscriber = __webpack_require__(35);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Notification.js
var Notification = __webpack_require__(190);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/pipe.js
var pipe = __webpack_require__(273);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/noop.js
var noop = __webpack_require__(199);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/identity.js
var identity = __webpack_require__(181);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/isObservable.js
/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */

function isObservable(obj) {
    return !!obj && (obj instanceof Observable["a" /* Observable */] || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function'));
}
//# sourceMappingURL=isObservable.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/ArgumentOutOfRangeError.js
var ArgumentOutOfRangeError = __webpack_require__(214);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/EmptyError.js
var EmptyError = __webpack_require__(220);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/ObjectUnsubscribedError.js
var ObjectUnsubscribedError = __webpack_require__(208);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/UnsubscriptionError.js
var UnsubscriptionError = __webpack_require__(278);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/TimeoutError.js
var TimeoutError = __webpack_require__(349);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/map.js
var map = __webpack_require__(116);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/canReportError.js
var canReportError = __webpack_require__(302);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isArray.js
var isArray = __webpack_require__(100);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isScheduler.js
var isScheduler = __webpack_require__(122);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/bindCallback.js
/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isArray,_util_isScheduler PURE_IMPORTS_END */






function bindCallback(callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (Object(isScheduler["a" /* isScheduler */])(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(map["a" /* map */])(function (args) { return Object(isArray["a" /* isArray */])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
            };
        }
    }
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var context = this;
        var subject;
        var params = {
            context: context,
            subject: subject,
            callbackFunc: callbackFunc,
            scheduler: scheduler,
        };
        return new Observable["a" /* Observable */](function (subscriber) {
            if (!scheduler) {
                if (!subject) {
                    subject = new AsyncSubject["a" /* AsyncSubject */]();
                    var handler = function () {
                        var innerArgs = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            innerArgs[_i] = arguments[_i];
                        }
                        subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
                        subject.complete();
                    };
                    try {
                        callbackFunc.apply(context, args.concat([handler]));
                    }
                    catch (err) {
                        if (Object(canReportError["a" /* canReportError */])(subject)) {
                            subject.error(err);
                        }
                        else {
                            console.warn(err);
                        }
                    }
                }
                return subject.subscribe(subscriber);
            }
            else {
                var state = {
                    args: args, subscriber: subscriber, params: params,
                };
                return scheduler.schedule(dispatch, 0, state);
            }
        });
    };
}
function dispatch(state) {
    var _this = this;
    var self = this;
    var args = state.args, subscriber = state.subscriber, params = state.params;
    var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler;
    var subject = params.subject;
    if (!subject) {
        subject = params.subject = new AsyncSubject["a" /* AsyncSubject */]();
        var handler = function () {
            var innerArgs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                innerArgs[_i] = arguments[_i];
            }
            var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
            _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject }));
        };
        try {
            callbackFunc.apply(context, args.concat([handler]));
        }
        catch (err) {
            subject.error(err);
        }
    }
    this.add(subject.subscribe(subscriber));
}
function dispatchNext(state) {
    var value = state.value, subject = state.subject;
    subject.next(value);
    subject.complete();
}
function dispatchError(state) {
    var err = state.err, subject = state.subject;
    subject.error(err);
}
//# sourceMappingURL=bindCallback.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/bindNodeCallback.js
/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isScheduler,_util_isArray PURE_IMPORTS_END */






function bindNodeCallback(callbackFunc, resultSelector, scheduler) {
    if (resultSelector) {
        if (Object(isScheduler["a" /* isScheduler */])(resultSelector)) {
            scheduler = resultSelector;
        }
        else {
            return function () {
                var args = [];
                for (var _i = 0; _i < arguments.length; _i++) {
                    args[_i] = arguments[_i];
                }
                return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(Object(map["a" /* map */])(function (args) { return Object(isArray["a" /* isArray */])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
            };
        }
    }
    return function () {
        var args = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            args[_i] = arguments[_i];
        }
        var params = {
            subject: undefined,
            args: args,
            callbackFunc: callbackFunc,
            scheduler: scheduler,
            context: this,
        };
        return new Observable["a" /* Observable */](function (subscriber) {
            var context = params.context;
            var subject = params.subject;
            if (!scheduler) {
                if (!subject) {
                    subject = params.subject = new AsyncSubject["a" /* AsyncSubject */]();
                    var handler = function () {
                        var innerArgs = [];
                        for (var _i = 0; _i < arguments.length; _i++) {
                            innerArgs[_i] = arguments[_i];
                        }
                        var err = innerArgs.shift();
                        if (err) {
                            subject.error(err);
                            return;
                        }
                        subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs);
                        subject.complete();
                    };
                    try {
                        callbackFunc.apply(context, args.concat([handler]));
                    }
                    catch (err) {
                        if (Object(canReportError["a" /* canReportError */])(subject)) {
                            subject.error(err);
                        }
                        else {
                            console.warn(err);
                        }
                    }
                }
                return subject.subscribe(subscriber);
            }
            else {
                return scheduler.schedule(bindNodeCallback_dispatch, 0, { params: params, subscriber: subscriber, context: context });
            }
        });
    };
}
function bindNodeCallback_dispatch(state) {
    var _this = this;
    var params = state.params, subscriber = state.subscriber, context = state.context;
    var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler;
    var subject = params.subject;
    if (!subject) {
        subject = params.subject = new AsyncSubject["a" /* AsyncSubject */]();
        var handler = function () {
            var innerArgs = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                innerArgs[_i] = arguments[_i];
            }
            var err = innerArgs.shift();
            if (err) {
                _this.add(scheduler.schedule(bindNodeCallback_dispatchError, 0, { err: err, subject: subject }));
            }
            else {
                var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs;
                _this.add(scheduler.schedule(bindNodeCallback_dispatchNext, 0, { value: value, subject: subject }));
            }
        };
        try {
            callbackFunc.apply(context, args.concat([handler]));
        }
        catch (err) {
            this.add(scheduler.schedule(bindNodeCallback_dispatchError, 0, { err: err, subject: subject }));
        }
    }
    this.add(subject.subscribe(subscriber));
}
function bindNodeCallback_dispatchNext(arg) {
    var value = arg.value, subject = arg.subject;
    subject.next(value);
    subject.complete();
}
function bindNodeCallback_dispatchError(arg) {
    var err = arg.err, subject = arg.subject;
    subject.error(err);
}
//# sourceMappingURL=bindNodeCallback.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/combineLatest.js
var combineLatest = __webpack_require__(294);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/concat.js
var concat = __webpack_require__(240);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/defer.js
var defer = __webpack_require__(298);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/empty.js
var empty = __webpack_require__(133);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isObject.js
var isObject = __webpack_require__(301);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/from.js
var from = __webpack_require__(140);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/forkJoin.js
/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */





function forkJoin() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    if (sources.length === 1) {
        var first_1 = sources[0];
        if (Object(isArray["a" /* isArray */])(first_1)) {
            return forkJoinInternal(first_1, null);
        }
        if (Object(isObject["a" /* isObject */])(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) {
            var keys = Object.keys(first_1);
            return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys);
        }
    }
    if (typeof sources[sources.length - 1] === 'function') {
        var resultSelector_1 = sources.pop();
        sources = (sources.length === 1 && Object(isArray["a" /* isArray */])(sources[0])) ? sources[0] : sources;
        return forkJoinInternal(sources, null).pipe(Object(map["a" /* map */])(function (args) { return resultSelector_1.apply(void 0, args); }));
    }
    return forkJoinInternal(sources, null);
}
function forkJoinInternal(sources, keys) {
    return new Observable["a" /* Observable */](function (subscriber) {
        var len = sources.length;
        if (len === 0) {
            subscriber.complete();
            return;
        }
        var values = new Array(len);
        var completed = 0;
        var emitted = 0;
        var _loop_1 = function (i) {
            var source = Object(from["a" /* from */])(sources[i]);
            var hasValue = false;
            subscriber.add(source.subscribe({
                next: function (value) {
                    if (!hasValue) {
                        hasValue = true;
                        emitted++;
                    }
                    values[i] = value;
                },
                error: function (err) { return subscriber.error(err); },
                complete: function () {
                    completed++;
                    if (completed === len || !hasValue) {
                        if (emitted === len) {
                            subscriber.next(keys ?
                                keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) :
                                values);
                        }
                        subscriber.complete();
                    }
                }
            }));
        };
        for (var i = 0; i < len; i++) {
            _loop_1(i);
        }
    });
}
//# sourceMappingURL=forkJoin.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isFunction.js
var isFunction = __webpack_require__(215);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/fromEvent.js
/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */




var fromEvent_toString = /*@__PURE__*/ (function () { return Object.prototype.toString; })();
function fromEvent(target, eventName, options, resultSelector) {
    if (Object(isFunction["a" /* isFunction */])(options)) {
        resultSelector = options;
        options = undefined;
    }
    if (resultSelector) {
        return fromEvent(target, eventName, options).pipe(Object(map["a" /* map */])(function (args) { return Object(isArray["a" /* isArray */])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        function handler(e) {
            if (arguments.length > 1) {
                subscriber.next(Array.prototype.slice.call(arguments));
            }
            else {
                subscriber.next(e);
            }
        }
        setupSubscription(target, eventName, handler, subscriber, options);
    });
}
function setupSubscription(sourceObj, eventName, handler, subscriber, options) {
    var unsubscribe;
    if (isEventTarget(sourceObj)) {
        var source_1 = sourceObj;
        sourceObj.addEventListener(eventName, handler, options);
        unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); };
    }
    else if (isJQueryStyleEventEmitter(sourceObj)) {
        var source_2 = sourceObj;
        sourceObj.on(eventName, handler);
        unsubscribe = function () { return source_2.off(eventName, handler); };
    }
    else if (isNodeStyleEventEmitter(sourceObj)) {
        var source_3 = sourceObj;
        sourceObj.addListener(eventName, handler);
        unsubscribe = function () { return source_3.removeListener(eventName, handler); };
    }
    else if (sourceObj && sourceObj.length) {
        for (var i = 0, len = sourceObj.length; i < len; i++) {
            setupSubscription(sourceObj[i], eventName, handler, subscriber, options);
        }
    }
    else {
        throw new TypeError('Invalid event target');
    }
    subscriber.add(unsubscribe);
}
function isNodeStyleEventEmitter(sourceObj) {
    return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function';
}
function isJQueryStyleEventEmitter(sourceObj) {
    return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function';
}
function isEventTarget(sourceObj) {
    return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function';
}
//# sourceMappingURL=fromEvent.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/fromEventPattern.js
/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */




function fromEventPattern(addHandler, removeHandler, resultSelector) {
    if (resultSelector) {
        return fromEventPattern(addHandler, removeHandler).pipe(Object(map["a" /* map */])(function (args) { return Object(isArray["a" /* isArray */])(args) ? resultSelector.apply(void 0, args) : resultSelector(args); }));
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        var handler = function () {
            var e = [];
            for (var _i = 0; _i < arguments.length; _i++) {
                e[_i] = arguments[_i];
            }
            return subscriber.next(e.length === 1 ? e[0] : e);
        };
        var retValue;
        try {
            retValue = addHandler(handler);
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
        if (!Object(isFunction["a" /* isFunction */])(removeHandler)) {
            return undefined;
        }
        return function () { return removeHandler(handler, retValue); };
    });
}
//# sourceMappingURL=fromEventPattern.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/generate.js
/** PURE_IMPORTS_START _Observable,_util_identity,_util_isScheduler PURE_IMPORTS_END */



function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) {
    var resultSelector;
    var initialState;
    if (arguments.length == 1) {
        var options = initialStateOrOptions;
        initialState = options.initialState;
        condition = options.condition;
        iterate = options.iterate;
        resultSelector = options.resultSelector || identity["a" /* identity */];
        scheduler = options.scheduler;
    }
    else if (resultSelectorOrObservable === undefined || Object(isScheduler["a" /* isScheduler */])(resultSelectorOrObservable)) {
        initialState = initialStateOrOptions;
        resultSelector = identity["a" /* identity */];
        scheduler = resultSelectorOrObservable;
    }
    else {
        initialState = initialStateOrOptions;
        resultSelector = resultSelectorOrObservable;
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        var state = initialState;
        if (scheduler) {
            return scheduler.schedule(generate_dispatch, 0, {
                subscriber: subscriber,
                iterate: iterate,
                condition: condition,
                resultSelector: resultSelector,
                state: state
            });
        }
        do {
            if (condition) {
                var conditionResult = void 0;
                try {
                    conditionResult = condition(state);
                }
                catch (err) {
                    subscriber.error(err);
                    return undefined;
                }
                if (!conditionResult) {
                    subscriber.complete();
                    break;
                }
            }
            var value = void 0;
            try {
                value = resultSelector(state);
            }
            catch (err) {
                subscriber.error(err);
                return undefined;
            }
            subscriber.next(value);
            if (subscriber.closed) {
                break;
            }
            try {
                state = iterate(state);
            }
            catch (err) {
                subscriber.error(err);
                return undefined;
            }
        } while (true);
        return undefined;
    });
}
function generate_dispatch(state) {
    var subscriber = state.subscriber, condition = state.condition;
    if (subscriber.closed) {
        return undefined;
    }
    if (state.needIterate) {
        try {
            state.state = state.iterate(state.state);
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
    }
    else {
        state.needIterate = true;
    }
    if (condition) {
        var conditionResult = void 0;
        try {
            conditionResult = condition(state.state);
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
        if (!conditionResult) {
            subscriber.complete();
            return undefined;
        }
        if (subscriber.closed) {
            return undefined;
        }
    }
    var value;
    try {
        value = state.resultSelector(state.state);
    }
    catch (err) {
        subscriber.error(err);
        return undefined;
    }
    if (subscriber.closed) {
        return undefined;
    }
    subscriber.next(value);
    if (subscriber.closed) {
        return undefined;
    }
    return this.schedule(state);
}
//# sourceMappingURL=generate.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/iif.js
/** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */


function iif(condition, trueResult, falseResult) {
    if (trueResult === void 0) {
        trueResult = empty["a" /* EMPTY */];
    }
    if (falseResult === void 0) {
        falseResult = empty["a" /* EMPTY */];
    }
    return Object(defer["a" /* defer */])(function () { return condition() ? trueResult : falseResult; });
}
//# sourceMappingURL=iif.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isNumeric.js
var isNumeric = __webpack_require__(231);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/interval.js
/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */



function interval(period, scheduler) {
    if (period === void 0) {
        period = 0;
    }
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    if (!Object(isNumeric["a" /* isNumeric */])(period) || period < 0) {
        period = 0;
    }
    if (!scheduler || typeof scheduler.schedule !== 'function') {
        scheduler = scheduler_async["a" /* async */];
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        subscriber.add(scheduler.schedule(interval_dispatch, period, { subscriber: subscriber, counter: 0, period: period }));
        return subscriber;
    });
}
function interval_dispatch(state) {
    var subscriber = state.subscriber, counter = state.counter, period = state.period;
    subscriber.next(counter);
    this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period);
}
//# sourceMappingURL=interval.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/merge.js
var merge = __webpack_require__(235);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/never.js
/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */


var NEVER = /*@__PURE__*/ new Observable["a" /* Observable */](noop["a" /* noop */]);
function never() {
    return NEVER;
}
//# sourceMappingURL=never.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/of.js
var of = __webpack_require__(254);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/onErrorResumeNext.js
/** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */




function onErrorResumeNext() {
    var sources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        sources[_i] = arguments[_i];
    }
    if (sources.length === 0) {
        return empty["a" /* EMPTY */];
    }
    var first = sources[0], remainder = sources.slice(1);
    if (sources.length === 1 && Object(isArray["a" /* isArray */])(first)) {
        return onErrorResumeNext.apply(void 0, first);
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); };
        return Object(from["a" /* from */])(first).subscribe({
            next: function (value) { subscriber.next(value); },
            error: subNext,
            complete: subNext,
        });
    });
}
//# sourceMappingURL=onErrorResumeNext.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/pairs.js
/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */


function pairs(obj, scheduler) {
    if (!scheduler) {
        return new Observable["a" /* Observable */](function (subscriber) {
            var keys = Object.keys(obj);
            for (var i = 0; i < keys.length && !subscriber.closed; i++) {
                var key = keys[i];
                if (obj.hasOwnProperty(key)) {
                    subscriber.next([key, obj[key]]);
                }
            }
            subscriber.complete();
        });
    }
    else {
        return new Observable["a" /* Observable */](function (subscriber) {
            var keys = Object.keys(obj);
            var subscription = new Subscription["a" /* Subscription */]();
            subscription.add(scheduler.schedule(pairs_dispatch, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj }));
            return subscription;
        });
    }
}
function pairs_dispatch(state) {
    var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj;
    if (!subscriber.closed) {
        if (index < keys.length) {
            var key = keys[index];
            subscriber.next([key, obj[key]]);
            subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj }));
        }
        else {
            subscriber.complete();
        }
    }
}
//# sourceMappingURL=pairs.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/not.js
var not = __webpack_require__(378);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeTo.js + 3 modules
var subscribeTo = __webpack_require__(286);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/filter.js
var filter = __webpack_require__(169);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/partition.js
/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */




function partition(source, predicate, thisArg) {
    return [
        Object(filter["a" /* filter */])(predicate, thisArg)(new Observable["a" /* Observable */](Object(subscribeTo["a" /* subscribeTo */])(source))),
        Object(filter["a" /* filter */])(Object(not["a" /* not */])(predicate, thisArg))(new Observable["a" /* Observable */](Object(subscribeTo["a" /* subscribeTo */])(source)))
    ];
}
//# sourceMappingURL=partition.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/race.js
var race = __webpack_require__(348);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/range.js
/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */

function range(start, count, scheduler) {
    if (start === void 0) {
        start = 0;
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        if (count === undefined) {
            count = start;
            start = 0;
        }
        var index = 0;
        var current = start;
        if (scheduler) {
            return scheduler.schedule(range_dispatch, 0, {
                index: index, count: count, start: start, subscriber: subscriber
            });
        }
        else {
            do {
                if (index++ >= count) {
                    subscriber.complete();
                    break;
                }
                subscriber.next(current++);
                if (subscriber.closed) {
                    break;
                }
            } while (true);
        }
        return undefined;
    });
}
function range_dispatch(state) {
    var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber;
    if (index >= count) {
        subscriber.complete();
        return;
    }
    subscriber.next(start);
    if (subscriber.closed) {
        return;
    }
    state.index = index + 1;
    state.start = start + 1;
    this.schedule(state);
}
//# sourceMappingURL=range.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/throwError.js
var throwError = __webpack_require__(295);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/timer.js
var timer = __webpack_require__(344);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/using.js
/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */



function using(resourceFactory, observableFactory) {
    return new Observable["a" /* Observable */](function (subscriber) {
        var resource;
        try {
            resource = resourceFactory();
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
        var result;
        try {
            result = observableFactory(resource);
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
        var source = result ? Object(from["a" /* from */])(result) : empty["a" /* EMPTY */];
        var subscription = source.subscribe(subscriber);
        return function () {
            subscription.unsubscribe();
            if (resource) {
                resource.unsubscribe();
            }
        };
    });
}
//# sourceMappingURL=using.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/zip.js
var zip = __webpack_require__(299);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/scheduled.js + 5 modules
var scheduled = __webpack_require__(350);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/config.js
var config = __webpack_require__(175);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/index.js
/** PURE_IMPORTS_START  PURE_IMPORTS_END */























































//# sourceMappingURL=index.js.map


/***/ }),
/* 140 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return from; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(286);
/* harmony import */ var _scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(350);
/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */



function from(input, scheduler) {
    if (!scheduler) {
        if (input instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"]) {
            return input;
        }
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](Object(_util_subscribeTo__WEBPACK_IMPORTED_MODULE_1__[/* subscribeTo */ "a"])(input));
    }
    else {
        return Object(_scheduled_scheduled__WEBPACK_IMPORTED_MODULE_2__[/* scheduled */ "a"])(input, scheduler);
    }
}
//# sourceMappingURL=from.js.map


/***/ }),
/* 141 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TableLegend; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ScaleLegend; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function TableLegend(table) {
    return { kind: 'table-legend', table: table };
}
function ScaleLegend(minLabel, maxLabel, colors) {
    return { kind: 'scale-legend', minLabel: minLabel, maxLabel: maxLabel, colors: colors };
}
//# sourceMappingURL=legend.js.map

/***/ }),
/* 142 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyTransparencyValue; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return clearTransparency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return createTransparency; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createEmptyTransparency; });
/* harmony import */ var _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function applyTransparencyValue(array, start, end, value) {
    for (var i = start; i < end; ++i) {
        array[i] = value * 255;
    }
    return true;
}
function clearTransparency(array, start, end) {
    array.fill(0, start, end);
}
function createTransparency(count, transparencyData) {
    var transparency = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* createTextureImage */ "c"])(Math.max(1, count), 1, Uint8Array, transparencyData && transparencyData.tTransparency.ref.value.array);
    if (transparencyData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(transparencyData.tTransparency, transparency);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(transparencyData.uTransparencyTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(transparency.width, transparency.height));
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(transparencyData.dTransparency, count > 0);
        return transparencyData;
    }
    else {
        return {
            tTransparency: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(transparency),
            uTransparencyTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(transparency.width, transparency.height)),
            dTransparency: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(count > 0),
            dTransparencyVariant: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create('single'),
        };
    }
}
var emptyTransparencyTexture = { array: new Uint8Array(1), width: 1, height: 1 };
function createEmptyTransparency(transparencyData) {
    if (transparencyData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(transparencyData.tTransparency, emptyTransparencyTexture);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(transparencyData.uTransparencyTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1));
        return transparencyData;
    }
    else {
        return {
            tTransparency: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(emptyTransparencyTexture),
            uTransparencyTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1)),
            dTransparency: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(false),
            dTransparencyVariant: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create('single'),
        };
    }
}
//# sourceMappingURL=transparency-data.js.map

/***/ }),
/* 143 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return applyClippingGroups; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return clearClipping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createClipping; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return createEmptyClipping; });
/* harmony import */ var _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(58);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function applyClippingGroups(array, start, end, groups) {
    for (var i = start; i < end; ++i) {
        array[i] = groups;
    }
    return true;
}
function clearClipping(array, start, end) {
    array.fill(0, start, end);
}
function createClipping(count, clippingData) {
    var clipping = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* createTextureImage */ "c"])(Math.max(1, count), 1, Uint8Array, clippingData && clippingData.tClipping.ref.value.array);
    if (clippingData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(clippingData.tClipping, clipping);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(clippingData.uClippingTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(clipping.width, clipping.height));
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(clippingData.dClipping, count > 0);
        return clippingData;
    }
    else {
        return {
            dClipObjectCount: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(0),
            dClipVariant: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create('instance'),
            tClipping: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(clipping),
            uClippingTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(clipping.width, clipping.height)),
            dClipping: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(count > 0),
        };
    }
}
var emptyClippingTexture = { array: new Uint8Array(1), width: 1, height: 1 };
function createEmptyClipping(clippingData) {
    if (clippingData) {
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(clippingData.tClipping, emptyClippingTexture);
        _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].update(clippingData.uClippingTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1));
        return clippingData;
    }
    else {
        return {
            dClipObjectCount: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(0),
            dClipVariant: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create('instance'),
            tClipping: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(emptyClippingTexture),
            uClippingTexDim: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(1, 1)),
            dClipping: _mol_util_value_cell__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "b"].create(false),
        };
    }
}
//# sourceMappingURL=clipping-data.js.map

/***/ }),
/* 144 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return NullLocation; });
/* unused harmony export isNullLocation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DataLocation; });
/* unused harmony export isDataLocation */
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/** A null value Location */
var NullLocation = { kind: 'null-location' };
function isNullLocation(x) {
    return !!x && x.kind === 'null-location';
}
function DataLocation(tag, data, element) {
    return { kind: 'data-location', tag: tag, data: data, element: element };
}
function isDataLocation(x) {
    return !!x && x.kind === 'data-location';
}
//# sourceMappingURL=location.js.map

/***/ }),
/* 145 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Geometry; });
/* harmony import */ var _mesh_mesh__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(39);
/* harmony import */ var _points_points__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(257);
/* harmony import */ var _text_text__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(123);
/* harmony import */ var _lines_lines__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(74);
/* harmony import */ var _direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(265);
/* harmony import */ var _spheres_spheres__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(258);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(29);
/* harmony import */ var _texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(259);
/* harmony import */ var _image_image__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(218);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var Geometry;
(function (Geometry) {
    function getDrawCount(geometry) {
        switch (geometry.kind) {
            case 'mesh': return geometry.triangleCount * 3;
            case 'points': return geometry.pointCount;
            case 'spheres': return geometry.sphereCount * 2 * 3;
            case 'text': return geometry.charCount * 2 * 3;
            case 'lines': return geometry.lineCount * 2 * 3;
            case 'direct-volume': return 12 * 3;
            case 'image': return 2 * 3;
            case 'texture-mesh': return geometry.vertexCount;
        }
    }
    Geometry.getDrawCount = getDrawCount;
    function getGroupCount(geometry) {
        switch (geometry.kind) {
            case 'mesh':
            case 'points':
            case 'spheres':
            case 'text':
            case 'lines':
                return getDrawCount(geometry) === 0 ? 0 : (Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_6__["arrayMax"])(geometry.groupBuffer.ref.value) + 1);
            case 'direct-volume':
                return 1;
            case 'image':
                return Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_6__["arrayMax"])(geometry.groupTexture.ref.value.array) + 1;
            case 'texture-mesh':
                return geometry.groupCount;
        }
    }
    Geometry.getGroupCount = getGroupCount;
    function getUtils(geometry) {
        // TODO avoid casting
        switch (geometry.kind) {
            case 'mesh': return _mesh_mesh__WEBPACK_IMPORTED_MODULE_0__[/* Mesh */ "a"].Utils;
            case 'points': return _points_points__WEBPACK_IMPORTED_MODULE_1__[/* Points */ "a"].Utils;
            case 'spheres': return _spheres_spheres__WEBPACK_IMPORTED_MODULE_5__[/* Spheres */ "a"].Utils;
            case 'text': return _text_text__WEBPACK_IMPORTED_MODULE_2__[/* Text */ "a"].Utils;
            case 'lines': return _lines_lines__WEBPACK_IMPORTED_MODULE_3__[/* Lines */ "a"].Utils;
            case 'direct-volume': return _direct_volume_direct_volume__WEBPACK_IMPORTED_MODULE_4__[/* DirectVolume */ "a"].Utils;
            case 'image': return _image_image__WEBPACK_IMPORTED_MODULE_8__[/* Image */ "a"].Utils;
            case 'texture-mesh': return _texture_mesh_texture_mesh__WEBPACK_IMPORTED_MODULE_7__[/* TextureMesh */ "a"].Utils;
        }
    }
    Geometry.getUtils = getUtils;
    function getGranularity(locationIt, granularity) {
        // Always use 'group' granularity for 'complex' location iterators,
        // i.e. for which an instance may include multiple units
        return granularity === 'instance' && locationIt.isComplex ? 'group' : granularity;
    }
    Geometry.getGranularity = getGranularity;
})(Geometry || (Geometry = {}));
//# sourceMappingURL=geometry.js.map

/***/ }),
/* 146 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createSizes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getMaxSize; });
/* unused harmony export createValueSize */
/* unused harmony export createUniformSize */
/* unused harmony export createTextureSize */
/* unused harmony export createInstanceSize */
/* unused harmony export createGroupSize */
/* unused harmony export createGroupInstanceSize */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(53);
/* harmony import */ var _mol_model_location__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(144);
/* harmony import */ var _geometry__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(145);
/* harmony import */ var _mol_util_float_packing__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(217);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







function createSizes(locationIt, sizeTheme, sizeData) {
    switch (_geometry__WEBPACK_IMPORTED_MODULE_5__[/* Geometry */ "a"].getGranularity(locationIt, sizeTheme.granularity)) {
        case 'uniform': return createUniformSize(locationIt, sizeTheme.size, sizeData);
        case 'group': return createGroupSize(locationIt, sizeTheme.size, sizeData);
        case 'groupInstance': return createGroupInstanceSize(locationIt, sizeTheme.size, sizeData);
        case 'instance': return createInstanceSize(locationIt, sizeTheme.size, sizeData);
    }
}
function getMaxSize(sizeData) {
    var type = sizeData.dSizeType.ref.value;
    switch (type) {
        case 'uniform':
            return sizeData.uSize.ref.value;
        case 'instance':
        case 'group':
        case 'groupInstance':
            var maxSize = 0;
            var array = sizeData.tSize.ref.value.array;
            for (var i = 0, il = array.length; i < il; ++i) {
                var value = Object(_mol_util_float_packing__WEBPACK_IMPORTED_MODULE_6__[/* decodeFloatLog */ "a"])(array[i] / 255);
                if (maxSize < value)
                    maxSize = value;
            }
            return maxSize;
    }
}
var emptySizeTexture = { array: new Uint8Array(1), width: 1, height: 1 };
function createEmptySizeTexture() {
    return {
        tSize: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(emptySizeTexture),
        uSizeTexDim: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].create(1, 1))
    };
}
function createValueSize(value, sizeData) {
    if (sizeData) {
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(sizeData.uSize, value);
        if (sizeData.dSizeType.ref.value !== 'uniform') {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(sizeData.dSizeType, 'uniform');
        }
        return sizeData;
    }
    else {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ uSize: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(value) }, createEmptySizeTexture()), { dSizeType: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create('uniform') });
    }
}
/** Creates size uniform */
function createUniformSize(locationIt, sizeFn, sizeData) {
    return createValueSize(sizeFn(_mol_model_location__WEBPACK_IMPORTED_MODULE_4__[/* NullLocation */ "b"]), sizeData);
}
function createTextureSize(sizes, type, sizeData) {
    if (sizeData) {
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(sizeData.tSize, sizes);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(sizeData.uSizeTexDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].create(sizes.width, sizes.height));
        if (sizeData.dSizeType.ref.value !== type) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(sizeData.dSizeType, type);
        }
        return sizeData;
    }
    else {
        return {
            uSize: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(0),
            tSize: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(sizes),
            uSizeTexDim: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec2"].create(sizes.width, sizes.height)),
            dSizeType: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(type),
        };
    }
}
/** Creates size texture with size for each instance/unit */
function createInstanceSize(locationIt, sizeFn, sizeData) {
    var instanceCount = locationIt.instanceCount;
    var sizes = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_3__[/* createTextureImage */ "c"])(Math.max(1, instanceCount), 1, Uint8Array, sizeData && sizeData.tSize.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext && !locationIt.isNextNewInstance) {
        var v = locationIt.move();
        sizes.array[v.instanceIndex] = Object(_mol_util_float_packing__WEBPACK_IMPORTED_MODULE_6__[/* encodeFloatLog */ "c"])(sizeFn(v.location)) * 255;
        locationIt.skipInstance();
    }
    return createTextureSize(sizes, 'instance', sizeData);
}
/** Creates size texture with size for each group (i.e. shared across instances/units) */
function createGroupSize(locationIt, sizeFn, sizeData) {
    var groupCount = locationIt.groupCount;
    var sizes = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_3__[/* createTextureImage */ "c"])(Math.max(1, groupCount), 1, Uint8Array, sizeData && sizeData.tSize.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext && !locationIt.isNextNewInstance) {
        var v = locationIt.move();
        sizes.array[v.groupIndex] = Object(_mol_util_float_packing__WEBPACK_IMPORTED_MODULE_6__[/* encodeFloatLog */ "c"])(sizeFn(v.location)) * 255;
    }
    return createTextureSize(sizes, 'group', sizeData);
}
/** Creates size texture with size for each group in each instance (i.e. for each unit) */
function createGroupInstanceSize(locationIt, sizeFn, sizeData) {
    var groupCount = locationIt.groupCount, instanceCount = locationIt.instanceCount;
    var count = instanceCount * groupCount;
    var sizes = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_3__[/* createTextureImage */ "c"])(Math.max(1, count), 1, Uint8Array, sizeData && sizeData.tSize.ref.value.array);
    locationIt.reset();
    while (locationIt.hasNext && !locationIt.isNextNewInstance) {
        var v = locationIt.move();
        sizes.array[v.index] = Object(_mol_util_float_packing__WEBPACK_IMPORTED_MODULE_6__[/* encodeFloatLog */ "c"])(sizeFn(v.location)) * 255;
    }
    return createTextureSize(sizes, 'groupInstance', sizeData);
}
//# sourceMappingURL=size-data.js.map

/***/ }),
/* 147 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getCoarseBegCompId */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getElementMoleculeType; });
/* unused harmony export getAtomicMoleculeType */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getAtomIdForAtomRole; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getPositions; });
/* harmony import */ var _model_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function getCoarseBegCompId(unit, element) {
    var entityKey = unit.coarseElements.entityKey[element];
    var seq = unit.model.sequence.byEntityKey[entityKey].sequence;
    var seq_id_begin = unit.coarseElements.seq_id_begin.value(element);
    return seq.compId.value(seq_id_begin - 1); // 1-indexed
}
function getElementMoleculeType(unit, element) {
    switch (unit.kind) {
        case 0 /* Atomic */:
            return unit.model.atomicHierarchy.derived.residue.moleculeType[unit.residueIndex[element]];
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            // TODO add unit.model.coarseHierarchy.derived.residue.moleculeType
            var compId = getCoarseBegCompId(unit, element);
            var cc = unit.model.properties.chemicalComponentMap.get(compId);
            if (cc)
                return Object(_model_types__WEBPACK_IMPORTED_MODULE_0__["getMoleculeType"])(cc.type, compId);
    }
    return 0 /* Unknown */;
}
function getAtomicMoleculeType(model, rI) {
    return model.atomicHierarchy.derived.residue.moleculeType[rI];
}
var EmptyAtomIds = new Set();
function getAtomIdForAtomRole(polymerType, atomRole) {
    var p = _model_types__WEBPACK_IMPORTED_MODULE_0__["PolymerTypeAtomRoleId"][polymerType];
    if (p !== undefined) {
        var a = p[atomRole];
        if (a !== undefined)
            return a;
    }
    return EmptyAtomIds;
}
var tmpPositionsVec = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].zero();
function getPositions(unit, indices) {
    var pos = unit.conformation.position;
    var positions = new Float32Array(indices.length * 3);
    var elements = unit.elements;
    for (var i = 0, il = indices.length; i < il; ++i) {
        pos(elements[indices[i]], tmpPositionsVec);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].toArray(tmpPositionsVec, positions, i * 3);
    }
    return positions;
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 148 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export QuadPositions */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return QuadSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return QuadValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return readTexture; });
/* unused harmony export printTexture */
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(53);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_gl_renderable_schema__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(17);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var QuadPositions = new Float32Array([
    1.0, 1.0, -1.0, 1.0, -1.0, -1.0,
    -1.0, -1.0, 1.0, -1.0, 1.0, 1.0 // Second triangle
]);
var QuadSchema = {
    drawCount: Object(_mol_gl_renderable_schema__WEBPACK_IMPORTED_MODULE_2__[/* ValueSpec */ "j"])('number'),
    instanceCount: Object(_mol_gl_renderable_schema__WEBPACK_IMPORTED_MODULE_2__[/* ValueSpec */ "j"])('number'),
    aPosition: Object(_mol_gl_renderable_schema__WEBPACK_IMPORTED_MODULE_2__[/* AttributeSpec */ "a"])('float32', 2, 0),
    uQuadScale: Object(_mol_gl_renderable_schema__WEBPACK_IMPORTED_MODULE_2__[/* UniformSpec */ "i"])('v2'),
};
var QuadValues = {
    drawCount: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(6),
    instanceCount: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(1),
    aPosition: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(QuadPositions),
    uQuadScale: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec2"].create(1, 1)),
};
//
function getArrayForTexture(gl, texture, size) {
    switch (texture.type) {
        case gl.UNSIGNED_BYTE: return new Uint8Array(size);
        case gl.FLOAT: return new Float32Array(size);
    }
    throw new Error('unknown/unsupported texture type');
}
function readTexture(ctx, texture, width, height) {
    var gl = ctx.gl, resources = ctx.resources;
    width = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(width, texture.getWidth());
    height = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(height, texture.getHeight());
    var size = width * height * 4;
    var framebuffer = resources.framebuffer();
    var array = getArrayForTexture(gl, texture, size);
    framebuffer.bind();
    texture.attachFramebuffer(framebuffer, 0);
    ctx.readPixels(0, 0, width, height, array);
    return { array: array, width: width, height: height };
}
function printTexture(ctx, texture, scale) {
    Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_0__[/* printTextureImage */ "d"])(readTexture(ctx, texture), scale);
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 149 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return polygon; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Create 3d points for a polygon:
 * 3 for a triangle, 4 for a rectangle, 5 for a pentagon, 6 for a hexagon...
 */
function polygon(sideCount, shift, radius) {
    if (radius === void 0) { radius = -1; }
    var points = new Float32Array(sideCount * 3);
    var r = radius === -1
        ? (sideCount <= 4 ? Math.sqrt(2) / 2 : 0.6)
        : radius;
    var offset = shift ? 1 : 0;
    for (var i = 0, il = sideCount; i < il; ++i) {
        var c = (i * 2 + offset) / sideCount * Math.PI;
        points[i * 3] = Math.cos(c) * r;
        points[i * 3 + 1] = Math.sin(c) * r;
        points[i * 3 + 2] = 0;
    }
    return points;
}
//# sourceMappingURL=polygon.js.map

/***/ }),
/* 150 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ size_SizeTheme; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size/uniform.js
var uniform = __webpack_require__(356);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/theme.js
var theme = __webpack_require__(89);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size/physical.js
var physical = __webpack_require__(282);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size/shape-group.js
var shape_group = __webpack_require__(360);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/size/uncertainty.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var Description = "Assigns a size reflecting the uncertainty or disorder of an element's position, e.g. B-factor or RMSF, depending on the data availability and experimental technique.";
var UncertaintySizeThemeParams = {
    bfactorFactor: param_definition["ParamDefinition"].Numeric(0.1, { min: 0, max: 1, step: 0.01 }),
    rmsfFactor: param_definition["ParamDefinition"].Numeric(0.05, { min: 0, max: 1, step: 0.01 }),
    baseSize: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 2, step: 0.1 }),
};
function getUncertaintySizeThemeParams(ctx) {
    return UncertaintySizeThemeParams; // TODO return copy
}
function getUncertainty(unit, element, props) {
    if (structure["Unit"].isAtomic(unit)) {
        return unit.model.atomicConformation.B_iso_or_equiv.value(element) * props.bfactorFactor;
    }
    else if (structure["Unit"].isSpheres(unit)) {
        return unit.model.coarseConformation.spheres.rmsf[element] * props.rmsfFactor;
    }
    else {
        return 0;
    }
}
function UncertaintySizeTheme(ctx, props) {
    function size(location) {
        var size = props.baseSize;
        if (structure["StructureElement"].Location.is(location)) {
            size += getUncertainty(location.unit, location.element, props);
        }
        else if (structure["Bond"].isLocation(location)) {
            size += getUncertainty(location.aUnit, location.aUnit.elements[location.aIndex], props);
        }
        return size;
    }
    return {
        factory: UncertaintySizeTheme,
        granularity: 'group',
        size: size,
        props: props,
        description: Description
    };
}
var UncertaintySizeThemeProvider = {
    name: 'uncertainty',
    label: 'Uncertainty/Disorder',
    category: '',
    factory: UncertaintySizeTheme,
    getParams: getUncertaintySizeThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(UncertaintySizeThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure && ctx.structure.models.some(function (m) { return m.atomicConformation.B_iso_or_equiv.isDefined || m.coarseHierarchy.isDefined; }); }
};
//# sourceMappingURL=uncertainty.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/size.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var size_SizeTheme;
(function (SizeTheme) {
    SizeTheme.EmptyFactory = function () { return SizeTheme.Empty; };
    SizeTheme.Empty = { factory: SizeTheme.EmptyFactory, granularity: 'uniform', size: function () { return 1; }, props: {} };
    function areEqual(themeA, themeB) {
        return themeA.factory === themeB.factory && Object(mol_util["h" /* deepEqual */])(themeA.props, themeB.props);
    }
    SizeTheme.areEqual = areEqual;
    SizeTheme.EmptyProvider = { name: '', label: '', category: '', factory: SizeTheme.EmptyFactory, getParams: function () { return ({}); }, defaultValues: {}, isApplicable: function () { return true; } };
    function createRegistry() {
        return new theme["b" /* ThemeRegistry */](SizeTheme.BuiltIn, SizeTheme.EmptyProvider);
    }
    SizeTheme.createRegistry = createRegistry;
    SizeTheme.BuiltIn = {
        'physical': physical["b" /* PhysicalSizeThemeProvider */],
        'shape-group': shape_group["b" /* ShapeGroupSizeThemeProvider */],
        'uncertainty': UncertaintySizeThemeProvider,
        'uniform': uniform["b" /* UniformSizeThemeProvider */]
    };
})(size_SizeTheme || (size_SizeTheme = {}));
//# sourceMappingURL=size.js.map

/***/ }),
/* 151 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export Immer */
/* unused harmony export applyPatches */
/* unused harmony export castDraft */
/* unused harmony export castImmutable */
/* unused harmony export createDraft */
/* unused harmony export enableAllPlugins */
/* unused harmony export enableES5 */
/* unused harmony export enableMapSet */
/* unused harmony export enablePatches */
/* unused harmony export finishDraft */
/* unused harmony export immerable */
/* unused harmony export isDraft */
/* unused harmony export isDraftable */
/* unused harmony export nothing */
/* unused harmony export original */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rn; });
/* unused harmony export produceWithPatches */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return on; });
/* unused harmony export setUseProxies */
function n(n){for(var t=arguments.length,r=Array(t>1?t-1:0),e=1;e<t;e++)r[e-1]=arguments[e];if(false){ var i, o; }throw Error("[Immer] minified error nr: "+n+(r.length?" "+r.join(","):"")+". Find the full error at: https://bit.ly/3cXEKWf")}function t(n){return!!n&&!!n[G]}function r(n){return!!n&&(function(n){if(!n||"object"!=typeof n)return!1;var t=Object.getPrototypeOf(n);return!t||t===Object.prototype}(n)||Array.isArray(n)||!!n[B]||!!n.constructor[B]||c(n)||s(n))}function e(n){if(n&&n[G])return n[G].t}function i(n,t,r){void 0===r&&(r=!1),0===o(n)?(r?Object.keys:Q)(n).forEach((function(r){return t(r,n[r],n)})):n.forEach((function(r,e){return t(e,r,n)}))}function o(n){var t=n[G];return t?t.i>3?t.i-4:t.i:Array.isArray(n)?1:c(n)?2:s(n)?3:0}function u(n,t){return 2===o(n)?n.has(t):Object.prototype.hasOwnProperty.call(n,t)}function a(n,t){return 2===o(n)?n.get(t):n[t]}function f(n,t){return n===t?0!==n||1/n==1/t:n!=n&&t!=t}function c(n){return U&&n instanceof Map}function s(n){return W&&n instanceof Set}function v(n){return n.o||n.t}function p(t,r){if(void 0===r&&(r=!1),Array.isArray(t))return t.slice();var e=Object.create(Object.getPrototypeOf(t));return i(t,(function(i){if(i!==G){var o=Object.getOwnPropertyDescriptor(t,i),u=o.value;o.get&&(r||n(1),u=o.get.call(t)),o.enumerable?e[i]=u:Object.defineProperty(e,i,{value:u,writable:!0,configurable:!0})}})),e}function d(n,e){t(n)||h(n)||!r(n)||(o(n)>1&&(n.set=n.add=n.clear=n.delete=l),Object.freeze(n),e&&i(n,(function(n,t){return d(t,!0)}),!0))}function l(){n(2)}function h(n){return null==n||"object"!=typeof n||Object.isFrozen(n)}function y(t){var r=V[t];return r||n( false?undefined:19,t),r}function b(n,t){V[n]=t}function m(){return true||false,K}function _(n,t){t&&(y("Patches"),n.u=[],n.s=[],n.v=t)}function j(n){O(n),n.p.forEach(w),n.p=null}function O(n){n===K&&(K=n.l)}function g(n){return K={p:[],l:K,h:n,m:!0,_:0}}function w(n){var t=n[G];0===t.i||1===t.i?t.j():t.O=!0}function S(t,e){e._=e.p.length;var i=e.p[0],o=void 0!==t&&t!==i;return e.h.g||y("ES5").S(e,t,o),o?(i[G].P&&(j(e),n(4)),r(t)&&(t=P(e,t),e.l||A(e,t)),e.u&&y("Patches").M(i[G],t,e.u,e.s)):t=P(e,i,[]),j(e),e.u&&e.v(e.u,e.s),t!==q?t:void 0}function P(n,t,r){if(h(t))return t;var e=t[G];if(!e)return i(t,(function(i,o){return M(n,e,t,i,o,r)}),!0),t;if(e.A!==n)return t;if(!e.P)return A(n,e.t,!0),e.t;if(!e.I){e.I=!0,e.A._--;var o=4===e.i||5===e.i?e.o=p(e.k,!0):e.o;i(o,(function(t,i){return M(n,e,o,t,i,r)})),A(n,o,!1),r&&n.u&&y("Patches").R(e,r,n.u,n.s)}return e.o}function M(e,i,c,s,v,p){if( false&&false,t(v)){var d=P(e,v,p&&i&&3!==i.i&&!u(i.D,s)?p.concat(s):void 0);if(h=s,y=d,2===(b=o(l=c))?l.set(h,y):3===b?(l.delete(h),l.add(y)):l[h]=y,!t(d))return;e.m=!1}var l,h,y,b;if((!i||!f(v,a(i.t,s)))&&r(v)){if(!e.h.N&&e._<1)return;P(e,v),i&&i.A.l||A(e,v)}}function A(n,t,r){void 0===r&&(r=!1),n.h.N&&n.m&&d(t,r)}function x(n,t){var r=n[G],e=Reflect.getOwnPropertyDescriptor(r?v(r):n,t);return e&&e.value}function z(n){if(!n.P){if(n.P=!0,0===n.i||1===n.i){var t=n.o=p(n.t);i(n.p,(function(n,r){t[n]=r})),n.p=void 0}n.l&&z(n.l)}}function I(n){n.o||(n.o=p(n.t))}function E(n,t,r){var e=c(t)?y("MapSet").T(t,r):s(t)?y("MapSet").F(t,r):n.g?function(n,t){var r=Array.isArray(n),e={i:r?1:0,A:t?t.A:m(),P:!1,I:!1,D:{},l:t,t:n,k:null,p:{},o:null,j:null,C:!1},i=e,o=Y;r&&(i=[e],o=Z);var u=Proxy.revocable(i,o),a=u.revoke,f=u.proxy;return e.k=f,e.j=a,f}(t,r):y("ES5").J(t,r);return(r?r.A:m()).p.push(e),e}function k(n,t){n.g?z(t):y("ES5").K(t)}function R(){function e(n,t){var r=n[G];if(r&&!r.$){r.$=!0;var e=n[t];return r.$=!1,e}return n[t]}function o(n){n.P||(n.P=!0,n.l&&o(n.l))}function a(n){n.o||(n.o=c(n.t))}function c(n){var t=n&&n[G];if(t){t.$=!0;var r=p(t.k,!0);return t.$=!1,r}return p(n)}function s(n){for(var t=n.length-1;t>=0;t--){var r=n[t][G];if(!r.P)switch(r.i){case 5:l(r)&&o(r);break;case 4:d(r)&&o(r)}}}function d(n){for(var t=n.t,r=n.k,e=Object.keys(r),i=e.length-1;i>=0;i--){var o=e[i],a=t[o];if(void 0===a&&!u(t,o))return!0;var c=r[o],s=c&&c[G];if(s?s.t!==a:!f(c,a))return!0}return e.length!==Object.keys(t).length}function l(n){var t=n.k;if(t.length!==n.t.length)return!0;var r=Object.getOwnPropertyDescriptor(t,t.length-1);return!(!r||r.get)}function h(t){t.O&&n(3,JSON.stringify(v(t)))}var y={};b("ES5",{J:function(n,t){var u=Array.isArray(n),s=c(n);i(s,(function(t){!function(n,t,i){var u=y[t];u?u.enumerable=i:y[t]=u={enumerable:i,get:function(){return function(n,t){h(n);var i=e(v(n),t);return n.$?i:i===e(n.t,t)&&r(i)?(a(n),n.o[t]=E(n.A.h,i,n)):i}(this[G],t)},set:function(n){!function(n,t,r){if(h(n),n.D[t]=!0,!n.P){if(f(r,e(v(n),t)))return;o(n),a(n)}n.o[t]=r}(this[G],t,n)}},Object.defineProperty(n,t,u)}(s,t,u||function(n,t){var r=Object.getOwnPropertyDescriptor(n,t);return!(!r||!r.enumerable)}(n,t))}));var p={i:u?5:4,A:t?t.A:m(),P:!1,$:!1,I:!1,D:{},l:t,t:n,k:s,o:null,O:!1,C:!1};return Object.defineProperty(s,G,{value:p,writable:!0}),s},K:o,S:function(n,r,e){n.p.forEach((function(n){n[G].$=!0})),e?t(r)&&r[G].A===n&&s(n.p):(n.u&&function n(t){if(t&&"object"==typeof t){var r=t[G];if(r){var e=r.t,a=r.k,f=r.D,c=r.i;if(4===c)i(a,(function(t){t!==G&&(void 0!==e[t]||u(e,t)?f[t]||n(a[t]):(f[t]=!0,o(r)))})),i(e,(function(n){void 0!==a[n]||u(a,n)||(f[n]=!1,o(r))}));else if(5===c){if(l(r)&&(o(r),f.length=!0),a.length<e.length)for(var s=a.length;s<e.length;s++)f[s]=!1;else for(var v=e.length;v<a.length;v++)f[v]=!0;for(var p=Math.min(a.length,e.length),d=0;d<p;d++)void 0===f[d]&&n(a[d])}}}}(n.p[0]),s(n.p))}})}function D(){function r(n){if(!n||"object"!=typeof n)return n;if(Array.isArray(n))return n.map(r);if(c(n))return new Map(Array.from(n.entries()).map((function(n){return[n[0],r(n[1])]})));if(s(n))return new Set(Array.from(n).map(r));var t=Object.create(Object.getPrototypeOf(n));for(var e in n)t[e]=r(n[e]);return t}function e(n){return t(n)?r(n):n}var f="add";b("Patches",{U:function(t,e){return e.forEach((function(e){for(var i=e.path,u=e.op,c=t,s=0;s<i.length-1;s++)"object"!=typeof(c=a(c,i[s]))&&n(15,i.join("/"));var v=o(c),p=r(e.value),d=i[i.length-1];switch(u){case"replace":switch(v){case 2:return c.set(d,p);case 3:n(16);default:return c[d]=p}case f:switch(v){case 1:return c.splice(d,0,p);case 2:return c.set(d,p);case 3:return c.add(p);default:return c[d]=p}case"remove":switch(v){case 1:return c.splice(d,1);case 2:return c.delete(d);case 3:return c.delete(e.value);default:return delete c[d]}default:n(17,u)}})),t},R:function(n,t,r,o){switch(n.i){case 0:case 4:case 2:return function(n,t,r,o){var c=n.t,s=n.o;i(n.D,(function(n,i){var v=a(c,n),p=a(s,n),d=i?u(c,n)?"replace":f:"remove";if(v!==p||"replace"!==d){var l=t.concat(n);r.push("remove"===d?{op:d,path:l}:{op:d,path:l,value:p}),o.push(d===f?{op:"remove",path:l}:"remove"===d?{op:f,path:l,value:e(v)}:{op:"replace",path:l,value:e(v)})}}))}(n,t,r,o);case 5:case 1:return function(n,t,r,i){var o=n.t,u=n.D,a=n.o;if(a.length<o.length){var c=[a,o];o=c[0],a=c[1];var s=[i,r];r=s[0],i=s[1]}for(var v=a.length-o.length,p=0;o[p]===a[p]&&p<o.length;)++p;for(var d=o.length;d>p&&o[d-1]===a[d+v-1];)--d;for(var l=p;l<d;++l)if(u[l]&&a[l]!==o[l]){var h=t.concat([l]);r.push({op:"replace",path:h,value:e(a[l])}),i.push({op:"replace",path:h,value:e(o[l])})}for(var y=r.length,b=d+v-1;b>=d;--b){var m=t.concat([b]);r[y+b-d]={op:f,path:m,value:e(a[b])},i.push({op:"remove",path:m})}}(n,t,r,o);case 3:return function(n,t,r,e){var i=n.t,o=n.o,u=0;i.forEach((function(n){if(!o.has(n)){var i=t.concat([u]);r.push({op:"remove",path:i,value:n}),e.unshift({op:f,path:i,value:n})}u++})),u=0,o.forEach((function(n){if(!i.has(n)){var o=t.concat([u]);r.push({op:f,path:o,value:n}),e.unshift({op:"remove",path:o,value:n})}u++}))}(n,t,r,o)}},M:function(n,t,r,e){r.push({op:"replace",path:[],value:t}),e.push({op:"replace",path:[],value:n.t})}})}function N(){function t(n,t){function r(){this.constructor=n}u(n,t),n.prototype=(r.prototype=t.prototype,new r)}function e(n){n.o||(n.D=new Map,n.o=new Map(n.t))}function i(n){n.o||(n.o=new Set,n.t.forEach((function(t){if(r(t)){var e=E(n.A.h,t,n);n.p.set(t,e),n.o.add(e)}else n.o.add(t)})))}function o(t){t.O&&n(3,JSON.stringify(v(t)))}var u=function(n,t){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,t){n.__proto__=t}||function(n,t){for(var r in t)t.hasOwnProperty(r)&&(n[r]=t[r])})(n,t)},a=function(){function n(n,t){return this[G]={i:2,l:t,A:t?t.A:m(),P:!1,I:!1,o:void 0,D:void 0,t:n,k:this,C:!1,O:!1},this}t(n,Map);var i=n.prototype;return Object.defineProperty(i,"size",{get:function(){return v(this[G]).size}}),i.has=function(n){return v(this[G]).has(n)},i.set=function(n,t){var r=this[G];return o(r),v(r).get(n)!==t&&(e(r),k(r.A.h,r),r.D.set(n,!0),r.o.set(n,t),r.D.set(n,!0)),this},i.delete=function(n){if(!this.has(n))return!1;var t=this[G];return o(t),e(t),k(t.A.h,t),t.D.set(n,!1),t.o.delete(n),!0},i.clear=function(){var n=this[G];return o(n),e(n),k(n.A.h,n),n.D=new Map,n.o.clear()},i.forEach=function(n,t){var r=this;v(this[G]).forEach((function(e,i){n.call(t,r.get(i),i,r)}))},i.get=function(n){var t=this[G];o(t);var i=v(t).get(n);if(t.I||!r(i))return i;if(i!==t.t.get(n))return i;var u=E(t.A.h,i,t);return e(t),t.o.set(n,u),u},i.keys=function(){return v(this[G]).keys()},i.values=function(){var n,t=this,r=this.keys();return(n={})[H]=function(){return t.values()},n.next=function(){var n=r.next();return n.done?n:{done:!1,value:t.get(n.value)}},n},i.entries=function(){var n,t=this,r=this.keys();return(n={})[H]=function(){return t.entries()},n.next=function(){var n=r.next();if(n.done)return n;var e=t.get(n.value);return{done:!1,value:[n.value,e]}},n},i[H]=function(){return this.entries()},n}(),f=function(){function n(n,t){return this[G]={i:3,l:t,A:t?t.A:m(),P:!1,I:!1,o:void 0,t:n,k:this,p:new Map,O:!1,C:!1},this}t(n,Set);var r=n.prototype;return Object.defineProperty(r,"size",{get:function(){return v(this[G]).size}}),r.has=function(n){var t=this[G];return o(t),t.o?!!t.o.has(n)||!(!t.p.has(n)||!t.o.has(t.p.get(n))):t.t.has(n)},r.add=function(n){var t=this[G];return o(t),this.has(n)||(i(t),k(t.A.h,t),t.o.add(n)),this},r.delete=function(n){if(!this.has(n))return!1;var t=this[G];return o(t),i(t),k(t.A.h,t),t.o.delete(n)||!!t.p.has(n)&&t.o.delete(t.p.get(n))},r.clear=function(){var n=this[G];return o(n),i(n),k(n.A.h,n),n.o.clear()},r.values=function(){var n=this[G];return o(n),i(n),n.o.values()},r.entries=function(){var n=this[G];return o(n),i(n),n.o.entries()},r.keys=function(){return this.values()},r[H]=function(){return this.values()},r.forEach=function(n,t){for(var r=this.values(),e=r.next();!e.done;)n.call(t,e.value,e.value,this),e=r.next()},n}();b("MapSet",{T:function(n,t){return new a(n,t)},F:function(n,t){return new f(n,t)}})}function T(){R(),N(),D()}function F(n){return n}function C(n){return n}var J,K,$="undefined"!=typeof Symbol&&"symbol"==typeof Symbol("x"),U="undefined"!=typeof Map,W="undefined"!=typeof Set,X="undefined"!=typeof Proxy&&void 0!==Proxy.revocable&&"undefined"!=typeof Reflect,q=$?Symbol("immer-nothing"):((J={})["immer-nothing"]=!0,J),B=$?Symbol("immer-draftable"):"__$immer_draftable",G=$?Symbol("immer-state"):"__$immer_state",H="undefined"!=typeof Symbol&&Symbol.iterator||"@@iterator",L={0:"Illegal state",1:"Immer drafts cannot have computed properties",2:"This object has been frozen and should not be mutated",3:function(n){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+n},4:"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.",5:"Immer forbids circular references",6:"The first or second argument to `produce` must be a function",7:"The third argument to `produce` must be a function or undefined",8:"First argument to `createDraft` must be a plain object, an array, or an immerable object",9:"First argument to `finishDraft` must be a draft returned by `createDraft`",10:"The given draft is already finalized",11:"Object.defineProperty() cannot be used on an Immer draft",12:"Object.setPrototypeOf() cannot be used on an Immer draft",13:"Immer only supports deleting array indices",14:"Immer only supports setting array indices and the 'length' property",15:function(n){return"Cannot apply patch, path doesn't resolve: "+n},16:'Sets cannot have "replace" patches.',17:function(n){return"Unsupported patch operation: "+n},18:function(n){return"The plugin for '"+n+"' has not been loaded into Immer. To enable the plugin, import and call `enable"+n+"()` when initializing your application."},19:function(n){return"plugin not loaded: "+n},20:"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available"},Q="undefined"!=typeof Reflect&&Reflect.ownKeys?Reflect.ownKeys:void 0!==Object.getOwnPropertySymbols?function(n){return Object.getOwnPropertyNames(n).concat(Object.getOwnPropertySymbols(n))}:Object.getOwnPropertyNames,V={},Y={get:function(n,t){if(t===G)return n;var e=n.p;if(!n.P&&u(e,t))return e[t];var i=v(n)[t];if(n.I||!r(i))return i;if(n.P){if(i!==x(n.t,t))return i;e=n.o}return e[t]=E(n.A.h,i,n)},has:function(n,t){return t in v(n)},ownKeys:function(n){return Reflect.ownKeys(v(n))},set:function(n,t,r){if(!n.P){var e=x(n.t,t);if(r?f(e,r)||r===n.p[t]:f(e,r)&&t in n.t)return!0;I(n),z(n)}return n.D[t]=!0,n.o[t]=r,!0},deleteProperty:function(n,t){return void 0!==x(n.t,t)||t in n.t?(n.D[t]=!1,I(n),z(n)):n.D[t]&&delete n.D[t],n.o&&delete n.o[t],!0},getOwnPropertyDescriptor:function(n,t){var r=v(n),e=Reflect.getOwnPropertyDescriptor(r,t);return e&&(e.writable=!0,e.configurable=1!==n.i||"length"!==t),e},defineProperty:function(){n(11)},getPrototypeOf:function(n){return Object.getPrototypeOf(n.t)},setPrototypeOf:function(){n(12)}},Z={};i(Y,(function(n,t){Z[n]=function(){return arguments[0]=arguments[0][0],t.apply(this,arguments)}})),Z.deleteProperty=function(t,r){return false&&false,Y.deleteProperty.call(this,t[0],r)},Z.set=function(t,r,e){return false&&false,Y.set.call(this,t[0],r,e,t[0])};var nn=function(){function e(n){this.g=X,this.N="production"!=="production","boolean"==typeof(null==n?void 0:n.useProxies)&&this.setUseProxies(n.useProxies),"boolean"==typeof(null==n?void 0:n.autoFreeze)&&this.setAutoFreeze(n.autoFreeze),this.produce=this.produce.bind(this),this.produceWithPatches=this.produceWithPatches.bind(this)}var i=e.prototype;return i.produce=function(t,e,i){if("function"==typeof t&&"function"!=typeof e){var o=e;e=t;var u=this;return function(n){var t=this;void 0===n&&(n=o);for(var r=arguments.length,i=Array(r>1?r-1:0),a=1;a<r;a++)i[a-1]=arguments[a];return u.produce(n,(function(n){var r;return(r=e).call.apply(r,[t,n].concat(i))}))}}var a;if("function"!=typeof e&&n(6),void 0!==i&&"function"!=typeof i&&n(7),r(t)){var f=g(this),c=E(this,t,void 0),s=!0;try{a=e(c),s=!1}finally{s?j(f):O(f)}return"undefined"!=typeof Promise&&a instanceof Promise?a.then((function(n){return _(f,i),S(n,f)}),(function(n){throw j(f),n})):(_(f,i),S(a,f))}if((a=e(t))!==q)return void 0===a&&(a=t),this.N&&d(a,!0),a},i.produceWithPatches=function(n,t){var r,e,i=this;return"function"==typeof n?function(t){for(var r=arguments.length,e=Array(r>1?r-1:0),o=1;o<r;o++)e[o-1]=arguments[o];return i.produceWithPatches(t,(function(t){return n.apply(void 0,[t].concat(e))}))}:[this.produce(n,t,(function(n,t){r=n,e=t})),r,e]},i.createDraft=function(t){r(t)||n(8);var e=g(this),i=E(this,t,void 0);return i[G].C=!0,O(e),i},i.finishDraft=function(t,r){var e=t&&t[G]; false&&(false);var i=e.A;return _(i,r),S(void 0,i)},i.setAutoFreeze=function(n){this.N=n},i.setUseProxies=function(t){X||n(20),this.g=t},i.applyPatches=function(n,r){var e;for(e=r.length-1;e>=0;e--){var i=r[e];if(0===i.path.length&&"replace"===i.op){n=i.value;break}}var o=y("Patches").U;return t(n)?o(n,r):this.produce(n,(function(n){return o(n,r.slice(e+1))}))},e}(),tn=new nn,rn=tn.produce,en=tn.produceWithPatches.bind(tn),on=tn.setAutoFreeze.bind(tn),un=tn.setUseProxies.bind(tn),an=tn.applyPatches.bind(tn),fn=tn.createDraft.bind(tn),cn=tn.finishDraft.bind(tn);/* harmony default export */ __webpack_exports__["a"] = (rn);
//# sourceMappingURL=immer.esm.js.map


/***/ }),
/* 152 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ SecondaryStructureProvider; });

// UNUSED EXPORTS: SecondaryStructureParams

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/seconday-structure.js
var seconday_structure = __webpack_require__(358);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/misc.js
var misc = __webpack_require__(46);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/bends.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */


/**
 * Bend(i) =: [angle ((CW - Ca(i - 2)),(C"(i + 2) - C"(i))) > 70"]
 *
 * Type: S
 */
function assignBends(ctx) {
    var unit = ctx.unit, flags = ctx.flags, proteinInfo = ctx.proteinInfo;
    var position = unit.conformation.position;
    var traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex;
    var residueIndices = proteinInfo.residueIndices, nIndices = proteinInfo.nIndices;
    var residueCount = residueIndices.length;
    // const position = (i: number, v: Vec3) => Vec3.set(v, x[i], y[i], z[i])
    var p = function (i, v) { return i === -1 ? linear_algebra["Vec3"].setNaN(v) : position(i, v); };
    var caPosPrev2 = Object(linear_algebra["Vec3"])();
    var caPos = Object(linear_algebra["Vec3"])();
    var caPosNext2 = Object(linear_algebra["Vec3"])();
    var cPos = Object(linear_algebra["Vec3"])();
    var nPosNext = Object(linear_algebra["Vec3"])();
    var caMinus2 = Object(linear_algebra["Vec3"])();
    var caPlus2 = Object(linear_algebra["Vec3"])();
    f1: for (var i = 2; i < residueCount - 2; i++) {
        // check for peptide bond
        for (var k = 0; k < 4; k++) {
            var index = i + k - 2;
            p(traceElementIndex[index], cPos);
            p(nIndices[index + 1], nPosNext);
            if (linear_algebra["Vec3"].squaredDistance(cPos, nPosNext) > 6.25 /* max squared peptide bond distance allowed */) {
                continue f1;
            }
        }
        var oRIprev2 = residueIndices[i - 2];
        var oRI = residueIndices[i];
        var oRInext2 = residueIndices[i + 2];
        var caAtomPrev2 = traceElementIndex[oRIprev2];
        var caAtom = traceElementIndex[oRI];
        var caAtomNext2 = traceElementIndex[oRInext2];
        p(caAtomPrev2, caPosPrev2);
        p(caAtom, caPos);
        p(caAtomNext2, caPosNext2);
        linear_algebra["Vec3"].sub(caMinus2, caPosPrev2, caPos);
        linear_algebra["Vec3"].sub(caPlus2, caPos, caPosNext2);
        var angle = Object(misc["f" /* radToDeg */])(linear_algebra["Vec3"].angle(caMinus2, caPlus2));
        if (angle && angle > 70.00) {
            flags[i] |= 32 /* S */;
        }
    }
}
//# sourceMappingURL=bends.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph.js + 1 modules
var graph = __webpack_require__(171);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/backbone-hbonds.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */


/** max distance between two C-alpha atoms to check for hbond */
var caMaxDist = 9.0;
/**
 * Constant for electrostatic energy in kcal/mol
 *      f  *  q1 *   q2
 * Q = -332 * 0.42 * 0.20
 *
 * f is the dimensional factor
 *
 * q1 and q2 are partial charges which are placed on the C,O
 * (+q1,-q1) and N,H (-q2,+q2)
 */
var Q = -27.888;
/** cutoff for hbonds in kcal/mol, must be lower to be consider as an hbond */
var hbondEnergyCutoff = -0.5;
/** prevent extremely low hbond energies */
var hbondEnergyMinimal = -9.9;
/**
 * E = Q * (1/r(ON) + l/r(CH) - l/r(OH) - l/r(CN))
 */
function calcHbondEnergy(oPos, cPos, nPos, hPos) {
    var distOH = linear_algebra["Vec3"].distance(oPos, hPos);
    var distCH = linear_algebra["Vec3"].distance(cPos, hPos);
    var distCN = linear_algebra["Vec3"].distance(cPos, nPos);
    var distON = linear_algebra["Vec3"].distance(oPos, nPos);
    var e1 = Q / distOH - Q / distCH;
    var e2 = Q / distCN - Q / distON;
    var e = e1 + e2;
    // cap lowest possible energy
    if (e < hbondEnergyMinimal)
        return hbondEnergyMinimal;
    return e;
}
function calcUnitBackboneHbonds(unit, proteinInfo, lookup3d) {
    var residueIndices = proteinInfo.residueIndices, cIndices = proteinInfo.cIndices, hIndices = proteinInfo.hIndices, nIndices = proteinInfo.nIndices, oIndices = proteinInfo.oIndices;
    var index = unit.model.atomicHierarchy.index;
    var invariantPosition = unit.conformation.invariantPosition;
    var traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex;
    var residueCount = residueIndices.length;
    var oAtomResidues = [];
    var nAtomResidues = [];
    var energies = [];
    var oPos = Object(linear_algebra["Vec3"])();
    var cPos = Object(linear_algebra["Vec3"])();
    var caPos = Object(linear_algebra["Vec3"])();
    var nPos = Object(linear_algebra["Vec3"])();
    var hPos = Object(linear_algebra["Vec3"])();
    var cPosPrev = Object(linear_algebra["Vec3"])();
    var oPosPrev = Object(linear_algebra["Vec3"])();
    for (var i = 0, il = residueIndices.length; i < il; ++i) {
        var oPI = i;
        var oRI = residueIndices[i];
        var oAtom = oIndices[oPI];
        var cAtom = cIndices[oPI];
        var caAtom = traceElementIndex[oRI];
        // continue if residue is missing O or C atom
        if (oAtom === -1 || cAtom === -1)
            continue;
        // ignore C-terminal residue as acceptor
        if (index.findAtomOnResidue(oRI, 'OXT') !== -1)
            continue;
        invariantPosition(oAtom, oPos);
        invariantPosition(cAtom, cPos);
        invariantPosition(caAtom, caPos);
        var _a = lookup3d.find(caPos[0], caPos[1], caPos[2], caMaxDist), indices = _a.indices, count = _a.count;
        for (var j = 0; j < count; ++j) {
            var nPI = indices[j];
            // ignore bonds within a residue or to prev or next residue
            if (nPI === oPI || nPI - 1 === oPI || nPI + 1 === oPI)
                continue;
            var nAtom = nIndices[nPI];
            if (nAtom === -1)
                continue;
            invariantPosition(nAtom, nPos);
            var hAtom = hIndices[nPI];
            if (hAtom === -1) {
                // approximate calculation of H position, TODO factor out
                if (nPI === 0)
                    continue;
                var nPIprev = nPI - 1;
                var oAtomPrev = oIndices[nPIprev];
                var cAtomPrev = cIndices[nPIprev];
                if (oAtomPrev === -1 || cAtomPrev === -1)
                    continue;
                invariantPosition(oAtomPrev, oPosPrev);
                invariantPosition(cAtomPrev, cPosPrev);
                linear_algebra["Vec3"].sub(hPos, cPosPrev, oPosPrev);
                var dist = linear_algebra["Vec3"].distance(oPosPrev, cPosPrev);
                linear_algebra["Vec3"].scaleAndAdd(hPos, nPos, hPos, 1 / dist);
            }
            else {
                invariantPosition(hAtom, hPos);
            }
            var e = calcHbondEnergy(oPos, cPos, nPos, hPos);
            if (e > hbondEnergyCutoff)
                continue;
            oAtomResidues[oAtomResidues.length] = oPI;
            nAtomResidues[nAtomResidues.length] = nPI;
            energies[energies.length] = e;
        }
    }
    return buildHbondGraph(residueCount, oAtomResidues, nAtomResidues, energies);
}
function buildHbondGraph(residueCount, oAtomResidues, nAtomResidues, energies) {
    var builder = new graph["a" /* IntAdjacencyGraph */].DirectedEdgeBuilder(residueCount, oAtomResidues, nAtomResidues);
    var _energies = new Float32Array(builder.slotCount);
    for (var i = 0, _i = builder.edgeCount; i < _i; i++) {
        builder.addNextEdge();
        builder.assignProperty(_energies, energies[i]);
    }
    return builder.createGraph({ energies: energies });
}
//# sourceMappingURL=backbone-hbonds.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/common.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */


var common_DSSPType;
(function (DSSPType) {
    DSSPType.is = mol_util["a" /* BitFlags */].has;
    DSSPType.create = mol_util["a" /* BitFlags */].create;
})(common_DSSPType || (common_DSSPType = {}));
var Bridge = /** @class */ (function () {
    function Bridge(p1, p2, type) {
        this.partner1 = Math.min(p1, p2);
        this.partner2 = Math.max(p1, p2);
        this.type = type;
    }
    return Bridge;
}());

//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/turns.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */
/**
 * The basic turn pattern is a single H bond of type (i, i + n).
 * We assign an n-turn at residue i if there is an H bond from CO(i) to NH(i + n),
 * i.e., “n-turn(i)=: Hbond(i, i + n), n = 3, 4, 5.”
 *
 * Type: T
 */
function assignTurns(ctx) {
    var proteinInfo = ctx.proteinInfo, hbonds = ctx.hbonds, flags = ctx.flags;
    var turnFlag = [1024 /* T3S */, 2048 /* T4S */, 4096 /* T5S */, 128 /* T3 */, 256 /* T4 */, 512 /* T5 */];
    for (var idx = 0; idx < 3; idx++) {
        for (var i = 0, il = proteinInfo.residueIndices.length - 1; i < il; ++i) {
            // check if hbond exists
            if (hbonds.getDirectedEdgeIndex(i, i + idx + 3) !== -1) {
                flags[i] |= turnFlag[idx + 3] | turnFlag[idx];
                if (ctx.params.oldDefinition) {
                    for (var k = 1; k < idx + 3; ++k) {
                        flags[i + k] |= turnFlag[idx + 3] | 64 /* T */;
                    }
                }
                else {
                    for (var k = 0; k <= idx + 3; ++k) {
                        flags[i + k] |= turnFlag[idx + 3] | 64 /* T */;
                    }
                }
            }
        }
    }
}
//# sourceMappingURL=turns.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/helices.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */

/**
 * A minimal helix is defined by two consecutive n-turns.
 * For example, a 4-helix, of minimal length 4 from residues i to i + 3,
 * requires 4-turns at residues i - 1 and i,
 *
 *      3-helix(i,i + 2)=: [3-turn(i - 1) and 3-turn(i)]
 *      4-helix(i,i + 3)=: [4-turn(i - 1) and 4-turn(i)]
 *      5-helix(i,i + 4)=: [5-turn(i - 1) and 5-turn(i)]
 *
 * Type: G (n=3), H (n=4), I (n=5)
 */
function assignHelices(ctx) {
    var proteinInfo = ctx.proteinInfo, flags = ctx.flags;
    var residueCount = proteinInfo.residueIndices.length;
    var turnFlag = [1024 /* T3S */, 2048 /* T4S */, 4096 /* T5S */, 128 /* T3 */, 256 /* T4 */, 512 /* T5 */];
    var helixFlag = [0, 0, 0, 8 /* G */, 1 /* H */, 16 /* I */];
    var helixCheckOrder = ctx.params.oldOrdering ? [4, 3, 5] : [3, 4, 5];
    for (var ni = 0; ni < helixCheckOrder.length; ni++) {
        var n = helixCheckOrder[ni];
        for (var i = 1, il = residueCount - n; i < il; i++) {
            var fI = common_DSSPType.create(flags[i]);
            var fI1 = common_DSSPType.create(flags[i - 1]);
            var fI2 = common_DSSPType.create(flags[i + 1]);
            // TODO rework to elegant solution which will not break instantly
            if (ctx.params.oldOrdering) {
                if ((n === 3 && (common_DSSPType.is(fI, 1 /* H */) || common_DSSPType.is(fI2, 1 /* H */)) || // for 3-10 yield to alpha helix
                    (n === 5 && ((common_DSSPType.is(fI, 1 /* H */) || common_DSSPType.is(fI, 8 /* G */)) || (common_DSSPType.is(fI2, 1 /* H */) || common_DSSPType.is(fI2, 8 /* G */)))))) { // for pi yield to all other helices
                    continue;
                }
            }
            else {
                if ((n === 4 && (common_DSSPType.is(fI, 8 /* G */) || common_DSSPType.is(fI2, 8 /* G */)) || // for alpha helix yield to 3-10
                    (n === 5 && ((common_DSSPType.is(fI, 1 /* H */) || common_DSSPType.is(fI, 8 /* G */)) || (common_DSSPType.is(fI2, 1 /* H */) || common_DSSPType.is(fI2, 8 /* G */)))))) { // for pi yield to all other helices
                    continue;
                }
            }
            if (common_DSSPType.is(fI, turnFlag[n]) && common_DSSPType.is(fI, turnFlag[n - 3]) && // check fI for turn start of proper type
                common_DSSPType.is(fI1, turnFlag[n]) && common_DSSPType.is(fI1, turnFlag[n - 3])) { // check fI1 accordingly
                if (ctx.params.oldDefinition) {
                    for (var k = 0; k < n; k++) {
                        flags[i + k] |= helixFlag[n];
                    }
                }
                else {
                    for (var k = -1; k <= n; k++) {
                        flags[i + k] |= helixFlag[n];
                    }
                }
            }
        }
    }
}
//# sourceMappingURL=helices.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/ladders.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */
function shouldExtendLadder(ladder, bridge) {
    // in order to extend ladders, same type must be present
    if (bridge.type !== ladder.type)
        return false;
    // only extend if residue 1 is sequence neighbor with regard to ladder
    if (bridge.partner1 !== ladder.firstEnd + 1)
        return false;
    if (bridge.type === 0 /* PARALLEL */) {
        if (bridge.partner2 === ladder.secondEnd + 1) {
            return true;
        }
    }
    else {
        if (bridge.partner2 === ladder.secondStart - 1) {
            return true;
        }
    }
    return false;
}
/**
 * For beta structures, we define: a bulge-linked ladder consists of two ladders or bridges of the same type
 * connected by at most one extra residue of one strand and at most four extra residues  on the other strand,
 * all residues in bulge-linked ladders are marked E, including any extra residues.
 */
function resemblesBulge(ladder1, ladder2) {
    if (!(ladder1.type === ladder2.type && ladder2.firstStart - ladder1.firstEnd < 6 &&
        ladder1.firstStart < ladder2.firstStart && ladder2.nextLadder === 0))
        return false;
    if (ladder1.type === 0 /* PARALLEL */) {
        return bulgeCriterion2(ladder1, ladder2);
    }
    else {
        return bulgeCriterion2(ladder2, ladder1);
    }
}
function bulgeCriterion2(ladder1, ladder2) {
    return ladder2.secondStart - ladder1.secondEnd > 0 && ((ladder2.secondStart - ladder1.secondEnd < 6 &&
        ladder2.firstStart - ladder1.firstEnd < 3) || ladder2.secondStart - ladder1.secondEnd < 3);
}
/**
 * ladder=: set of one or more consecutive bridges of identical type
 *
 * Type: E
 */
function assignLadders(ctx) {
    var bridges = ctx.bridges, ladders = ctx.ladders;
    // create ladders
    for (var bridgeIndex = 0; bridgeIndex < bridges.length; bridgeIndex++) {
        var bridge = bridges[bridgeIndex];
        var found = false;
        for (var ladderIndex = 0; ladderIndex < ladders.length; ladderIndex++) {
            var ladder = ladders[ladderIndex];
            if (shouldExtendLadder(ladder, bridge)) {
                found = true;
                ladder.firstEnd++;
                if (bridge.type === 0 /* PARALLEL */) {
                    ladder.secondEnd++;
                }
                else {
                    ladder.secondStart--;
                }
            }
        }
        // no suitable assignment: create new ladder with single bridge as content
        if (!found) {
            ladders[ladders.length] = {
                previousLadder: 0,
                nextLadder: 0,
                firstStart: bridge.partner1,
                firstEnd: bridge.partner1,
                secondStart: bridge.partner2,
                secondEnd: bridge.partner2,
                type: bridge.type
            };
        }
    }
    // connect ladders
    for (var ladderIndex1 = 0; ladderIndex1 < ladders.length; ladderIndex1++) {
        var ladder1 = ladders[ladderIndex1];
        for (var ladderIndex2 = ladderIndex1; ladderIndex2 < ladders.length; ladderIndex2++) {
            var ladder2 = ladders[ladderIndex2];
            if (resemblesBulge(ladder1, ladder2)) {
                ladder1.nextLadder = ladderIndex2;
                ladder2.previousLadder = ladderIndex1;
            }
        }
    }
}
//# sourceMappingURL=ladders.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/bridges.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */

/**
 * Two nonoverlapping stretches of three residues each, i - 1, i, i + 1 and j - 1, j, j + 1,
 * form either a parallel or antiparallel bridge, depending on which of
 * two basic patterns is matched. We assign a bridge between residues i and j
 * if there are two H bonds characteristic of P-structure; in particular,
 *
 * Parallel Bridge(i, j) =:
 *      [Hbond(i - 1, j) and Hbond(j, i + 1)] or
 *      [Hbond(j - 1, i) and Hbond(i, j + 1)]
 *
 * Antiparallel Bridge(i, j) =:
 *      [Hbond(i, j) and Hbond(j, i)] or
 *      [Hbond(i - 1, j + 1) and Hbond(j - 1, i + l)]
 *
 * Type: B
 */
function assignBridges(ctx) {
    var proteinInfo = ctx.proteinInfo, hbonds = ctx.hbonds, flags = ctx.flags, bridges = ctx.bridges;
    var offset = hbonds.offset, b = hbonds.b;
    var i, j;
    for (var k = 0, kl = proteinInfo.residueIndices.length; k < kl; ++k) {
        for (var t = offset[k], _t = offset[k + 1]; t < _t; t++) {
            var l = b[t];
            if (k > l)
                continue;
            // Parallel Bridge(i, j) =: [Hbond(i - 1, j) and Hbond(j, i + 1)]
            i = k + 1; // k is i - 1
            j = l;
            if (i !== j && hbonds.getDirectedEdgeIndex(j, i + 1) !== -1) {
                flags[i] |= 2 /* B */;
                flags[j] |= 2 /* B */;
                // TODO move to constructor, actually omit object all together
                bridges[bridges.length] = new Bridge(i, j, 0 /* PARALLEL */);
            }
            // Parallel Bridge(i, j) =: [Hbond(j - 1, i) and Hbond(i, j + 1)]
            i = k;
            j = l - 1; // l is j + 1
            if (i !== j && hbonds.getDirectedEdgeIndex(j - 1, i) !== -1) {
                flags[i] |= 2 /* B */;
                flags[j] |= 2 /* B */;
                bridges[bridges.length] = new Bridge(j, i, 0 /* PARALLEL */);
            }
            // Antiparallel Bridge(i, j) =: [Hbond(i, j) and Hbond(j, i)]
            i = k;
            j = l;
            if (i !== j && hbonds.getDirectedEdgeIndex(j, i) !== -1) {
                flags[i] |= 2 /* B */;
                flags[j] |= 2 /* B */;
                bridges[bridges.length] = new Bridge(j, i, 1 /* ANTI_PARALLEL */);
            }
            // Antiparallel Bridge(i, j) =: [Hbond(i - 1, j + 1) and Hbond(j - 1, i + l)]
            i = k + 1;
            j = l - 1;
            if (i !== j && hbonds.getDirectedEdgeIndex(j - 1, i + 1) !== -1) {
                flags[i] |= 2 /* B */;
                flags[j] |= 2 /* B */;
                bridges[bridges.length] = new Bridge(j, i, 1 /* ANTI_PARALLEL */);
            }
        }
    }
    bridges.sort(function (a, b) { return a.partner1 > b.partner1 ? 1 : a.partner1 < b.partner1 ? -1 : 0; });
}
//# sourceMappingURL=bridges.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/sheets.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */

function isHelixType(f) {
    return common_DSSPType.is(f, 8 /* G */) || common_DSSPType.is(f, 1 /* H */) || common_DSSPType.is(f, 16 /* I */);
}
/**
 * sheet=: set of one or more ladders connected by shared residues
 *
 * Type: E
 */
function assignSheets(ctx) {
    var ladders = ctx.ladders, flags = ctx.flags;
    for (var ladderIndex = 0; ladderIndex < ladders.length; ladderIndex++) {
        var ladder = ladders[ladderIndex];
        for (var lcount = ladder.firstStart; lcount <= ladder.firstEnd; lcount++) {
            var diff = ladder.firstStart - lcount;
            var l2count = ladder.secondStart - diff;
            if (ladder.firstStart !== ladder.firstEnd) {
                flags[lcount] |= 4 /* E */;
                flags[l2count] |= 4 /* E */;
            }
            else {
                if (!isHelixType(flags[lcount]) && common_DSSPType.is(flags[lcount], 4 /* E */)) {
                    flags[lcount] |= 2 /* B */;
                }
                if (!isHelixType(flags[l2count]) && common_DSSPType.is(flags[l2count], 4 /* E */)) {
                    flags[l2count] |= 2 /* B */;
                }
            }
        }
        if (ladder.nextLadder === 0)
            continue;
        var conladder = ladders[ladder.nextLadder];
        for (var lcount = ladder.firstStart; lcount <= conladder.firstEnd; lcount++) {
            flags[lcount] |= 4 /* E */;
        }
        if (ladder.type === 0 /* PARALLEL */) {
            for (var lcount = ladder.secondStart; lcount <= conladder.secondEnd; lcount++) {
                flags[lcount] |= 4 /* E */;
            }
        }
        else {
            for (var lcount = conladder.secondEnd; lcount <= ladder.secondStart; lcount++) {
                flags[lcount] |= 4 /* E */;
            }
        }
    }
}
//# sourceMappingURL=sheets.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/dihedral-angles.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */


function calculateUnitDihedralAngles(unit, proteinInfo) {
    var cIndices = proteinInfo.cIndices, nIndices = proteinInfo.nIndices, residueIndices = proteinInfo.residueIndices;
    var position = unit.conformation.position;
    var index = unit.model.atomicHierarchy.index;
    var traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex;
    var residueCount = residueIndices.length;
    var p = function (i, v) { return i === -1 ? linear_algebra["Vec3"].setNaN(v) : position(i, v); };
    var cPosPrev = Object(linear_algebra["Vec3"])(), caPosPrev = Object(linear_algebra["Vec3"])(), nPosPrev = Object(linear_algebra["Vec3"])();
    var cPos = Object(linear_algebra["Vec3"])(), caPos = Object(linear_algebra["Vec3"])(), nPos = Object(linear_algebra["Vec3"])();
    var cPosNext = Object(linear_algebra["Vec3"])(), caPosNext = Object(linear_algebra["Vec3"])(), nPosNext = Object(linear_algebra["Vec3"])();
    if (residueCount === 0)
        return { phi: new Float32Array(0), psi: new Float32Array(0) };
    var phi = new Float32Array(residueCount - 1);
    var psi = new Float32Array(residueCount - 1);
    p(-1, cPosPrev);
    p(-1, caPosPrev);
    p(-1, nPosPrev);
    p(cIndices[0], cPos);
    p(traceElementIndex[residueIndices[0]], caPos);
    p(nIndices[0], nPos);
    p(cIndices[1], cPosNext);
    p(traceElementIndex[residueIndices[1]], caPosNext);
    p(nIndices[1], nPosNext);
    for (var i = 0; i < residueCount - 1; ++i) {
        // ignore C-terminal residue as acceptor
        if (index.findAtomOnResidue(residueIndices[i], 'OXT') !== -1)
            continue;
        // returns NaN for missing atoms
        phi[i] = Object(misc["f" /* radToDeg */])(linear_algebra["Vec3"].dihedralAngle(cPosPrev, nPos, caPos, cPos));
        psi[i] = Object(misc["f" /* radToDeg */])(linear_algebra["Vec3"].dihedralAngle(nPos, caPos, cPos, nPosNext));
        cPosPrev = cPos, caPosPrev = caPos, nPosPrev = nPos;
        cPos = cPosNext, caPos = caPosNext, nPos = nPosNext;
        p(cIndices[i + 1], cPosNext);
        p(traceElementIndex[residueIndices[i + 1]], caPosNext);
        p(nIndices[i + 1], nPosNext);
    }
    return { phi: phi, psi: psi };
}
//# sourceMappingURL=dihedral-angles.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary.js
var boundary = __webpack_require__(185);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/trace-lookup.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function calcUnitProteinTraceLookup3D(unit, unitProteinResidues) {
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex;
    var indices = new Uint32Array(unitProteinResidues.length);
    for (var i = 0, il = unitProteinResidues.length; i < il; ++i) {
        indices[i] = traceElementIndex[unitProteinResidues[i]];
    }
    var position = { x: x, y: y, z: z, indices: mol_data_int["SortedArray"].ofSortedArray(indices) };
    return Object(geometry["c" /* GridLookup3D */])(position, Object(boundary["a" /* getBoundary */])(position));
}
//# sourceMappingURL=trace-lookup.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp/protein-info.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */

function getUnitProteinInfo(unit) {
    var index = unit.model.atomicHierarchy.index;
    var proteinElements = unit.proteinElements, residueIndex = unit.residueIndex;
    var residueCount = proteinElements.length;
    var unitProteinResidues = new Uint32Array(residueCount);
    var c = new Int32Array(residueCount);
    var h = new Int32Array(residueCount);
    var o = new Int32Array(residueCount);
    var n = new Int32Array(residueCount);
    for (var i = 0; i < residueCount; ++i) {
        var rI = residueIndex[proteinElements[i]];
        unitProteinResidues[i] = rI;
        c[i] = index.findAtomOnResidue(rI, 'C');
        h[i] = index.findAtomOnResidue(rI, 'H');
        o[i] = index.findAtomOnResidue(rI, 'O');
        n[i] = index.findAtomOnResidue(rI, 'N');
    }
    return {
        residueIndices: mol_data_int["SortedArray"].ofSortedArray(unitProteinResidues),
        cIndices: c,
        hIndices: h,
        oIndices: o,
        nIndices: n,
    };
}
//# sourceMappingURL=protein-info.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure/dssp.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */
















/**
 * TODO bugs to fix:
 * - some turns are not detected correctly: see e.g. pdb:1acj - maybe more than 2 hbonds require some residue to donate electrons
 * - some sheets are not extended correctly: see e.g. pdb:1acj
 * - validate new helix definition
 * - validate new ordering of secondary structure elements
 */
var DSSPComputationParams = {
    oldDefinition: param_definition["ParamDefinition"].Boolean(true, { description: 'Whether to use the old DSSP convention for the annotation of turns and helices, causes them to be two residues shorter' }),
    oldOrdering: param_definition["ParamDefinition"].Boolean(true, { description: 'Alpha-helices are preferred over 3-10 helices' })
};
function computeUnitDSSP(unit, params) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var proteinInfo, residueIndices, lookup3d, hbonds, residueCount, flags, torsionAngles, ladders, bridges, getResidueFlag, getFlagName, ctx, assignment, type, keys, elements, getIndex, i, il, assign, flag;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            proteinInfo = getUnitProteinInfo(unit);
            residueIndices = proteinInfo.residueIndices;
            lookup3d = calcUnitProteinTraceLookup3D(unit, residueIndices);
            hbonds = calcUnitBackboneHbonds(unit, proteinInfo, lookup3d);
            residueCount = residueIndices.length;
            flags = new Uint32Array(residueCount);
            torsionAngles = calculateUnitDihedralAngles(unit, proteinInfo);
            ladders = [];
            bridges = [];
            getResidueFlag = params.oldDefinition ? getOriginalResidueFlag : getUpdatedResidueFlag;
            getFlagName = params.oldOrdering ? getOriginalFlagName : getUpdatedFlagName;
            ctx = {
                params: params,
                getResidueFlag: getResidueFlag,
                getFlagName: getFlagName,
                unit: unit,
                proteinInfo: proteinInfo,
                flags: flags,
                hbonds: hbonds,
                torsionAngles: torsionAngles,
                ladders: ladders,
                bridges: bridges
            };
            assignTurns(ctx);
            assignHelices(ctx);
            assignBends(ctx);
            assignBridges(ctx);
            assignLadders(ctx);
            assignSheets(ctx);
            assignment = getDSSPAssignment(flags, getResidueFlag);
            type = new Uint32Array(residueCount);
            keys = [];
            elements = [];
            getIndex = function (rI) { return mol_data_int["SortedArray"].indexOf(residueIndices, rI); };
            for (i = 0, il = residueIndices.length; i < il; ++i) {
                assign = assignment[i];
                type[i] = assign;
                flag = getResidueFlag(flags[i]);
                // console.log(i, SortedArray.indexOf(residueIndices, i), getFlagName(flags[i]))
                // TODO is this expected behavior? elements will be strictly split depending on 'winning' flag
                if (elements.length === 0 /* would fail at very start */ || flag !== elements[elements.length - 1].flags /* flag changed */) {
                    elements[elements.length] = createElement(mapToKind(assign), flags[i], getResidueFlag);
                }
                keys[i] = elements.length - 1;
            }
            return [2 /*return*/, Object(seconday_structure["a" /* SecondaryStructure */])(type, keys, elements, getIndex)];
        });
    });
}
function createElement(kind, flag, getResidueFlag) {
    // TODO would be nice to add more detailed information
    if (kind === 'helix') {
        return {
            kind: 'helix',
            flags: getResidueFlag(flag)
        };
    }
    else if (kind === 'sheet') {
        return {
            kind: 'sheet',
            flags: getResidueFlag(flag)
        };
    }
    else if (kind === 'turn' || kind === 'bend') {
        return {
            kind: 'turn',
            flags: getResidueFlag(flag)
        };
    }
    else {
        return {
            kind: 'none'
        };
    }
}
function mapToKind(assignment) {
    if (assignment === types["SecondaryStructureType"].SecondaryStructureDssp.H || assignment === types["SecondaryStructureType"].SecondaryStructureDssp.G || assignment === types["SecondaryStructureType"].SecondaryStructureDssp.I) {
        return 'helix';
    }
    else if (assignment === types["SecondaryStructureType"].SecondaryStructureDssp.B || assignment === types["SecondaryStructureType"].SecondaryStructureDssp.E) {
        return 'sheet';
    }
    else if (assignment === types["SecondaryStructureType"].SecondaryStructureDssp.T) {
        return 'turn';
    }
    else if (assignment === types["SecondaryStructureType"].SecondaryStructureDssp.S) {
        return 'bend';
    }
    else {
        return 'none';
    }
}
/** Original priority: H,B,E,G,I,T,S */
function getOriginalResidueFlag(f) {
    if (common_DSSPType.is(f, 1 /* H */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.H;
    if (common_DSSPType.is(f, 4 /* E */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.E;
    if (common_DSSPType.is(f, 2 /* B */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.B;
    if (common_DSSPType.is(f, 8 /* G */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.G;
    if (common_DSSPType.is(f, 16 /* I */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.I;
    if (common_DSSPType.is(f, 64 /* T */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.T;
    if (common_DSSPType.is(f, 32 /* S */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.S;
    return 0 /* None */;
}
function getOriginalFlagName(f) {
    if (common_DSSPType.is(f, 1 /* H */))
        return 'H';
    if (common_DSSPType.is(f, 4 /* E */))
        return 'E';
    if (common_DSSPType.is(f, 2 /* B */))
        return 'B';
    if (common_DSSPType.is(f, 8 /* G */))
        return 'G';
    if (common_DSSPType.is(f, 16 /* I */))
        return 'I';
    if (common_DSSPType.is(f, 64 /* T */))
        return 'T';
    if (common_DSSPType.is(f, 32 /* S */))
        return 'S';
    return '-';
}
/** Version 2.1.0 priority: I,H,B,E,G,T,S */
function getUpdatedResidueFlag(f) {
    if (common_DSSPType.is(f, 16 /* I */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.I;
    if (common_DSSPType.is(f, 1 /* H */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.H;
    if (common_DSSPType.is(f, 4 /* E */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.E;
    if (common_DSSPType.is(f, 2 /* B */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.B;
    if (common_DSSPType.is(f, 8 /* G */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.G;
    if (common_DSSPType.is(f, 64 /* T */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.T;
    if (common_DSSPType.is(f, 32 /* S */))
        return types["SecondaryStructureType"].SecondaryStructureDssp.S;
    return 0 /* None */;
}
function getUpdatedFlagName(f) {
    if (common_DSSPType.is(f, 16 /* I */))
        return 'I';
    if (common_DSSPType.is(f, 1 /* H */))
        return 'H';
    if (common_DSSPType.is(f, 4 /* E */))
        return 'E';
    if (common_DSSPType.is(f, 2 /* B */))
        return 'B';
    if (common_DSSPType.is(f, 8 /* G */))
        return 'G';
    if (common_DSSPType.is(f, 64 /* T */))
        return 'T';
    if (common_DSSPType.is(f, 32 /* S */))
        return 'S';
    return '-';
}
function getDSSPAssignment(flags, getResidueFlag) {
    var type = new Uint32Array(flags.length);
    for (var i = 0, il = flags.length; i < il; ++i) {
        var f = common_DSSPType.create(flags[i]);
        type[i] = getResidueFlag(f);
    }
    return type;
}
//# sourceMappingURL=dssp.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js + 5 modules
var structure_structure = __webpack_require__(27);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-structure-property.js
var custom_structure_property = __webpack_require__(204);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/secondary-structure.js
var secondary_structure = __webpack_require__(280);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model.js
var model = __webpack_require__(243);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








function getSecondaryStructureParams(data) {
    var defaultType = 'model';
    if (data) {
        defaultType = 'dssp';
        for (var i = 0, il = data.models.length; i < il; ++i) {
            var m = data.models[i];
            if (model["Model"].isFromPdbArchive(m) || model["Model"].hasSecondaryStructure(m)) {
                // if there is any secondary structure definition given or if there is
                // an archival model, don't calculate dssp by default
                defaultType = 'model';
                break;
            }
        }
    }
    return {
        type: param_definition["ParamDefinition"].MappedStatic(defaultType, {
            'model': param_definition["ParamDefinition"].EmptyGroup({ label: 'Model' }),
            'dssp': param_definition["ParamDefinition"].Group(DSSPComputationParams, { label: 'DSSP', isFlat: true })
        }, { options: [['model', 'Model'], ['dssp', 'DSSP']] })
    };
}
var SecondaryStructureParams = getSecondaryStructureParams();
var SecondaryStructureProvider = custom_structure_property["a" /* CustomStructureProperty */].createProvider({
    label: 'Secondary Structure',
    descriptor: Object(custom_property["CustomPropertyDescriptor"])({
        name: 'molstar_computed_secondary_structure',
    }),
    type: 'root',
    defaultParams: SecondaryStructureParams,
    getParams: getSecondaryStructureParams,
    isApplicable: function (data) { return true; },
    obtain: function (ctx, data, props) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var p, _a, _b, _c;
        return Object(tslib_es6["__generator"])(this, function (_d) {
            switch (_d.label) {
                case 0:
                    p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(SecondaryStructureParams)), props);
                    _a = p.type.name;
                    switch (_a) {
                        case 'dssp': return [3 /*break*/, 1];
                        case 'model': return [3 /*break*/, 3];
                    }
                    return [3 /*break*/, 5];
                case 1:
                    _b = {};
                    return [4 /*yield*/, computeDssp(data, p.type.params)];
                case 2: return [2 /*return*/, (_b.value = _d.sent(), _b)];
                case 3:
                    _c = {};
                    return [4 /*yield*/, computeModel(data)];
                case 4: return [2 /*return*/, (_c.value = _d.sent(), _c)];
                case 5: return [2 /*return*/];
            }
        });
    }); }
});
function computeDssp(structure, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var map, i, il, u, secondaryStructure;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    map = new Map();
                    i = 0, il = structure.unitSymmetryGroups.length;
                    _a.label = 1;
                case 1:
                    if (!(i < il)) return [3 /*break*/, 4];
                    u = structure.unitSymmetryGroups[i].units[0];
                    if (!structure_structure["g" /* Unit */].isAtomic(u)) return [3 /*break*/, 3];
                    return [4 /*yield*/, computeUnitDSSP(u, props)];
                case 2:
                    secondaryStructure = _a.sent();
                    map.set(u.invariantId, secondaryStructure);
                    _a.label = 3;
                case 3:
                    ++i;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/, map];
            }
        });
    });
}
function computeModel(structure) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var map, i, il, u, secondaryStructure;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            map = new Map();
            for (i = 0, il = structure.unitSymmetryGroups.length; i < il; ++i) {
                u = structure.unitSymmetryGroups[i].units[0];
                if (structure_structure["g" /* Unit */].isAtomic(u)) {
                    secondaryStructure = secondary_structure["a" /* ModelSecondaryStructure */].Provider.get(u.model);
                    if (secondaryStructure) {
                        map.set(u.invariantId, secondaryStructure);
                    }
                }
            }
            return [2 /*return*/, map];
        });
    });
}
//# sourceMappingURL=secondary-structure.js.map

/***/ }),
/* 153 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return geometryLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return assignGeometry; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AtomGeometryAngles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return calcAngles; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return calcPlaneAngle; });
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(30);
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function geometryLabel(geometry) {
    switch (geometry) {
        case 0 /* Spherical */:
            return 'Spherical';
        case 1 /* Terminal */:
            return 'Terminal';
        case 2 /* Linear */:
            return 'Linear';
        case 3 /* Trigonal */:
            return 'Trigonal';
        case 4 /* Tetrahedral */:
            return 'Tetrahedral';
        case 5 /* TrigonalBiPyramidal */:
            return 'Trigonal Bi-Pyramidal';
        case 6 /* Octahedral */:
            return 'Octahedral';
        case 7 /* SquarePlanar */:
            return 'Square Planar';
        case 8 /* Unknown */:
            return 'Unknown';
    }
}
function assignGeometry(totalCoordination) {
    switch (totalCoordination) {
        case 0: return 0 /* Spherical */;
        case 1: return 1 /* Terminal */;
        case 2: return 2 /* Linear */;
        case 3: return 3 /* Trigonal */;
        case 4: return 4 /* Tetrahedral */;
        default: return 8 /* Unknown */;
    }
}
var AtomGeometryAngles = new Map([
    [2 /* Linear */, Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_0__[/* degToRad */ "c"])(180)],
    [3 /* Trigonal */, Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_0__[/* degToRad */ "c"])(120)],
    [4 /* Tetrahedral */, Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_0__[/* degToRad */ "c"])(109.4721)],
    [6 /* Octahedral */, Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_0__[/* degToRad */ "c"])(90)]
]);
// tmp objects for `calcAngles` and `calcPlaneAngle`
var tmpDir1 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var tmpDir2 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var tmpPosA = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var tmpPosB = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var tmpPosX = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
/**
 * Calculate the angles x-a1-a2 for all x where x is a heavy atom (not H) bonded to ap1.
 */
function calcAngles(structure, unitA, indexA, unitB, indexB) {
    var angles = [];
    unitA.conformation.position(unitA.elements[indexA], tmpPosA);
    unitB.conformation.position(unitB.elements[indexB], tmpPosB);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpDir1, tmpPosB, tmpPosA);
    Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* eachBondedAtom */ "g"])(structure, unitA, indexA, function (unitX, indexX) {
        if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* typeSymbol */ "i"])(unitX, indexX) !== "H" /* H */) {
            unitX.conformation.position(unitX.elements[indexX], tmpPosX);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpDir2, tmpPosX, tmpPosA);
            angles.push(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].angle(tmpDir1, tmpDir2));
        }
    });
    return angles;
}
/**
 * Find two neighbours of ap1 to define a plane (if possible) and
 * measure angle out of plane to ap2
 * @param  {AtomProxy} ap1 First atom (angle centre)
 * @param  {AtomProxy} ap2 Second atom (out-of-plane)
 * @return {number}        Angle from plane to second atom
 */
function calcPlaneAngle(structure, unitA, indexA, unitB, indexB) {
    unitA.conformation.position(unitA.elements[indexA], tmpPosA);
    unitB.conformation.position(unitB.elements[indexB], tmpPosB);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpDir1, tmpPosB, tmpPosA);
    var neighbours = [Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])()];
    var ni = 0;
    var unitX1;
    var indexX1;
    Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* eachBondedAtom */ "g"])(structure, unitA, indexA, function (unitX, indexX) {
        if (ni > 1)
            return;
        if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* typeSymbol */ "i"])(unitX, indexX) !== "H" /* H */) {
            unitX1 = unitX;
            indexX1 = indexX;
            unitX.conformation.position(unitX.elements[indexX], tmpPosX);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(neighbours[ni++], tmpPosX, tmpPosA);
        }
    });
    if (ni === 1 && unitX1 && indexX1) {
        Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* eachBondedAtom */ "g"])(structure, unitX1, indexX1, function (unitX, indexX) {
            if (ni > 1)
                return;
            if (unitX === unitA && indexX === indexA)
                return;
            if (Object(_util__WEBPACK_IMPORTED_MODULE_2__[/* typeSymbol */ "i"])(unitX, indexX) !== "H" /* H */) {
                unitX.conformation.position(unitX.elements[indexX], tmpPosX);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(neighbours[ni++], tmpPosX, tmpPosA);
            }
        });
    }
    if (ni !== 2) {
        return;
    }
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].cross(tmpDir2, neighbours[0], neighbours[1]);
    return Math.abs((Math.PI / 2) - _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].angle(tmpDir2, tmpDir1));
}
//# sourceMappingURL=geometry.js.map

/***/ }),
/* 154 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ createModels; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/uuid.js
var uuid = __webpack_require__(194);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/model.js + 1 modules
var model_model = __webpack_require__(352);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic.js
var properties_atomic = __webpack_require__(119);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic/hierarchy.js
var atomic_hierarchy = __webpack_require__(304);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/utils/atomic-index.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function getResidueId(seq_id, ins_code) {
    if (!ins_code)
        return seq_id;
    if (ins_code.length === 1)
        return Object(util["f" /* cantorPairing */])(ins_code.charCodeAt(0), seq_id);
    if (ins_code.length === 2)
        return Object(util["f" /* cantorPairing */])(ins_code.charCodeAt(0), Object(util["f" /* cantorPairing */])(ins_code.charCodeAt(1), seq_id));
    return seq_id + " " + ins_code;
}
function updateMapMapIndex(map, key0, key1, index) {
    if (map.has(key0)) {
        var submap = map.get(key0);
        if (!submap.has(key1)) {
            submap.set(key1, index);
        }
    }
    else {
        var submap = new Map();
        map.set(key0, submap);
        submap.set(key1, index);
    }
}
function missingEntity(k) {
    throw new Error("Missing entity entry for entity id '" + k + "'.");
}
function createMapping(entities, data, segments) {
    return {
        entities: entities,
        segments: segments,
        label_seq_id: mol_data_int["SortedArray"].ofSortedArray(data.residues.label_seq_id.toArray({ array: Int32Array })),
        label_atom_id: data.atoms.label_atom_id,
        auth_atom_id: data.atoms.auth_atom_id,
        label_alt_id: data.atoms.label_alt_id,
        chain_index_entity_index: new Int32Array(data.chains._rowCount),
        entity_index_label_asym_id: new Map(),
        chain_index_label_seq_id: new Map(),
        auth_asym_id_auth_seq_id: new Map(),
        chain_index_auth_seq_id: new Map(),
        label_asym_id: new Map(),
    };
}
var _tempResidueKey = atomic_hierarchy["b" /* AtomicIndex */].EmptyResidueKey();
var atomic_index_Index = /** @class */ (function () {
    function Index(map) {
        this.map = map;
        this.entityIndex = map.entities.getEntityIndex;
        this.residueOffsets = this.map.segments.residueAtomSegments.offsets;
    }
    Index.prototype.getEntityFromChain = function (cI) {
        return this.map.chain_index_entity_index[cI];
    };
    Index.prototype.findEntity = function (label_asym_id) {
        var entityIndex = this.map.label_asym_id.get(label_asym_id);
        return entityIndex !== undefined ? entityIndex : -1;
    };
    Index.prototype.findChainLabel = function (key) {
        var eI = this.entityIndex(key.label_entity_id);
        if (eI < 0 || !this.map.entity_index_label_asym_id.has(eI))
            return -1;
        var cm = this.map.entity_index_label_asym_id.get(eI);
        if (!cm)
            return -1;
        return cm.has(key.label_asym_id) ? cm.get(key.label_asym_id) : -1;
    };
    Index.prototype.findChainAuth = function (key) {
        if (!this.map.auth_asym_id_auth_seq_id.has(key.auth_asym_id))
            return -1;
        var rm = this.map.auth_asym_id_auth_seq_id.get(key.auth_asym_id);
        return rm.has(key.auth_seq_id) ? rm.get(key.auth_seq_id) : -1;
    };
    Index.prototype.findResidue = function (label_entity_id_or_key, label_asym_id, auth_seq_id, pdbx_PDB_ins_code) {
        var key;
        if (arguments.length === 1) {
            key = label_entity_id_or_key;
        }
        else {
            _tempResidueKey.label_entity_id = label_entity_id_or_key;
            _tempResidueKey.label_asym_id = label_asym_id;
            _tempResidueKey.auth_seq_id = auth_seq_id;
            _tempResidueKey.pdbx_PDB_ins_code = pdbx_PDB_ins_code;
            key = _tempResidueKey;
        }
        var cI = this.findChainLabel(key);
        if (cI < 0)
            return -1;
        var rm = this.map.chain_index_auth_seq_id.get(cI);
        var id = getResidueId(key.auth_seq_id, key.pdbx_PDB_ins_code || '');
        return rm.has(id) ? rm.get(id) : -1;
    };
    Index.prototype.findResidueAuth = function (key) {
        var cI = this.findChainAuth(key);
        if (cI < 0)
            return -1;
        var rm = this.map.chain_index_auth_seq_id.get(cI);
        var id = getResidueId(key.auth_seq_id, key.pdbx_PDB_ins_code || '');
        return rm.has(id) ? rm.get(id) : -1;
    };
    Index.prototype.findResidueInsertion = function (key) {
        var cI = this.findChainLabel(key);
        if (cI < 0)
            return -1;
        var rm = this.map.chain_index_label_seq_id.get(cI);
        var id = getResidueId(key.label_seq_id, key.pdbx_PDB_ins_code || '');
        if (rm.has(id))
            return rm.get(id);
        var idx = mol_data_int["SortedArray"].findPredecessorIndex(this.map.label_seq_id, key.label_seq_id);
        var start = atomic_hierarchy["a" /* AtomicHierarchy */].chainStartResidueIndex(this.map.segments, cI);
        if (idx < start)
            return start;
        var end = atomic_hierarchy["a" /* AtomicHierarchy */].chainEndResidueIndexExcl(this.map.segments, cI) - 1;
        if (idx >= end)
            return end;
        return idx;
    };
    Index.prototype.findAtom = function (key) {
        var rI = this.findResidue(key);
        if (rI < 0)
            return -1;
        if (typeof key.label_alt_id === 'undefined') {
            return findAtomByName(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.label_atom_id, key.label_atom_id);
        }
        return findAtomByNameAndAltLoc(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.label_atom_id, this.map.label_alt_id, key.label_atom_id, key.label_alt_id);
    };
    Index.prototype.findAtomAuth = function (key) {
        var rI = this.findResidueAuth(key);
        if (rI < 0)
            return -1;
        if (typeof key.label_alt_id === 'undefined') {
            return findAtomByName(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.auth_atom_id, key.auth_atom_id);
        }
        return findAtomByNameAndAltLoc(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.auth_atom_id, this.map.label_alt_id, key.auth_atom_id, key.label_alt_id);
    };
    Index.prototype.findAtomOnResidue = function (rI, label_atom_id, label_alt_id) {
        if (typeof label_alt_id === 'undefined') {
            return findAtomByName(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.label_atom_id, label_atom_id);
        }
        return findAtomByNameAndAltLoc(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.label_atom_id, this.map.label_alt_id, label_atom_id, label_alt_id);
    };
    Index.prototype.findAtomsOnResidue = function (rI, label_atom_ids) {
        return findAtomByNames(this.residueOffsets[rI], this.residueOffsets[rI + 1], this.map.label_atom_id, label_atom_ids);
    };
    return Index;
}());
function findAtomByName(start, end, data, atomName) {
    for (var i = start; i < end; i++) {
        if (data.value(i) === atomName)
            return i;
    }
    return -1;
}
function findAtomByNames(start, end, data, atomNames) {
    for (var i = start; i < end; i++) {
        if (atomNames.has(data.value(i)))
            return i;
    }
    return -1;
}
function findAtomByNameAndAltLoc(start, end, nameData, altLocData, atomName, altLoc) {
    for (var i = start; i < end; i++) {
        if (nameData.value(i) === atomName && altLocData.value(i) === altLoc)
            return i;
    }
    return -1;
}
function getAtomicIndex(data, entities, segments) {
    var map = createMapping(entities, data, segments);
    var _a = data.residues, label_seq_id = _a.label_seq_id, auth_seq_id = _a.auth_seq_id, pdbx_PDB_ins_code = _a.pdbx_PDB_ins_code;
    var _b = data.chains, label_entity_id = _b.label_entity_id, label_asym_id = _b.label_asym_id, auth_asym_id = _b.auth_asym_id;
    var atomSet = mol_data_int["Interval"].ofBounds(0, data.atoms._rowCount);
    var chainsIt = mol_data_int["Segmentation"].transientSegments(segments.chainAtomSegments, atomSet);
    while (chainsIt.hasNext) {
        var chainSegment = chainsIt.move();
        var chainIndex = chainSegment.index;
        var entityIndex = entities.getEntityIndex(label_entity_id.value(chainIndex));
        if (entityIndex < 0)
            missingEntity(label_entity_id.value(chainIndex));
        map.chain_index_entity_index[chainIndex] = entityIndex;
        var authAsymId = auth_asym_id.value(chainIndex);
        var auth_asym_id_auth_seq_id = map.auth_asym_id_auth_seq_id.get(authAsymId);
        if (!auth_asym_id_auth_seq_id) {
            auth_asym_id_auth_seq_id = new Map();
            map.auth_asym_id_auth_seq_id.set(authAsymId, auth_asym_id_auth_seq_id);
        }
        var labelAsymId = label_asym_id.value(chainIndex);
        if (!map.label_asym_id.has(labelAsymId))
            map.label_asym_id.set(labelAsymId, entityIndex);
        updateMapMapIndex(map.entity_index_label_asym_id, entityIndex, labelAsymId, chainIndex);
        var chain_index_label_seq_id = new Map();
        var chain_index_auth_seq_id = new Map();
        map.chain_index_label_seq_id.set(chainIndex, chain_index_label_seq_id);
        map.chain_index_auth_seq_id.set(chainIndex, chain_index_auth_seq_id);
        var residuesIt = mol_data_int["Segmentation"].transientSegments(segments.residueAtomSegments, atomSet, chainSegment);
        while (residuesIt.hasNext) {
            var residueSegment = residuesIt.move();
            var rI = residueSegment.index;
            var authSeqId = auth_seq_id.value(rI);
            var insCode = pdbx_PDB_ins_code.value(rI);
            chain_index_label_seq_id.set(getResidueId(label_seq_id.value(rI), insCode), rI);
            chain_index_auth_seq_id.set(getResidueId(authSeqId, insCode), rI);
            auth_asym_id_auth_seq_id.set(authSeqId, chainIndex);
        }
    }
    return new atomic_index_Index(map);
}
//# sourceMappingURL=atomic-index.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var model_types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/util.js
var structure_util = __webpack_require__(147);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/utils/atomic-derived.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function getAtomicDerivedData(data, segments, index, chemicalComponentMap) {
    var label_comp_id = data.atoms.label_comp_id;
    var n = data.residues._rowCount;
    var offsets = segments.residueAtomSegments.offsets;
    var traceElementIndex = new Int32Array(n);
    var directionFromElementIndex = new Int32Array(n);
    var directionToElementIndex = new Int32Array(n);
    var moleculeType = new Uint8Array(n);
    var polymerType = new Uint8Array(n);
    var moleculeTypeMap = new Map();
    var polymerTypeMap = new Map();
    for (var i = 0; i < n; ++i) {
        var compId = label_comp_id.value(offsets[i]);
        var chemCompMap = chemicalComponentMap;
        var molType = void 0;
        var polyType = void 0;
        if (moleculeTypeMap.has(compId)) {
            molType = moleculeTypeMap.get(compId);
            polyType = polymerTypeMap.get(compId);
        }
        else {
            var type = void 0;
            if (chemCompMap.has(compId)) {
                type = chemCompMap.get(compId).type;
            }
            else {
                if (!debug["b" /* isProductionMode */])
                    console.info('chemComp not found', compId);
                type = Object(model_types["getComponentType"])(compId);
            }
            molType = Object(model_types["getMoleculeType"])(type, compId);
            // TODO if unknown molecule type, use atom names to guess molecule type
            polyType = Object(model_types["getPolymerType"])(type, molType);
            moleculeTypeMap.set(compId, molType);
            polymerTypeMap.set(compId, polyType);
        }
        moleculeType[i] = molType;
        polymerType[i] = polyType;
        var traceAtomId = Object(structure_util["a" /* getAtomIdForAtomRole */])(polyType, 'trace');
        var traceIndex = index.findAtomsOnResidue(i, traceAtomId);
        if (traceIndex === -1) {
            var coarseAtomId = Object(structure_util["a" /* getAtomIdForAtomRole */])(polyType, 'coarseBackbone');
            traceIndex = index.findAtomsOnResidue(i, coarseAtomId);
        }
        traceElementIndex[i] = traceIndex;
        var directionFromAtomId = Object(structure_util["a" /* getAtomIdForAtomRole */])(polyType, 'directionFrom');
        directionFromElementIndex[i] = index.findAtomsOnResidue(i, directionFromAtomId);
        var directionToAtomId = Object(structure_util["a" /* getAtomIdForAtomRole */])(polyType, 'directionTo');
        directionToElementIndex[i] = index.findAtomsOnResidue(i, directionToAtomId);
    }
    return {
        residue: {
            traceElementIndex: traceElementIndex,
            directionFromElementIndex: directionFromElementIndex,
            directionToElementIndex: directionToElementIndex,
            moleculeType: moleculeType,
            polymerType: polymerType,
        }
    };
}
//# sourceMappingURL=atomic-derived.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/export/categories/atom_site_operator_mapping.js
var atom_site_operator_mapping = __webpack_require__(326);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema.js
var schema = __webpack_require__(135);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/atomic.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













function findHierarchyOffsets(atom_site) {
    if (atom_site._rowCount === 0)
        return { residues: [], chains: [] };
    var start = 0, end = atom_site._rowCount;
    var residues = [start], chains = [start];
    var label_entity_id = atom_site.label_entity_id, label_asym_id = atom_site.label_asym_id, label_seq_id = atom_site.label_seq_id, auth_seq_id = atom_site.auth_seq_id, pdbx_PDB_ins_code = atom_site.pdbx_PDB_ins_code;
    for (var i = start + 1; i < end; i++) {
        var newChain = !label_entity_id.areValuesEqual(i - 1, i) || !label_asym_id.areValuesEqual(i - 1, i);
        var newResidue = newChain
            || !label_seq_id.areValuesEqual(i - 1, i)
            || !auth_seq_id.areValuesEqual(i - 1, i)
            || !pdbx_PDB_ins_code.areValuesEqual(i - 1, i);
        // not checking label_comp_id to allow for MICROHETEROGENEITY
        if (newResidue)
            residues[residues.length] = i;
        if (newChain)
            chains[chains.length] = i;
    }
    return { residues: residues, chains: chains };
}
function substUndefinedColumn(table, a, b) {
    if (!table[a].isDefined) {
        table[a] = table[b];
    }
    if (!table[b].isDefined) {
        table[b] = table[a];
    }
}
function createHierarchyData(atom_site, sourceIndex, offsets) {
    var atoms = db["Table"].ofColumns(properties_atomic["AtomsSchema"], {
        type_symbol: db["Column"].ofArray({ array: db["Column"].mapToArray(atom_site.type_symbol, model_types["ElementSymbol"]), schema: db["Column"].Schema.Aliased(db["Column"].Schema.str) }),
        label_atom_id: atom_site.label_atom_id,
        auth_atom_id: atom_site.auth_atom_id,
        label_alt_id: atom_site.label_alt_id,
        label_comp_id: atom_site.label_comp_id,
        auth_comp_id: atom_site.auth_comp_id,
        pdbx_formal_charge: atom_site.pdbx_formal_charge,
        sourceIndex: sourceIndex
    });
    var residues = db["Table"].view(atom_site, properties_atomic["ResiduesSchema"], offsets.residues);
    // Optimize the numeric columns
    db["Table"].columnToArray(residues, 'label_seq_id', Int32Array);
    db["Table"].columnToArray(residues, 'auth_seq_id', Int32Array);
    var chains = db["Table"].view(atom_site, properties_atomic["ChainsSchema"], offsets.chains);
    // Fix possibly missing auth_/label_ columns
    substUndefinedColumn(atoms, 'label_atom_id', 'auth_atom_id');
    substUndefinedColumn(atoms, 'label_comp_id', 'auth_comp_id');
    substUndefinedColumn(residues, 'label_seq_id', 'auth_seq_id');
    substUndefinedColumn(chains, 'label_asym_id', 'auth_asym_id');
    return { atoms: atoms, residues: residues, chains: chains };
}
function getConformation(atom_site) {
    return {
        id: uuid["a" /* default */].create22(),
        atomId: atom_site.id,
        occupancy: atom_site.occupancy,
        B_iso_or_equiv: atom_site.B_iso_or_equiv,
        xyzDefined: atom_site.Cartn_x.isDefined && atom_site.Cartn_y.isDefined && atom_site.Cartn_z.isDefined,
        x: atom_site.Cartn_x.toArray({ array: Float32Array }),
        y: atom_site.Cartn_y.toArray({ array: Float32Array }),
        z: atom_site.Cartn_z.toArray({ array: Float32Array }),
    };
}
function isHierarchyDataEqual(a, b) {
    // TODO need to cast because of how TS handles type resolution for interfaces https://github.com/Microsoft/TypeScript/issues/15300
    return db["Table"].areEqual(a.chains, b.chains)
        && db["Table"].areEqual(a.residues, b.residues)
        && db["Table"].areEqual(a.atoms, b.atoms);
}
function createChainOperatorMappingAndSubstituteNames(hierarchy, format) {
    var mapping = new Map();
    if (!mmcif["MmcifFormat"].is(format))
        return mapping;
    var entries = Object(schema["toDatabase"])(atom_site_operator_mapping["a" /* AtomSiteOperatorMappingSchema */], format.data.frame).molstar_atom_site_operator_mapping;
    if (entries._rowCount === 0)
        return mapping;
    var labelMap = new Map();
    var authMap = new Map();
    for (var i = 0; i < entries._rowCount; i++) {
        var assembly = entries.assembly_operator_id.valueKind(i) === 0 /* Present */
            ? { id: entries.assembly_id.value(i), operList: [], operId: entries.assembly_operator_id.value(i) }
            : void 0;
        var operator = geometry["h" /* SymmetryOperator */].create(entries.operator_name.value(i), linear_algebra["Mat4"].identity(), {
            assembly: assembly,
            spgrOp: entries.symmetry_operator_index.valueKind(i) === 0 /* Present */ ? entries.symmetry_operator_index.value(i) : void 0,
            hkl: linear_algebra["Vec3"].ofArray(entries.symmetry_hkl.value(i)),
            ncsId: entries.ncs_id.value(i)
        });
        var suffix = entries.suffix.value(i);
        var label = entries.label_asym_id.value(i);
        labelMap.set("" + label + suffix, { name: label, operator: operator });
        var auth = entries.auth_asym_id.value(i);
        authMap.set("" + auth + suffix, auth);
    }
    var _a = hierarchy.chains, label_asym_id = _a.label_asym_id, auth_asym_id = _a.auth_asym_id;
    var mappedLabel = new Array(label_asym_id.rowCount);
    var mappedAuth = new Array(label_asym_id.rowCount);
    for (var i = 0; i < label_asym_id.rowCount; i++) {
        var label = label_asym_id.value(i), auth = auth_asym_id.value(i);
        if (!labelMap.has(label)) {
            mappedLabel[i] = label;
            mappedAuth[i] = auth;
            continue;
        }
        var _b = labelMap.get(label), name_1 = _b.name, operator = _b.operator;
        mapping.set(i, operator);
        mappedLabel[i] = name_1;
        mappedAuth[i] = authMap.get(auth) || auth;
    }
    hierarchy.chains.label_asym_id = db["Column"].ofArray({ array: mappedLabel, valueKind: hierarchy.chains.label_asym_id.valueKind, schema: hierarchy.chains.label_asym_id.schema });
    hierarchy.chains.auth_asym_id = db["Column"].ofArray({ array: mappedAuth, valueKind: hierarchy.chains.auth_asym_id.valueKind, schema: hierarchy.chains.auth_asym_id.schema });
    return mapping;
}
function getAtomicHierarchy(atom_site, sourceIndex, entities, chemicalComponentMap, format, previous) {
    var hierarchyOffsets = findHierarchyOffsets(atom_site);
    var hierarchyData = createHierarchyData(atom_site, sourceIndex, hierarchyOffsets);
    var chainOperatorMapping = createChainOperatorMappingAndSubstituteNames(hierarchyData, format);
    if (previous && isHierarchyDataEqual(previous.atomicHierarchy, hierarchyData)) {
        return {
            sameAsPrevious: true,
            hierarchy: previous.atomicHierarchy,
            chainOperatorMapping: chainOperatorMapping
        };
    }
    var hierarchySegments = {
        residueAtomSegments: mol_data_int["Segmentation"].ofOffsets(hierarchyOffsets.residues, mol_data_int["Interval"].ofBounds(0, atom_site._rowCount)),
        chainAtomSegments: mol_data_int["Segmentation"].ofOffsets(hierarchyOffsets.chains, mol_data_int["Interval"].ofBounds(0, atom_site._rowCount)),
    };
    var index = getAtomicIndex(hierarchyData, entities, hierarchySegments);
    var derived = getAtomicDerivedData(hierarchyData, hierarchySegments, index, chemicalComponentMap);
    var hierarchy = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, hierarchyData), hierarchySegments), { index: index, derived: derived });
    return { sameAsPrevious: false, hierarchy: hierarchy, chainOperatorMapping: chainOperatorMapping };
}
function getAtomicHierarchyAndConformation(atom_site, sourceIndex, entities, chemicalComponentMap, format, previous) {
    var _a = getAtomicHierarchy(atom_site, sourceIndex, entities, chemicalComponentMap, format, previous), sameAsPrevious = _a.sameAsPrevious, hierarchy = _a.hierarchy, chainOperatorMapping = _a.chainOperatorMapping;
    var conformation = getConformation(atom_site);
    return { sameAsPrevious: sameAsPrevious, hierarchy: hierarchy, conformation: conformation, chainOperatorMapping: chainOperatorMapping };
}
//# sourceMappingURL=atomic.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/coarse.js
var properties_coarse = __webpack_require__(414);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int/sorted-ranges.js
var sorted_ranges = __webpack_require__(79);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/utils/coarse-keys.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function getElementKey(map, key, counter) {
    if (map.has(key))
        return map.get(key);
    var ret = counter.index++;
    map.set(key, ret);
    return ret;
}
function getElementSubstructureKeyMap(map, key) {
    if (map.has(key))
        return map.get(key);
    var ret = new Map();
    map.set(key, ret);
    return ret;
}
function createLookUp(entities, chain, seq) {
    var getEntKey = entities.getEntityIndex;
    var findChainKey = function (e, c) {
        var eKey = getEntKey(e);
        if (eKey < 0)
            return -1;
        var cm = chain.get(eKey);
        if (!cm.has(c))
            return -1;
        return cm.get(c);
    };
    var findSequenceKey = function (e, c, s) {
        var eKey = getEntKey(e);
        if (eKey < 0)
            return -1;
        var cm = chain.get(eKey);
        if (cm === undefined)
            return -1;
        var cKey = cm.get(c);
        if (cKey === undefined)
            return -1;
        var sm = seq.get(cKey);
        var elementIndices = sm.elementIndices, seqRanges = sm.seqRanges;
        var idx = sorted_ranges["a" /* default */].firstIntersectionIndex(seqRanges, mol_data_int["OrderedSet"].ofSingleton(s));
        return (idx !== -1 ? elementIndices[idx] : -1);
    };
    return { findChainKey: findChainKey, findSequenceKey: findSequenceKey };
}
function coarse_keys_missingEntity(k) {
    throw new Error("Missing entity entry for entity id '" + k + "'.");
}
function getCoarseKeys(data, entities) {
    var entity_id = data.entity_id, asym_id = data.asym_id, seq_id_begin = data.seq_id_begin, seq_id_end = data.seq_id_end, count = data.count, chainElementSegments = data.chainElementSegments;
    var seqMaps = new Map();
    var chainMaps = new Map(), chainCounter = { index: 0 };
    var chainKey = new Int32Array(count);
    var entityKey = new Int32Array(count);
    var chainToEntity = new Int32Array(chainElementSegments.count);
    for (var i = 0; i < count; i++) {
        entityKey[i] = entities.getEntityIndex(entity_id.value(i));
        if (entityKey[i] < 0)
            coarse_keys_missingEntity(entity_id.value(i));
    }
    for (var cI = 0; cI < chainElementSegments.count; cI++) {
        var start = chainElementSegments.offsets[cI];
        var end = chainElementSegments.offsets[cI + 1];
        var eK = entityKey[start];
        chainToEntity[cI] = eK;
        var map = getElementSubstructureKeyMap(chainMaps, eK);
        var key = getElementKey(map, asym_id.value(start), chainCounter);
        for (var i = start; i < end; i++)
            chainKey[i] = key;
        // create seq_id map for the ranges defined by seq_id_begin and seq_id_end
        var elementIndices = [];
        var seqRanges = [];
        for (var i = start; i < end; i++) {
            var seqStart = seq_id_begin.value(i);
            var seqEnd = seq_id_end.value(i);
            elementIndices.push(i);
            seqRanges.push(seqStart, seqEnd);
        }
        var seqMap = { elementIndices: elementIndices, seqRanges: sorted_ranges["a" /* default */].ofSortedRanges(seqRanges) };
        seqMaps.set(key, seqMap);
    }
    var _a = createLookUp(entities, chainMaps, seqMaps), findChainKey = _a.findChainKey, findSequenceKey = _a.findSequenceKey;
    var getEntityFromChain = function (c) {
        return chainToEntity[c];
    };
    return { chainKey: chainKey, entityKey: entityKey, findSequenceKey: findSequenceKey, findChainKey: findChainKey, getEntityFromChain: getEntityFromChain };
}
//# sourceMappingURL=coarse-keys.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/utils/coarse-ranges.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


// TODO assumes all coarse elements are part of a polymer
// TODO add gaps at the ends of the chains by comparing to the polymer sequence data
function getCoarseRanges(data, chemicalComponentMap) {
    var polymerRanges = [];
    var gapRanges = [];
    var chainIt = mol_data_int["Segmentation"].transientSegments(data.chainElementSegments, mol_data_int["Interval"].ofBounds(0, data.count));
    var seq_id_begin = data.seq_id_begin, seq_id_end = data.seq_id_end;
    while (chainIt.hasNext) {
        var _a = chainIt.move(), start = _a.start, end = _a.end;
        var startIndex = -1;
        var prevSeqEnd = -1;
        for (var i = start; i < end; ++i) {
            var seqEnd = seq_id_end.value(i);
            if (i === start) {
                startIndex = i;
                prevSeqEnd = seq_id_end.value(i);
            }
            else {
                if (prevSeqEnd !== seq_id_begin.value(i) - 1) {
                    polymerRanges.push(startIndex, i - 1);
                    gapRanges.push(i - 1, i);
                    startIndex = i;
                }
            }
            if (i === end - 1) {
                polymerRanges.push(startIndex, i);
            }
            prevSeqEnd = seqEnd;
        }
    }
    return {
        polymerRanges: sorted_ranges["a" /* default */].ofSortedRanges(polymerRanges),
        gapRanges: sorted_ranges["a" /* default */].ofSortedRanges(gapRanges)
    };
}
//# sourceMappingURL=coarse-ranges.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/schema.js
var basic_schema = __webpack_require__(93);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/coarse.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var EmptyCoarse = { hierarchy: properties_coarse["CoarseHierarchy"].Empty, conformation: void 0 };
function getCoarse(data, properties) {
    var ihm_sphere_obj_site = data.ihm_sphere_obj_site, ihm_gaussian_obj_site = data.ihm_gaussian_obj_site;
    if (ihm_sphere_obj_site._rowCount === 0 && ihm_gaussian_obj_site._rowCount === 0)
        return EmptyCoarse;
    var sphereData = getData(ihm_sphere_obj_site);
    var sphereConformation = getSphereConformation(ihm_sphere_obj_site);
    var sphereKeys = getCoarseKeys(sphereData, data.entities);
    var sphereRanges = getCoarseRanges(sphereData, properties.chemicalComponentMap);
    var gaussianData = getData(ihm_gaussian_obj_site);
    var gaussianConformation = getGaussianConformation(ihm_gaussian_obj_site);
    var gaussianKeys = getCoarseKeys(gaussianData, data.entities);
    var gaussianRanges = getCoarseRanges(gaussianData, properties.chemicalComponentMap);
    return {
        hierarchy: {
            isDefined: true,
            spheres: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, sphereData), sphereKeys), sphereRanges),
            gaussians: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, gaussianData), gaussianKeys), gaussianRanges),
        },
        conformation: {
            id: mol_util["c" /* UUID */].create22(),
            spheres: sphereConformation,
            gaussians: gaussianConformation
        }
    };
}
function getSphereConformation(data) {
    return {
        x: data.Cartn_x.toArray({ array: Float32Array }),
        y: data.Cartn_y.toArray({ array: Float32Array }),
        z: data.Cartn_z.toArray({ array: Float32Array }),
        radius: data.object_radius.toArray({ array: Float32Array }),
        rmsf: data.rmsf.toArray({ array: Float32Array })
    };
}
function getGaussianConformation(data) {
    var matrix_space = basic_schema["a" /* BasicSchema */].ihm_gaussian_obj_site.covariance_matrix.space;
    var covariance_matrix = [];
    var cm = data.covariance_matrix;
    for (var i = 0, _i = cm.rowCount; i < _i; i++) {
        covariance_matrix[i] = linear_algebra["Tensor"].toMat3(Object(linear_algebra["Mat3"])(), matrix_space, cm.value(i));
    }
    return {
        x: data.mean_Cartn_x.toArray({ array: Float32Array }),
        y: data.mean_Cartn_y.toArray({ array: Float32Array }),
        z: data.mean_Cartn_z.toArray({ array: Float32Array }),
        weight: data.weight.toArray({ array: Float32Array }),
        covariance_matrix: covariance_matrix
    };
}
function getSegments(asym_id, seq_id_begin, seq_id_end) {
    var chainOffsets = [0];
    for (var i = 1, _i = asym_id.rowCount; i < _i; i++) {
        var newChain = !asym_id.areValuesEqual(i - 1, i);
        if (newChain)
            chainOffsets[chainOffsets.length] = i;
    }
    return {
        chainElementSegments: mol_data_int["Segmentation"].ofOffsets(chainOffsets, mol_data_int["Interval"].ofBounds(0, asym_id.rowCount))
    };
}
function getData(data) {
    var entity_id = data.entity_id, seq_id_begin = data.seq_id_begin, seq_id_end = data.seq_id_end, asym_id = data.asym_id;
    return Object(tslib_es6["__assign"])({ count: entity_id.rowCount, entity_id: entity_id, asym_id: asym_id, seq_id_begin: seq_id_begin, seq_id_end: seq_id_end }, getSegments(asym_id, seq_id_begin, seq_id_end));
}
//# sourceMappingURL=coarse.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/sequence.js
var properties_sequence = __webpack_require__(343);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/sequence.js + 2 modules
var mol_model_sequence = __webpack_require__(335);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/sequence.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function getSequence(data, entities, atomicHierarchy, coarseHierarchy) {
    if (!data.entity_poly_seq || !data.entity_poly_seq._rowCount) {
        return properties_sequence["a" /* default */].fromHierarchy(entities, atomicHierarchy, coarseHierarchy);
    }
    var _a = data.entity_poly_seq, entity_id = _a.entity_id, num = _a.num, mon_id = _a.mon_id;
    var byEntityKey = {};
    var sequences = [];
    var count = entity_id.rowCount;
    var i = 0;
    while (i < count) {
        var start = i;
        while (i < count - 1 && entity_id.areValuesEqual(i, i + 1))
            i++;
        i++;
        var id = entity_id.value(start);
        var compId = db["Column"].window(mon_id, start, i);
        var seqId = db["Column"].window(num, start, i);
        var entityKey = entities.getEntityIndex(id);
        byEntityKey[entityKey] = {
            entityId: id,
            sequence: mol_model_sequence["a" /* Sequence */].ofResidueNames(compId, seqId)
        };
        sequences.push(byEntityKey[entityKey]);
    }
    return { byEntityKey: byEntityKey, sequences: sequences };
}
//# sourceMappingURL=sequence.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/sort.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




function sortAtomSite(ctx, atom_site, start, end) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var indices, label_entity_id, label_asym_id, label_seq_id, entityBuckets, ei, _eI, chainBuckets, cI, _cI, aI;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    indices = Object(util["g" /* createRangeArray */])(start, end - 1);
                    label_entity_id = atom_site.label_entity_id, label_asym_id = atom_site.label_asym_id, label_seq_id = atom_site.label_seq_id;
                    entityBuckets = Object(util["o" /* makeBuckets */])(indices, label_entity_id.value);
                    if (!ctx.shouldUpdate) return [3 /*break*/, 2];
                    return [4 /*yield*/, ctx.update()];
                case 1:
                    _a.sent();
                    _a.label = 2;
                case 2:
                    ei = 0, _eI = entityBuckets.length - 1;
                    _a.label = 3;
                case 3:
                    if (!(ei < _eI)) return [3 /*break*/, 10];
                    chainBuckets = Object(util["o" /* makeBuckets */])(indices, label_asym_id.value, { start: entityBuckets[ei], end: entityBuckets[ei + 1] });
                    cI = 0, _cI = chainBuckets.length - 1;
                    _a.label = 4;
                case 4:
                    if (!(cI < _cI)) return [3 /*break*/, 7];
                    aI = chainBuckets[cI];
                    // are we in HETATM territory?
                    if (label_seq_id.valueKind(aI) !== 0 /* Present */)
                        return [3 /*break*/, 6];
                    Object(util["o" /* makeBuckets */])(indices, label_seq_id.value, { sort: true, start: aI, end: chainBuckets[cI + 1] });
                    if (!ctx.shouldUpdate) return [3 /*break*/, 6];
                    return [4 /*yield*/, ctx.update()];
                case 5:
                    _a.sent();
                    _a.label = 6;
                case 6:
                    cI++;
                    return [3 /*break*/, 4];
                case 7:
                    if (!ctx.shouldUpdate) return [3 /*break*/, 9];
                    return [4 /*yield*/, ctx.update()];
                case 8:
                    _a.sent();
                    _a.label = 9;
                case 9:
                    ei++;
                    return [3 /*break*/, 3];
                case 10:
                    if (Object(array["arrayIsIdentity"])(indices) && indices.length === atom_site._rowCount) {
                        return [2 /*return*/, { atom_site: atom_site, sourceIndex: db["Column"].ofIntArray(indices) }];
                    }
                    return [2 /*return*/, {
                            atom_site: db["Table"].view(atom_site, atom_site._schema, indices),
                            sourceIndex: db["Column"].ofIntArray(indices)
                        }];
            }
        });
    });
}
//# sourceMappingURL=sort.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/utils/atomic-ranges.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function areBackboneConnected(riStart, riEnd, conformation, index, derived) {
    var _a = derived.residue, polymerType = _a.polymerType, traceElementIndex = _a.traceElementIndex, directionFromElementIndex = _a.directionFromElementIndex, directionToElementIndex = _a.directionToElementIndex;
    var ptStart = polymerType[riStart];
    var ptEnd = polymerType[riEnd];
    if (ptStart === 0 /* NA */ || ptEnd === 0 /* NA */)
        return false;
    if (traceElementIndex[riStart] === -1 || traceElementIndex[riEnd] === -1)
        return false;
    var eiStart = index.findAtomsOnResidue(riStart, Object(structure_util["a" /* getAtomIdForAtomRole */])(ptStart, 'backboneStart'));
    var eiEnd = index.findAtomsOnResidue(riEnd, Object(structure_util["a" /* getAtomIdForAtomRole */])(ptEnd, 'backboneEnd'));
    if (eiStart === -1 || eiEnd === -1) {
        eiStart = index.findAtomsOnResidue(riStart, Object(structure_util["a" /* getAtomIdForAtomRole */])(ptStart, 'coarseBackbone'));
        eiEnd = index.findAtomsOnResidue(riEnd, Object(structure_util["a" /* getAtomIdForAtomRole */])(ptEnd, 'coarseBackbone'));
    }
    var x = conformation.x, y = conformation.y, z = conformation.z;
    var pStart = linear_algebra["Vec3"].create(x[eiStart], y[eiStart], z[eiStart]);
    var pEnd = linear_algebra["Vec3"].create(x[eiEnd], y[eiEnd], z[eiEnd]);
    var isCoarse = directionFromElementIndex[riStart] === -1 || directionToElementIndex[riStart] === -1 || directionFromElementIndex[riEnd] === -1 || directionToElementIndex[riEnd] === -1;
    return linear_algebra["Vec3"].distance(pStart, pEnd) < (isCoarse ? 10 : 3);
}
function getAtomicRanges(hierarchy, entities, conformation, sequence) {
    var polymerRanges = [];
    var gapRanges = [];
    var cyclicPolymerMap = new Map();
    var chainIt = mol_data_int["Segmentation"].transientSegments(hierarchy.chainAtomSegments, mol_data_int["Interval"].ofBounds(0, hierarchy.atoms._rowCount));
    var residueIt = mol_data_int["Segmentation"].transientSegments(hierarchy.residueAtomSegments, mol_data_int["Interval"].ofBounds(0, hierarchy.atoms._rowCount));
    var index = hierarchy.index, derived = hierarchy.derived;
    var label_seq_id = hierarchy.residues.label_seq_id;
    var label_entity_id = hierarchy.chains.label_entity_id;
    var _a = derived.residue, moleculeType = _a.moleculeType, traceElementIndex = _a.traceElementIndex;
    var prevSeqId;
    var prevStart;
    var prevEnd;
    var startIndex;
    while (chainIt.hasNext) {
        var chainSegment = chainIt.move();
        residueIt.setSegment(chainSegment);
        prevSeqId = -1;
        prevStart = -1;
        prevEnd = -1;
        startIndex = -1;
        var eI = entities.getEntityIndex(label_entity_id.value(chainSegment.index));
        var seq = sequence.byEntityKey[eI];
        var maxSeqId = seq ? seq.sequence.seqId.value(seq.sequence.seqId.rowCount - 1) : -1;
        // check cyclic peptides, seqIds and distance must be compatible
        var riStart = hierarchy.residueAtomSegments.index[chainSegment.start];
        var riEnd = hierarchy.residueAtomSegments.index[chainSegment.end - 1];
        var seqIdStart = label_seq_id.value(riStart);
        var seqIdEnd = label_seq_id.value(riEnd);
        if (seqIdStart === 1 && seqIdEnd === maxSeqId && conformation.xyzDefined && areBackboneConnected(riStart, riEnd, conformation, index, derived)) {
            cyclicPolymerMap.set(riStart, riEnd);
            cyclicPolymerMap.set(riEnd, riStart);
        }
        while (residueIt.hasNext) {
            var residueSegment = residueIt.move();
            var residueIndex = residueSegment.index;
            var seqId = label_seq_id.value(residueIndex);
            // treat polymers residues that don't have a trace element resolved as gaps
            if (Object(model_types["isPolymer"])(moleculeType[residueIndex]) && traceElementIndex[residueIndex] !== -1) {
                if (startIndex !== -1) {
                    if (seqId !== prevSeqId + 1) {
                        polymerRanges.push(startIndex, prevEnd - 1);
                        gapRanges.push(prevStart, residueSegment.end - 1);
                        startIndex = residueSegment.start;
                    }
                    else if (!residueIt.hasNext) {
                        polymerRanges.push(startIndex, residueSegment.end - 1);
                        // TODO store terminal gaps
                    }
                    else {
                        var riStart_1 = hierarchy.residueAtomSegments.index[residueSegment.start];
                        var riEnd_1 = hierarchy.residueAtomSegments.index[prevEnd - 1];
                        if (conformation.xyzDefined && !areBackboneConnected(riStart_1, riEnd_1, conformation, hierarchy.index, derived)) {
                            polymerRanges.push(startIndex, prevEnd - 1);
                            // add gap even for consecutive residues if they are not connected
                            gapRanges.push(prevStart, residueSegment.end - 1);
                            startIndex = residueSegment.start;
                        }
                    }
                }
                else {
                    startIndex = residueSegment.start; // start polymer
                    // TODO store terminal gaps
                }
            }
            else {
                if (startIndex !== -1) {
                    polymerRanges.push(startIndex, prevEnd - 1);
                    startIndex = -1;
                }
            }
            prevStart = residueSegment.start;
            prevEnd = residueSegment.end;
            prevSeqId = seqId;
        }
    }
    return {
        polymerRanges: sorted_ranges["a" /* default */].ofSortedRanges(polymerRanges),
        gapRanges: sorted_ranges["a" /* default */].ofSortedRanges(gapRanges),
        cyclicPolymerMap: cyclicPolymerMap
    };
}
//# sourceMappingURL=atomic-ranges.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/constants.js
var constants = __webpack_require__(178);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/memoize.js
var memoize = __webpack_require__(155);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/properties.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getMissingResidues(data) {
    var map = new Map();
    var getKey = function (model_num, asym_id, seq_id) {
        return model_num + "|" + asym_id + "|" + seq_id;
    };
    var c = data.pdbx_unobs_or_zero_occ_residues;
    for (var i = 0, il = c._rowCount; i < il; ++i) {
        var key = getKey(c.PDB_model_num.value(i), c.label_asym_id.value(i), c.label_seq_id.value(i));
        map.set(key, { polymer_flag: c.polymer_flag.value(i), occupancy_flag: c.occupancy_flag.value(i) });
    }
    return {
        has: function (model_num, asym_id, seq_id) {
            return map.has(getKey(model_num, asym_id, seq_id));
        },
        get: function (model_num, asym_id, seq_id) {
            return map.get(getKey(model_num, asym_id, seq_id));
        },
        size: map.size
    };
}
function getChemicalComponentMap(data) {
    var map = new Map();
    if (data.chem_comp._rowCount > 0) {
        var id = data.chem_comp.id;
        for (var i = 0, il = id.rowCount; i < il; ++i) {
            map.set(id.value(i), db["Table"].getRow(data.chem_comp, i));
        }
    }
    else {
        var uniqueNames = getUniqueComponentNames(data);
        uniqueNames.forEach(function (n) {
            map.set(n, Object(model_types["getDefaultChemicalComponent"])(n));
        });
    }
    return map;
}
function getSaccharideComponentMap(data) {
    var map = new Map();
    if (data.pdbx_chem_comp_identifier._rowCount > 0) {
        // note that `pdbx_chem_comp_identifier` does not contain
        // a 'SNFG CARBOHYDRATE SYMBOL' entry for 'Unknown' saccharide components
        // so we always need to check `chem_comp` for those
        var _a = data.pdbx_chem_comp_identifier, comp_id = _a.comp_id, type = _a.type, identifier = _a.identifier;
        for (var i = 0, il = comp_id.rowCount; i < il; ++i) {
            if (type.value(i) === 'SNFG CARBOHYDRATE SYMBOL' ||
                type.value(i) === 'SNFG CARB SYMBOL' // legacy, to be removed from mmCIF dictionary
            ) {
                var snfgName = identifier.value(i);
                var saccharideComp = constants["d" /* SaccharidesSnfgMap */].get(snfgName);
                if (saccharideComp) {
                    map.set(comp_id.value(i), saccharideComp);
                }
                else {
                    console.warn("Unknown SNFG name '" + snfgName + "'");
                }
            }
        }
    }
    if (data.chem_comp._rowCount > 0) {
        var _b = data.chem_comp, id = _b.id, type = _b.type;
        for (var i = 0, il = id.rowCount; i < il; ++i) {
            var _id = id.value(i);
            if (map.has(_id))
                continue;
            var _type = type.value(i);
            if (constants["c" /* SaccharideCompIdMap */].has(_id)) {
                map.set(_id, constants["c" /* SaccharideCompIdMap */].get(_id));
            }
            else if (Object(model_types["getMoleculeType"])(_type, _id) === 9 /* Saccharide */) {
                map.set(_id, constants["e" /* UnknownSaccharideComponent */]);
            }
        }
    }
    else {
        var uniqueNames_1 = getUniqueComponentNames(data);
        constants["c" /* SaccharideCompIdMap */].forEach(function (v, k) {
            if (!map.has(k) && uniqueNames_1.has(k))
                map.set(k, v);
        });
    }
    return map;
}
var getUniqueComponentNames = Object(memoize["a" /* memoize1 */])(function (data) {
    var uniqueNames = new Set();
    var _a = data.atom_site, label_comp_id = _a.label_comp_id, auth_comp_id = _a.auth_comp_id;
    var comp_id = label_comp_id.isDefined ? label_comp_id : auth_comp_id;
    for (var i = 0, il = comp_id.rowCount; i < il; ++i) {
        uniqueNames.add(comp_id.value(i));
    }
    return uniqueNames;
});
function getStructAsymMap(data) {
    var map = new Map();
    var _a = data.atom_site, label_asym_id = _a.label_asym_id, auth_asym_id = _a.auth_asym_id, label_entity_id = _a.label_entity_id;
    for (var i = 0, il = label_asym_id.rowCount; i < il; ++i) {
        var id = label_asym_id.value(i);
        if (!map.has(id)) {
            map.set(id, {
                id: id,
                auth_id: auth_asym_id.value(i),
                entity_id: label_entity_id.value(i)
            });
        }
    }
    if (data.struct_asym._rowCount > 0) {
        var _b = data.struct_asym, id = _b.id, entity_id = _b.entity_id;
        for (var i = 0, il = id.rowCount; i < il; ++i) {
            var _id = id.value(i);
            if (!map.has(_id)) {
                map.set(_id, {
                    id: _id,
                    auth_id: '',
                    entity_id: entity_id.value(i)
                });
            }
        }
    }
    return map;
}
function getProperties(data) {
    return {
        missingResidues: getMissingResidues(data),
        chemicalComponentMap: getChemicalComponentMap(data),
        saccharideComponentMap: getSaccharideComponentMap(data),
        structAsymMap: getStructAsymMap(data)
    };
}
//# sourceMappingURL=properties.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/common.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var EntitySubtype = db["Column"].Schema.Aliased(db["Column"].Schema.Str(''));
//# sourceMappingURL=common.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/entities.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getEntities(data, properties) {
    var _a;
    var entityData;
    if (!data.entity.id.isDefined) {
        var entityIds_1 = new Set();
        var ids = [];
        var types = [];
        var _b = data.atom_site, label_entity_id = _b.label_entity_id, label_comp_id = _b.label_comp_id;
        for (var i = 0, il = data.atom_site._rowCount; i < il; i++) {
            var entityId = label_entity_id.value(i);
            if (!entityIds_1.has(entityId)) {
                ids.push(entityId);
                types.push(Object(model_types["getEntityType"])(label_comp_id.value(i)));
                entityIds_1.add(entityId);
            }
        }
        var sphere_entity_id = data.ihm_sphere_obj_site.entity_id;
        for (var i = 0, il = data.ihm_sphere_obj_site._rowCount; i < il; i++) {
            var entityId = sphere_entity_id.value(i);
            if (!entityIds_1.has(entityId)) {
                ids.push(entityId);
                types.push('polymer');
                entityIds_1.add(entityId);
            }
        }
        var gaussian_entity_id = data.ihm_gaussian_obj_site.entity_id;
        for (var i = 0, il = data.ihm_gaussian_obj_site._rowCount; i < il; i++) {
            var entityId = gaussian_entity_id.value(i);
            if (!entityIds_1.has(entityId)) {
                ids.push(entityId);
                types.push('polymer');
                entityIds_1.add(entityId);
            }
        }
        entityData = db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].entity, {
            id: db["Column"].ofArray({ array: ids, schema: basic_schema["a" /* BasicSchema */].entity.id }),
            type: db["Column"].ofArray({ array: types, schema: basic_schema["a" /* BasicSchema */].entity.type }),
        }, ids.length);
    }
    else {
        entityData = data.entity;
    }
    var getEntityIndex = db["Column"].createIndexer(entityData.id);
    //
    var subtypes = new Array(entityData._rowCount);
    subtypes.fill('other');
    var entityIds = new Set();
    var assignSubtype = false;
    if (data.entity_poly && data.entity_poly.type.isDefined) {
        var _c = data.entity_poly, entity_id = _c.entity_id, type = _c.type, _rowCount = _c._rowCount;
        for (var i = 0; i < _rowCount; ++i) {
            var entityId = entity_id.value(i);
            subtypes[getEntityIndex(entityId)] = type.value(i);
            entityIds.add(entityId);
        }
    }
    else {
        assignSubtype = true;
    }
    if (data.pdbx_entity_branch && data.pdbx_entity_branch.entity_id.isDefined) {
        var _d = data.pdbx_entity_branch, entity_id = _d.entity_id, type = _d.type, _rowCount = _d._rowCount;
        for (var i = 0; i < _rowCount; ++i) {
            var entityId = entity_id.value(i);
            subtypes[getEntityIndex(entityId)] = type.value(i);
            entityIds.add(entityId);
        }
    }
    else {
        assignSubtype = true;
    }
    if (assignSubtype) {
        var chemCompType = new Map();
        if (data.chem_comp) {
            var _e = data.chem_comp, id = _e.id, type = _e.type;
            for (var i = 0, il = data.chem_comp._rowCount; i < il; i++) {
                chemCompType.set(id.value(i), type.value(i));
            }
        }
        if (data.atom_site) {
            var _f = data.atom_site, label_entity_id = _f.label_entity_id, label_comp_id = _f.label_comp_id;
            for (var i = 0, il = data.atom_site._rowCount; i < il; i++) {
                var entityId = label_entity_id.value(i);
                if (!entityIds.has(entityId)) {
                    var compId = label_comp_id.value(i);
                    var compType = chemCompType.get(compId) || '';
                    subtypes[getEntityIndex(entityId)] = Object(model_types["getEntitySubtype"])(compId, compType);
                    entityIds.add(entityId);
                }
            }
        }
        // TODO how to handle coarse?
    }
    var subtypeColumn = db["Column"].ofArray({ array: subtypes, schema: EntitySubtype });
    //
    var prdIds = new Array(entityData._rowCount);
    prdIds.fill('');
    if (data.pdbx_molecule && data.pdbx_molecule.prd_id.isDefined) {
        var _g = data.pdbx_molecule, asym_id = _g.asym_id, prd_id = _g.prd_id, _rowCount = _g._rowCount;
        for (var i = 0; i < _rowCount; ++i) {
            var asymId = asym_id.value(i);
            var entityId = (_a = properties.structAsymMap.get(asymId)) === null || _a === void 0 ? void 0 : _a.entity_id;
            if (entityId !== undefined) {
                prdIds[getEntityIndex(entityId)] = prd_id.value(i);
            }
        }
    }
    var prdIdColumn = db["Column"].ofArray({ array: prdIds, schema: db["Column"].Schema.str });
    return {
        data: entityData,
        subtype: subtypeColumn,
        prd_id: prdIdColumn,
        getEntityIndex: getEntityIndex
    };
}
//# sourceMappingURL=entities.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/util.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function getModelGroupName(model_id, data) {
    var ihm_model_group = data.ihm_model_group, ihm_model_group_link = data.ihm_model_group_link;
    var link = db["Table"].pickRow(ihm_model_group_link, function (i) { return ihm_model_group_link.model_id.value(i) === model_id; });
    if (link) {
        var group = db["Table"].pickRow(ihm_model_group, function (i) { return ihm_model_group.id.value(i) === link.group_id; });
        if (group)
            return group.name;
    }
    return '';
}
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/parser.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













function createModels(data, format, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var properties, models, _a, i;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    properties = getProperties(data);
                    if (!(data.ihm_model_list._rowCount > 0)) return [3 /*break*/, 2];
                    return [4 /*yield*/, readIntegrative(ctx, data, properties, format)];
                case 1:
                    _a = _b.sent();
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, readStandard(ctx, data, properties, format)];
                case 3:
                    _a = _b.sent();
                    _b.label = 4;
                case 4:
                    models = _a;
                    for (i = 0; i < models.length; i++) {
                        model_model["a" /* Model */].TrajectoryInfo.set(models[i], { index: i, size: models.length });
                    }
                    return [2 /*return*/, models];
            }
        });
    });
}
/** Standard atomic model */
function createStandardModel(data, atom_site, sourceIndex, entities, properties, format, previous) {
    var atomic = getAtomicHierarchyAndConformation(atom_site, sourceIndex, entities, properties.chemicalComponentMap, format, previous);
    var modelNum = atom_site.pdbx_PDB_model_num.value(0);
    if (previous && atomic.sameAsPrevious) {
        return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, previous), { id: uuid["a" /* default */].create22(), modelNum: modelNum, atomicConformation: atomic.conformation, _dynamicPropertyData: Object.create(null) });
    }
    var coarse = EmptyCoarse;
    var sequence = getSequence(data, entities, atomic.hierarchy, coarse.hierarchy);
    var atomicRanges = getAtomicRanges(atomic.hierarchy, entities, atomic.conformation, sequence);
    var entry = data.entry.id.valueKind(0) === 0 /* Present */
        ? data.entry.id.value(0) : format.name;
    var label = [];
    if (entry)
        label.push(entry);
    if (data.struct.title.valueKind(0) === 0 /* Present */)
        label.push(data.struct.title.value(0));
    return {
        id: uuid["a" /* default */].create22(),
        entryId: entry,
        label: label.join(' | '),
        entry: entry,
        sourceData: format,
        modelNum: modelNum,
        entities: entities,
        sequence: sequence,
        atomicHierarchy: atomic.hierarchy,
        atomicConformation: atomic.conformation,
        atomicRanges: atomicRanges,
        atomicChainOperatorMappinng: atomic.chainOperatorMapping,
        coarseHierarchy: coarse.hierarchy,
        coarseConformation: coarse.conformation,
        properties: properties,
        customProperties: new custom_property["CustomProperties"](),
        _staticPropertyData: Object.create(null),
        _dynamicPropertyData: Object.create(null)
    };
}
/** Integrative model with atomic/coarse parts */
function createIntegrativeModel(data, ihm, properties, format) {
    var atomic = getAtomicHierarchyAndConformation(ihm.atom_site, ihm.atom_site_sourceIndex, ihm.entities, properties.chemicalComponentMap, format);
    var coarse = getCoarse(ihm, properties);
    var sequence = getSequence(data, ihm.entities, atomic.hierarchy, coarse.hierarchy);
    var atomicRanges = getAtomicRanges(atomic.hierarchy, ihm.entities, atomic.conformation, sequence);
    var entry = data.entry.id.valueKind(0) === 0 /* Present */
        ? data.entry.id.value(0) : format.name;
    var label = [];
    if (entry)
        label.push(entry);
    if (data.struct.title.valueKind(0) === 0 /* Present */)
        label.push(data.struct.title.value(0));
    if (ihm.model_name)
        label.push(ihm.model_name);
    if (ihm.model_group_name)
        label.push(ihm.model_group_name);
    return {
        id: uuid["a" /* default */].create22(),
        entryId: entry,
        label: label.join(' | '),
        entry: entry,
        sourceData: format,
        modelNum: ihm.model_id,
        entities: ihm.entities,
        sequence: sequence,
        atomicHierarchy: atomic.hierarchy,
        atomicConformation: atomic.conformation,
        atomicRanges: atomicRanges,
        atomicChainOperatorMappinng: atomic.chainOperatorMapping,
        coarseHierarchy: coarse.hierarchy,
        coarseConformation: coarse.conformation,
        properties: properties,
        customProperties: new custom_property["CustomProperties"](),
        _staticPropertyData: Object.create(null),
        _dynamicPropertyData: Object.create(null)
    };
}
function findModelEnd(num, startIndex) {
    var rowCount = num.rowCount;
    if (!num.isDefined)
        return rowCount;
    var endIndex = startIndex + 1;
    while (endIndex < rowCount && num.areValuesEqual(startIndex, endIndex))
        endIndex++;
    return endIndex;
}
function readStandard(ctx, data, properties, format) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var models, atomCount, entities, modelStart, modelEnd, _a, atom_site, sourceIndex, model;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    models = [];
                    if (!data.atom_site) return [3 /*break*/, 3];
                    atomCount = data.atom_site.id.rowCount;
                    entities = getEntities(data, properties);
                    modelStart = 0;
                    _b.label = 1;
                case 1:
                    if (!(modelStart < atomCount)) return [3 /*break*/, 3];
                    modelEnd = findModelEnd(data.atom_site.pdbx_PDB_model_num, modelStart);
                    return [4 /*yield*/, sortAtomSite(ctx, data.atom_site, modelStart, modelEnd)];
                case 2:
                    _a = _b.sent(), atom_site = _a.atom_site, sourceIndex = _a.sourceIndex;
                    model = createStandardModel(data, atom_site, sourceIndex, entities, properties, format, models.length > 0 ? models[models.length - 1] : void 0);
                    models.push(model);
                    modelStart = modelEnd;
                    return [3 /*break*/, 1];
                case 3: return [2 /*return*/, models];
            }
        });
    });
}
function splitTable(table, col) {
    var ret = new Map();
    var rowCount = table._rowCount;
    var modelStart = 0;
    while (modelStart < rowCount) {
        var modelEnd = findModelEnd(col, modelStart);
        var id = col.value(modelStart);
        ret.set(id, {
            table: db["Table"].window(table, table._schema, modelStart, modelEnd),
            start: modelStart,
            end: modelEnd
        });
        modelStart = modelEnd;
    }
    return ret;
}
function readIntegrative(ctx, data, properties, format) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var entities, atom_sites_modelColumn, atom_sites, sphere_sites, gauss_sites, models, _a, model_id, model_name, i, id, atom_site, atom_site_sourceIndex, e, _b, sorted, sourceIndex, ihm, model;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    entities = getEntities(data, properties);
                    atom_sites_modelColumn = data.atom_site.ihm_model_id.isDefined
                        ? data.atom_site.ihm_model_id : data.atom_site.pdbx_PDB_model_num;
                    atom_sites = splitTable(data.atom_site, atom_sites_modelColumn);
                    sphere_sites = splitTable(data.ihm_sphere_obj_site, data.ihm_sphere_obj_site.model_id);
                    gauss_sites = splitTable(data.ihm_gaussian_obj_site, data.ihm_gaussian_obj_site.model_id);
                    models = [];
                    if (!data.ihm_model_list) return [3 /*break*/, 6];
                    _a = data.ihm_model_list, model_id = _a.model_id, model_name = _a.model_name;
                    i = 0;
                    _c.label = 1;
                case 1:
                    if (!(i < data.ihm_model_list._rowCount)) return [3 /*break*/, 6];
                    id = model_id.value(i);
                    atom_site = void 0, atom_site_sourceIndex = void 0;
                    if (!atom_sites.has(id)) return [3 /*break*/, 3];
                    e = atom_sites.get(id);
                    return [4 /*yield*/, sortAtomSite(ctx, data.atom_site, e.start, e.end)];
                case 2:
                    _b = _c.sent(), sorted = _b.atom_site, sourceIndex = _b.sourceIndex;
                    atom_site = sorted;
                    atom_site_sourceIndex = sourceIndex;
                    return [3 /*break*/, 4];
                case 3:
                    atom_site = db["Table"].window(data.atom_site, data.atom_site._schema, 0, 0);
                    atom_site_sourceIndex = db["Column"].ofIntArray([]);
                    _c.label = 4;
                case 4:
                    ihm = {
                        model_id: id,
                        model_name: model_name.value(i),
                        model_group_name: getModelGroupName(id, data),
                        entities: entities,
                        atom_site: atom_site,
                        atom_site_sourceIndex: atom_site_sourceIndex,
                        ihm_sphere_obj_site: sphere_sites.has(id) ? sphere_sites.get(id).table : db["Table"].window(data.ihm_sphere_obj_site, data.ihm_sphere_obj_site._schema, 0, 0),
                        ihm_gaussian_obj_site: gauss_sites.has(id) ? gauss_sites.get(id).table : db["Table"].window(data.ihm_gaussian_obj_site, data.ihm_gaussian_obj_site._schema, 0, 0)
                    };
                    model = createIntegrativeModel(data, ihm, properties, format);
                    models.push(model);
                    _c.label = 5;
                case 5:
                    i++;
                    return [3 /*break*/, 1];
                case 6: return [2 /*return*/, models];
            }
        });
    });
}
//# sourceMappingURL=parser.js.map

/***/ }),
/* 155 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return memoizeLatest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return memoize1; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
/** Cache the latest result from calls to a function with any number of arguments */
function memoizeLatest(f) {
    var lastArgs = void 0, value = void 0;
    return function () {
        var args = [];
        for (var _a = 0; _a < arguments.length; _a++) {
            args[_a] = arguments[_a];
        }
        if (!lastArgs || lastArgs.length !== args.length) {
            lastArgs = args;
            value = f.apply(void 0, args);
            return value;
        }
        for (var i = 0, _i = args.length; i < _i; i++) {
            if (args[i] !== lastArgs[i]) {
                lastArgs = args;
                value = f.apply(void 0, args);
                return value;
            }
        }
        return value;
    };
}
/** Cache all results from calls to a function with a single argument */
function memoize1(f) {
    var cache = new Map();
    return function (a) {
        if (cache.has(a))
            return cache.get(a);
        var v = f(a);
        cache.set(a, v);
        return v;
    };
}
//# sourceMappingURL=memoize.js.map

/***/ }),
/* 156 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return structureUnion; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return structureAreEqual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return structureAreIntersecting; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return structureIntersect; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return structureSubtract; });
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function structureUnion(source, structures) {
    if (structures.length === 0)
        return _structure__WEBPACK_IMPORTED_MODULE_0__[/* Structure */ "c"].Empty;
    if (structures.length === 1)
        return structures[0];
    var unitMap = new Map();
    var fullUnits = new Set();
    for (var _a = 0, structures_1 = structures; _a < structures_1.length; _a++) {
        var units = structures_1[_a].units;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var u = units[i];
            if (unitMap.has(u.id)) {
                // check if there is anything more to union in this particual unit.
                if (fullUnits.has(u.id))
                    continue;
                var merged = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].union(unitMap.get(u.id), u.elements);
                unitMap.set(u.id, merged);
                if (merged.length === source.unitMap.get(u.id).elements.length)
                    fullUnits.add(u.id);
            }
            else {
                unitMap.set(u.id, u.elements);
                if (u.elements.length === source.unitMap.get(u.id).elements.length)
                    fullUnits.add(u.id);
            }
        }
    }
    var builder = source.subsetBuilder(true);
    unitMap.forEach(buildUnion, builder);
    return builder.getStructure();
}
function buildUnion(elements, id) {
    this.setUnit(id, elements);
}
function structureAreEqual(sA, sB) {
    if (sA === sB)
        return true;
    if (sA.units.length !== sB.units.length)
        return false;
    var aU = sA.units, bU = sB.unitMap;
    for (var i = 0, _i = aU.length; i < _i; i++) {
        var u = aU[i];
        if (!bU.has(u.id))
            return false;
        var v = bU.get(u.id);
        if (!_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].areEqual(u.elements, v.elements))
            return false;
    }
    return true;
}
function structureAreIntersecting(sA, sB) {
    if (sA === sB)
        return true;
    var a, b;
    if (sA.units.length < sB.units.length) {
        a = sA;
        b = sB;
    }
    else {
        a = sB;
        b = sA;
    }
    var aU = a.units, bU = b.unitMap;
    for (var i = 0, _i = aU.length; i < _i; i++) {
        var u = aU[i];
        if (!bU.has(u.id))
            continue;
        var v = bU.get(u.id);
        if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].areIntersecting(u.elements, v.elements))
            return true;
    }
    return false;
}
function structureIntersect(sA, sB) {
    if (sA === sB)
        return sA;
    if (!structureAreIntersecting(sA, sB))
        return _structure__WEBPACK_IMPORTED_MODULE_0__[/* Structure */ "c"].Empty;
    var a, b;
    if (sA.units.length < sB.units.length) {
        a = sA;
        b = sB;
    }
    else {
        a = sB;
        b = sA;
    }
    var aU = a.units, bU = b.unitMap;
    var units = [];
    for (var i = 0, _i = aU.length; i < _i; i++) {
        var u = aU[i];
        if (!bU.has(u.id))
            continue;
        var v = bU.get(u.id);
        if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].areIntersecting(u.elements, v.elements)) {
            var int = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].intersect(u.elements, v.elements);
            units[units.length] = u.getChild(int);
        }
    }
    return _structure__WEBPACK_IMPORTED_MODULE_0__[/* Structure */ "c"].create(units, { parent: sA.parent || sB.parent });
}
function structureSubtract(a, b) {
    if (a === b)
        return _structure__WEBPACK_IMPORTED_MODULE_0__[/* Structure */ "c"].Empty;
    if (!structureAreIntersecting(a, b))
        return a;
    var aU = a.units, bU = b.unitMap;
    var units = [];
    for (var i = 0, _i = aU.length; i < _i; i++) {
        var u = aU[i];
        if (!bU.has(u.id)) {
            units[units.length] = u;
            continue;
        }
        var v = bU.get(u.id);
        var sub = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].subtract(u.elements, v.elements);
        if (sub.length > 0) {
            units[units.length] = u.getChild(sub);
        }
    }
    return _structure__WEBPACK_IMPORTED_MODULE_0__[/* Structure */ "c"].create(units, { parent: a.parent || b.parent });
}
//# sourceMappingURL=structure-set.js.map

/***/ }),
/* 157 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return utf8Write; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return utf8Read; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return utf8ByteCount; });
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from https://github.com/rcsb/mmtf-javascript
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function utf8Write(data, offset, str) {
    for (var i = 0, l = str.length; i < l; i++) {
        var codePoint = str.charCodeAt(i);
        // One byte of UTF-8
        if (codePoint < 0x80) {
            data[offset++] = codePoint >>> 0 & 0x7f | 0x00;
            continue;
        }
        // Two bytes of UTF-8
        if (codePoint < 0x800) {
            data[offset++] = codePoint >>> 6 & 0x1f | 0xc0;
            data[offset++] = codePoint >>> 0 & 0x3f | 0x80;
            continue;
        }
        // Three bytes of UTF-8.
        if (codePoint < 0x10000) {
            data[offset++] = codePoint >>> 12 & 0x0f | 0xe0;
            data[offset++] = codePoint >>> 6 & 0x3f | 0x80;
            data[offset++] = codePoint >>> 0 & 0x3f | 0x80;
            continue;
        }
        // Four bytes of UTF-8
        if (codePoint < 0x110000) {
            data[offset++] = codePoint >>> 18 & 0x07 | 0xf0;
            data[offset++] = codePoint >>> 12 & 0x3f | 0x80;
            data[offset++] = codePoint >>> 6 & 0x3f | 0x80;
            data[offset++] = codePoint >>> 0 & 0x3f | 0x80;
            continue;
        }
        throw new Error('bad codepoint ' + codePoint);
    }
}
var __chars = function () {
    var data = [];
    for (var i = 0; i < 1024; i++)
        data[i] = String.fromCharCode(i);
    return data;
}();
function throwError(err) {
    throw new Error(err);
}
function _utf8Read(data, offset, length) {
    var chars = __chars;
    var str = void 0, chunk = [], chunkSize = 512, chunkOffset = 0;
    for (var i = offset, end = offset + length; i < end; i++) {
        var byte = data[i];
        if ((byte & 0x80) === 0x00) {
            // One byte character
            chunk[chunkOffset++] = chars[byte];
        }
        else if ((byte & 0xe0) === 0xc0) {
            // Two byte character
            chunk[chunkOffset++] = chars[((byte & 0x0f) << 6) | (data[++i] & 0x3f)];
        }
        else if ((byte & 0xf0) === 0xe0) {
            // Three byte character
            chunk[chunkOffset++] = String.fromCharCode(((byte & 0x0f) << 12) |
                ((data[++i] & 0x3f) << 6) |
                ((data[++i] & 0x3f) << 0));
        }
        else if ((byte & 0xf8) === 0xf0) {
            // Four byte character
            chunk[chunkOffset++] = String.fromCharCode(((byte & 0x07) << 18) |
                ((data[++i] & 0x3f) << 12) |
                ((data[++i] & 0x3f) << 6) |
                ((data[++i] & 0x3f) << 0));
        }
        else
            throwError('Invalid byte ' + byte.toString(16));
        if (chunkOffset === chunkSize) {
            str = str || [];
            str[str.length] = chunk.join('');
            chunkOffset = 0;
        }
    }
    if (!str)
        return chunk.slice(0, chunkOffset).join('');
    if (chunkOffset > 0) {
        str[str.length] = chunk.slice(0, chunkOffset).join('');
    }
    return str.join('');
}
var utf8Decoder = (typeof TextDecoder !== 'undefined') ? new TextDecoder() : undefined;
function utf8Read(data, offset, length) {
    if (utf8Decoder) {
        var input = (offset || length !== data.length) ? data.subarray(offset, offset + length) : data;
        return utf8Decoder.decode(input);
    }
    else {
        return _utf8Read(data, offset, length);
    }
}
function utf8ByteCount(str) {
    var count = 0;
    for (var i = 0, l = str.length; i < l; i++) {
        var codePoint = str.charCodeAt(i);
        if (codePoint < 0x80) {
            count += 1;
            continue;
        }
        if (codePoint < 0x800) {
            count += 2;
            continue;
        }
        if (codePoint < 0x10000) {
            count += 3;
            continue;
        }
        if (codePoint < 0x110000) {
            count += 4;
            continue;
        }
        throwError('bad codepoint ' + codePoint);
    }
    return count;
}
//# sourceMappingURL=utf8.js.map

/***/ }),
/* 158 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* WEBPACK VAR INJECTION */(function(setImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Canvas3DParams", function() { return Canvas3DParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultCanvas3DParams", function() { return DefaultCanvas3DParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Canvas3D", function() { return Canvas3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(279);
/* harmony import */ var _mol_util_now__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(83);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(84);
/* harmony import */ var _mol_gl_renderer__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(393);
/* harmony import */ var _controls_trackball__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(394);
/* harmony import */ var _camera_util__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(176);
/* harmony import */ var _mol_gl_webgl_context__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(333);
/* harmony import */ var _mol_repr_representation__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(40);
/* harmony import */ var _mol_gl_scene__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(263);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(23);
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(232);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(2);
/* harmony import */ var _helper_bounding_sphere_helper__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(395);
/* harmony import */ var _mol_util_set__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(90);
/* harmony import */ var _helper_interaction_events__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(415);
/* harmony import */ var _passes_postprocessing__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(318);
/* harmony import */ var _passes_multi_sample__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(319);
/* harmony import */ var _mol_gl_compute_util__WEBPACK_IMPORTED_MODULE_19__ = __webpack_require__(148);
/* harmony import */ var _passes_draw__WEBPACK_IMPORTED_MODULE_20__ = __webpack_require__(331);
/* harmony import */ var _passes_pick__WEBPACK_IMPORTED_MODULE_21__ = __webpack_require__(416);
/* harmony import */ var _passes_image__WEBPACK_IMPORTED_MODULE_22__ = __webpack_require__(417);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__ = __webpack_require__(11);
/* harmony import */ var _mol_util_debug__WEBPACK_IMPORTED_MODULE_24__ = __webpack_require__(61);
/* harmony import */ var _helper_camera_helper__WEBPACK_IMPORTED_MODULE_25__ = __webpack_require__(284);
/* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_26__ = __webpack_require__(151);
/* harmony import */ var _helper_handle_helper__WEBPACK_IMPORTED_MODULE_27__ = __webpack_require__(396);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */




























var Canvas3DParams = {
    camera: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group({
        mode: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Select('perspective', [['perspective', 'Perspective'], ['orthographic', 'Orthographic']], { label: 'Camera' }),
        helper: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_helper_camera_helper__WEBPACK_IMPORTED_MODULE_25__[/* CameraHelperParams */ "b"], { isFlat: true })
    }, { pivot: 'mode' }),
    cameraFog: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].MappedStatic('on', {
        on: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group({
            intensity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Numeric(50, { min: 1, max: 100, step: 1 }),
        }),
        off: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group({})
    }, { cycle: true, description: 'Show fog in the distance' }),
    cameraClipping: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group({
        radius: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Numeric(100, { min: 0, max: 99, step: 1 }, { label: 'Clipping', description: 'How much of the scene to show.' }),
        far: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Boolean(true, { description: 'Hide scene in the distance' }),
    }, { pivot: 'radius' }),
    cameraResetDurationMs: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Numeric(250, { min: 0, max: 1000, step: 1 }, { description: 'The time it takes to reset the camera.' }),
    transparentBackground: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Boolean(false),
    multiSample: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_passes_multi_sample__WEBPACK_IMPORTED_MODULE_18__[/* MultiSampleParams */ "a"]),
    postprocessing: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_passes_postprocessing__WEBPACK_IMPORTED_MODULE_17__[/* PostprocessingParams */ "a"]),
    renderer: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_mol_gl_renderer__WEBPACK_IMPORTED_MODULE_5__[/* RendererParams */ "a"]),
    trackball: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_controls_trackball__WEBPACK_IMPORTED_MODULE_6__[/* TrackballControlsParams */ "b"]),
    debug: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_helper_bounding_sphere_helper__WEBPACK_IMPORTED_MODULE_14__[/* DebugHelperParams */ "b"]),
    handle: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].Group(_helper_handle_helper__WEBPACK_IMPORTED_MODULE_27__[/* HandleHelperParams */ "b"]),
};
var DefaultCanvas3DParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_13__["ParamDefinition"].getDefaultValues(Canvas3DParams);

var requestAnimationFrame = typeof window !== 'undefined' ? window.requestAnimationFrame : function (f) { return setImmediate(function () { return f(Date.now()); }); };
var Canvas3D;
(function (Canvas3D) {
    function fromCanvas(canvas, props) {
        if (props === void 0) { props = {}; }
        var gl = Object(_mol_gl_webgl_context__WEBPACK_IMPORTED_MODULE_8__[/* getGLContext */ "c"])(canvas, {
            alpha: true,
            antialias: true,
            depth: true,
            preserveDrawingBuffer: true,
            premultipliedAlpha: false,
        });
        if (gl === null)
            throw new Error('Could not create a WebGL rendering context');
        var input = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_4__[/* default */ "c"].fromElement(canvas);
        var webgl = Object(_mol_gl_webgl_context__WEBPACK_IMPORTED_MODULE_8__[/* createContext */ "b"])(gl);
        if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"]) {
            var loseContextExt_1 = gl.getExtension('WEBGL_lose_context');
            if (loseContextExt_1) {
                canvas.addEventListener('mousedown', function (e) {
                    if (webgl.isContextLost)
                        return;
                    if (!e.shiftKey || !e.ctrlKey || !e.altKey)
                        return;
                    if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                        console.log('lose context');
                    loseContextExt_1.loseContext();
                    setTimeout(function () {
                        if (!webgl.isContextLost)
                            return;
                        if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                            console.log('restore context');
                        loseContextExt_1.restoreContext();
                    }, 1000);
                }, false);
            }
        }
        // https://www.khronos.org/webgl/wiki/HandlingContextLost
        canvas.addEventListener('webglcontextlost', function (e) {
            webgl.setContextLost();
            e.preventDefault();
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                console.log('context lost');
        }, false);
        canvas.addEventListener('webglcontextrestored', function () {
            if (!webgl.isContextLost)
                return;
            webgl.handleContextRestored();
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                console.log('context restored');
        }, false);
        return Canvas3D.create(webgl, input, props);
    }
    Canvas3D.fromCanvas = fromCanvas;
    function create(webgl, input, props) {
        if (props === void 0) { props = {}; }
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultCanvas3DParams), props);
        var reprRenderObjects = new Map();
        var reprUpdatedSubscriptions = new Map();
        var reprCount = new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* BehaviorSubject */ "a"](0);
        var startTime = Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_2__[/* now */ "b"])();
        var didDraw = new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* BehaviorSubject */ "a"](0);
        var gl = webgl.gl, contextRestored = webgl.contextRestored;
        var width = gl.drawingBufferWidth;
        var height = gl.drawingBufferHeight;
        var scene = _mol_gl_scene__WEBPACK_IMPORTED_MODULE_10__[/* default */ "a"].create(webgl);
        var camera = new _camera__WEBPACK_IMPORTED_MODULE_12__[/* Camera */ "a"]({
            position: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(0, 0, 100),
            mode: p.camera.mode,
            fog: p.cameraFog.name === 'on' ? p.cameraFog.params.intensity : 0,
            clipFar: p.cameraClipping.far
        });
        var controls = _controls_trackball__WEBPACK_IMPORTED_MODULE_6__[/* TrackballControls */ "a"].create(input, camera, p.trackball);
        var renderer = _mol_gl_renderer__WEBPACK_IMPORTED_MODULE_5__[/* default */ "b"].create(webgl, p.renderer);
        var debugHelper = new _helper_bounding_sphere_helper__WEBPACK_IMPORTED_MODULE_14__[/* BoundingSphereHelper */ "a"](webgl, scene, p.debug);
        var handleHelper = new _helper_handle_helper__WEBPACK_IMPORTED_MODULE_27__[/* HandleHelper */ "a"](webgl, p.handle);
        var interactionHelper = new _helper_interaction_events__WEBPACK_IMPORTED_MODULE_16__[/* Canvas3dInteractionHelper */ "a"](identify, getLoci, input);
        var drawPass = new _passes_draw__WEBPACK_IMPORTED_MODULE_20__[/* DrawPass */ "a"](webgl, renderer, scene, camera, debugHelper, handleHelper, {
            cameraHelper: p.camera.helper
        });
        var pickPass = new _passes_pick__WEBPACK_IMPORTED_MODULE_21__[/* PickPass */ "a"](webgl, renderer, scene, camera, handleHelper, 0.5);
        var postprocessing = new _passes_postprocessing__WEBPACK_IMPORTED_MODULE_17__[/* PostprocessingPass */ "b"](webgl, camera, drawPass, p.postprocessing);
        var multiSample = new _passes_multi_sample__WEBPACK_IMPORTED_MODULE_18__[/* MultiSamplePass */ "b"](webgl, camera, drawPass, postprocessing, p.multiSample);
        var drawPending = false;
        var cameraResetRequested = false;
        var nextCameraResetDuration = void 0;
        var nextCameraResetSnapshot = void 0;
        function getLoci(pickingId) {
            var loci = _mol_model_loci__WEBPACK_IMPORTED_MODULE_11__["EmptyLoci"];
            var repr = _mol_repr_representation__WEBPACK_IMPORTED_MODULE_9__[/* Representation */ "a"].Empty;
            loci = handleHelper.getLoci(pickingId);
            reprRenderObjects.forEach(function (_, _repr) {
                var _loci = _repr.getLoci(pickingId);
                if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_11__["isEmptyLoci"])(_loci)) {
                    if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_11__["isEmptyLoci"])(loci)) {
                        console.warn('found another loci, this should not happen');
                    }
                    loci = _loci;
                    repr = _repr;
                }
            });
            return { loci: loci, repr: repr };
        }
        function mark(reprLoci, action) {
            var repr = reprLoci.repr, loci = reprLoci.loci;
            var changed = false;
            if (repr) {
                changed = repr.mark(loci, action);
            }
            else {
                changed = handleHelper.mark(loci, action);
                reprRenderObjects.forEach(function (_, _repr) { changed = _repr.mark(loci, action) || changed; });
            }
            if (changed) {
                scene.update(void 0, true);
                handleHelper.scene.update(void 0, true);
                var prevPickDirty = pickPass.pickDirty;
                draw(true);
                pickPass.pickDirty = prevPickDirty; // marking does not change picking buffers
            }
        }
        function render(force) {
            if (webgl.isContextLost)
                return false;
            var didRender = false;
            controls.update(currentTime);
            _camera_util__WEBPACK_IMPORTED_MODULE_7__[/* Viewport */ "a"].set(camera.viewport, 0, 0, width, height);
            var cameraChanged = camera.update();
            multiSample.update(force || cameraChanged, currentTime);
            if (force || cameraChanged || multiSample.enabled) {
                renderer.setViewport(0, 0, width, height);
                if (multiSample.enabled) {
                    multiSample.render(true, p.transparentBackground);
                }
                else {
                    drawPass.render(!postprocessing.enabled, p.transparentBackground);
                    if (postprocessing.enabled)
                        postprocessing.render(true);
                }
                pickPass.pickDirty = true;
                didRender = true;
            }
            return didRender;
        }
        var forceNextDraw = false;
        var forceDrawAfterAllCommited = false;
        var currentTime = 0;
        function draw(force) {
            if (render(!!force || forceNextDraw)) {
                didDraw.next(Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_2__[/* now */ "b"])() - startTime);
            }
            forceNextDraw = false;
            drawPending = false;
        }
        function requestDraw(force) {
            if (drawPending)
                return;
            drawPending = true;
            forceNextDraw = !!force;
        }
        function animate() {
            currentTime = Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_2__[/* now */ "b"])();
            commit();
            camera.transition.tick(currentTime);
            draw(false);
            if (!camera.transition.inTransition && !webgl.isContextLost) {
                interactionHelper.tick(currentTime);
            }
            requestAnimationFrame(animate);
        }
        function identify(x, y) {
            return webgl.isContextLost ? undefined : pickPass.identify(x, y);
        }
        function commit(isSynchronous) {
            if (isSynchronous === void 0) { isSynchronous = false; }
            var allCommited = commitScene(isSynchronous);
            // Only reset the camera after the full scene has been commited.
            if (allCommited) {
                resolveCameraReset();
                if (forceDrawAfterAllCommited) {
                    if (debugHelper.isEnabled)
                        debugHelper.update();
                    draw(true);
                    forceDrawAfterAllCommited = false;
                }
            }
        }
        function resolveCameraReset() {
            if (!cameraResetRequested)
                return;
            var _a = scene.boundingSphereVisible, center = _a.center, radius = _a.radius;
            if (radius > 0) {
                var duration = nextCameraResetDuration === undefined ? p.cameraResetDurationMs : nextCameraResetDuration;
                var focus_1 = camera.getFocus(center, radius);
                var snapshot = nextCameraResetSnapshot ? Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, focus_1), nextCameraResetSnapshot) : focus_1;
                camera.setState(snapshot, duration);
            }
            nextCameraResetDuration = void 0;
            nextCameraResetSnapshot = void 0;
            cameraResetRequested = false;
        }
        var oldBoundingSphereVisible = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"])();
        var cameraSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"])();
        function shouldResetCamera() {
            if (camera.state.radiusMax === 0)
                return true;
            if (camera.transition.inTransition || nextCameraResetSnapshot)
                return false;
            var cameraSphereOverlapsNone = true;
            _mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"].set(cameraSphere, camera.state.target, camera.state.radius);
            // check if any renderable has moved outside of the old bounding sphere
            // and if no renderable is overlapping with the camera sphere
            for (var _i = 0, _a = scene.renderables; _i < _a.length; _i++) {
                var r = _a[_i];
                if (!r.state.visible)
                    continue;
                var b = r.values.boundingSphere.ref.value;
                if (!b.radius)
                    continue;
                if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"].includes(oldBoundingSphereVisible, b))
                    return true;
                if (_mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"].overlaps(cameraSphere, b))
                    cameraSphereOverlapsNone = false;
            }
            return cameraSphereOverlapsNone;
        }
        var sceneCommitTimeoutMs = 250;
        function commitScene(isSynchronous) {
            if (!scene.needsCommit)
                return true;
            // snapshot the current bounding sphere of visible objects
            _mol_math_geometry__WEBPACK_IMPORTED_MODULE_23__[/* Sphere3D */ "g"].copy(oldBoundingSphereVisible, scene.boundingSphereVisible);
            if (!scene.commit(isSynchronous ? void 0 : sceneCommitTimeoutMs))
                return false;
            if (debugHelper.isEnabled)
                debugHelper.update();
            if (reprCount.value === 0 || shouldResetCamera()) {
                cameraResetRequested = true;
            }
            if (oldBoundingSphereVisible.radius === 0)
                nextCameraResetDuration = 0;
            camera.setState({ radiusMax: scene.boundingSphere.radius }, 0);
            reprCount.next(reprRenderObjects.size);
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                consoleStats();
            return true;
        }
        function consoleStats() {
            console.table(scene.renderables.map(function (r) { return ({
                drawCount: r.values.drawCount.ref.value,
                instanceCount: r.values.instanceCount.ref.value,
                materialId: r.materialId,
            }); }));
        }
        function add(repr) {
            registerAutoUpdate(repr);
            var oldRO = reprRenderObjects.get(repr);
            var newRO = new Set();
            repr.renderObjects.forEach(function (o) { return newRO.add(o); });
            if (oldRO) {
                if (!_mol_util_set__WEBPACK_IMPORTED_MODULE_15__[/* SetUtils */ "a"].areEqual(newRO, oldRO)) {
                    newRO.forEach(function (o) { if (!oldRO.has(o))
                        scene.add(o); });
                    oldRO.forEach(function (o) { if (!newRO.has(o))
                        scene.remove(o); });
                }
            }
            else {
                repr.renderObjects.forEach(function (o) { return scene.add(o); });
            }
            reprRenderObjects.set(repr, newRO);
            scene.update(repr.renderObjects, false);
            forceDrawAfterAllCommited = true;
            if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                consoleStats();
        }
        function remove(repr) {
            unregisterAutoUpdate(repr);
            var renderObjects = reprRenderObjects.get(repr);
            if (renderObjects) {
                renderObjects.forEach(function (o) { return scene.remove(o); });
                reprRenderObjects.delete(repr);
                scene.update(repr.renderObjects, false, true);
                forceDrawAfterAllCommited = true;
                if (_mol_util_debug__WEBPACK_IMPORTED_MODULE_24__[/* isDebugMode */ "a"])
                    consoleStats();
            }
        }
        function registerAutoUpdate(repr) {
            if (reprUpdatedSubscriptions.has(repr))
                return;
            reprUpdatedSubscriptions.set(repr, repr.updated.subscribe(function (_) {
                if (!repr.state.syncManually)
                    add(repr);
            }));
        }
        function unregisterAutoUpdate(repr) {
            var updatedSubscription = reprUpdatedSubscriptions.get(repr);
            if (updatedSubscription) {
                updatedSubscription.unsubscribe();
                reprUpdatedSubscriptions.delete(repr);
            }
        }
        function getProps() {
            var radius = scene.boundingSphere.radius > 0
                ? 100 - Math.round((camera.transition.target.radius / scene.boundingSphere.radius) * 100)
                : 0;
            return {
                camera: {
                    mode: camera.state.mode,
                    helper: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, drawPass.props.cameraHelper)
                },
                cameraFog: camera.state.fog > 0
                    ? { name: 'on', params: { intensity: camera.state.fog } }
                    : { name: 'off', params: {} },
                cameraClipping: { far: camera.state.clipFar, radius: radius },
                cameraResetDurationMs: p.cameraResetDurationMs,
                transparentBackground: p.transparentBackground,
                postprocessing: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, postprocessing.props),
                multiSample: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, multiSample.props),
                renderer: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, renderer.props),
                trackball: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, controls.props),
                debug: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, debugHelper.props),
                handle: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, handleHelper.props),
            };
        }
        handleResize();
        var contextRestoredSub = contextRestored.subscribe(function () {
            pickPass.pickDirty = true;
            draw(true);
        });
        return {
            webgl: webgl,
            add: add,
            remove: remove,
            commit: commit,
            update: function (repr, keepSphere) {
                if (repr) {
                    if (!reprRenderObjects.has(repr))
                        return;
                    scene.update(repr.renderObjects, !!keepSphere);
                }
                else {
                    scene.update(void 0, !!keepSphere);
                }
                forceDrawAfterAllCommited = true;
            },
            clear: function () {
                reprUpdatedSubscriptions.forEach(function (v) { return v.unsubscribe(); });
                reprUpdatedSubscriptions.clear();
                reprRenderObjects.clear();
                scene.clear();
                debugHelper.clear();
                requestDraw(true);
                reprCount.next(reprRenderObjects.size);
            },
            syncVisibility: function () {
                if (camera.state.radiusMax === 0) {
                    cameraResetRequested = true;
                    nextCameraResetDuration = 0;
                }
                if (scene.syncVisibility()) {
                    if (debugHelper.isEnabled)
                        debugHelper.update();
                }
                requestDraw(true);
            },
            // draw,
            requestDraw: requestDraw,
            animate: animate,
            identify: identify,
            mark: mark,
            getLoci: getLoci,
            handleResize: handleResize,
            requestCameraReset: function (options) {
                nextCameraResetDuration = options === null || options === void 0 ? void 0 : options.durationMs;
                nextCameraResetSnapshot = options === null || options === void 0 ? void 0 : options.snapshot;
                cameraResetRequested = true;
            },
            camera: camera,
            boundingSphere: scene.boundingSphere,
            getPixelData: function (variant) {
                switch (variant) {
                    case 'color': return webgl.getDrawingBufferPixelData();
                    case 'pickObject': return pickPass.objectPickTarget.getPixelData();
                    case 'pickInstance': return pickPass.instancePickTarget.getPixelData();
                    case 'pickGroup': return pickPass.groupPickTarget.getPixelData();
                    case 'depth': return Object(_mol_gl_compute_util__WEBPACK_IMPORTED_MODULE_19__[/* readTexture */ "c"])(webgl, drawPass.depthTexture);
                }
            },
            didDraw: didDraw,
            reprCount: reprCount,
            setProps: function (properties) {
                var _a;
                var props = typeof properties === 'function'
                    ? Object(immer__WEBPACK_IMPORTED_MODULE_26__[/* produce */ "b"])(getProps(), properties)
                    : properties;
                var cameraState = Object.create(null);
                if (props.camera && props.camera.mode !== undefined && props.camera.mode !== camera.state.mode) {
                    cameraState.mode = props.camera.mode;
                }
                if (props.cameraFog !== undefined) {
                    var newFog = props.cameraFog.name === 'on' ? props.cameraFog.params.intensity : 0;
                    if (newFog !== camera.state.fog)
                        cameraState.fog = newFog;
                }
                if (props.cameraClipping !== undefined) {
                    if (props.cameraClipping.far !== undefined && props.cameraClipping.far !== camera.state.clipFar) {
                        cameraState.clipFar = props.cameraClipping.far;
                    }
                    if (props.cameraClipping.radius !== undefined) {
                        var radius = (scene.boundingSphere.radius / 100) * (100 - props.cameraClipping.radius);
                        if (radius > 0 && radius !== cameraState.radius) {
                            // if radius = 0, NaNs happen
                            cameraState.radius = Math.max(radius, 0.01);
                        }
                    }
                }
                if (Object.keys(cameraState).length > 0)
                    camera.setState(cameraState);
                if ((_a = props.camera) === null || _a === void 0 ? void 0 : _a.helper)
                    drawPass.setProps({ cameraHelper: props.camera.helper });
                if (props.cameraResetDurationMs !== undefined)
                    p.cameraResetDurationMs = props.cameraResetDurationMs;
                if (props.transparentBackground !== undefined)
                    p.transparentBackground = props.transparentBackground;
                if (props.postprocessing)
                    postprocessing.setProps(props.postprocessing);
                if (props.multiSample)
                    multiSample.setProps(props.multiSample);
                if (props.renderer)
                    renderer.setProps(props.renderer);
                if (props.trackball)
                    controls.setProps(props.trackball);
                if (props.debug)
                    debugHelper.setProps(props.debug);
                if (props.handle)
                    handleHelper.setProps(props.handle);
                requestDraw(true);
            },
            getImagePass: function (props) {
                if (props === void 0) { props = {}; }
                return new _passes_image__WEBPACK_IMPORTED_MODULE_22__[/* ImagePass */ "a"](webgl, renderer, scene, camera, debugHelper, handleHelper, props);
            },
            get props() {
                var radius = scene.boundingSphere.radius > 0
                    ? 100 - Math.round((camera.transition.target.radius / scene.boundingSphere.radius) * 100)
                    : 0;
                return {
                    camera: {
                        mode: camera.state.mode,
                        helper: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, drawPass.props.cameraHelper)
                    },
                    cameraFog: camera.state.fog > 0
                        ? { name: 'on', params: { intensity: camera.state.fog } }
                        : { name: 'off', params: {} },
                    cameraClipping: { far: camera.state.clipFar, radius: radius },
                    cameraResetDurationMs: p.cameraResetDurationMs,
                    transparentBackground: p.transparentBackground,
                    postprocessing: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, postprocessing.props),
                    multiSample: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, multiSample.props),
                    renderer: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, renderer.props),
                    trackball: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, controls.props),
                    debug: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, debugHelper.props),
                    handle: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, handleHelper.props),
                };
            },
            get input() {
                return input;
            },
            get stats() {
                return renderer.stats;
            },
            get interaction() {
                return interactionHelper.events;
            },
            dispose: function () {
                contextRestoredSub.unsubscribe();
                scene.clear();
                debugHelper.clear();
                input.dispose();
                controls.dispose();
                renderer.dispose();
                interactionHelper.dispose();
            }
        };
        function handleResize() {
            width = gl.drawingBufferWidth;
            height = gl.drawingBufferHeight;
            renderer.setViewport(0, 0, width, height);
            _camera_util__WEBPACK_IMPORTED_MODULE_7__[/* Viewport */ "a"].set(camera.viewport, 0, 0, width, height);
            _camera_util__WEBPACK_IMPORTED_MODULE_7__[/* Viewport */ "a"].set(controls.viewport, 0, 0, width, height);
            drawPass.setSize(width, height);
            pickPass.setSize(width, height);
            postprocessing.setSize(width, height);
            multiSample.setSize(width, height);
            requestDraw(true);
        }
    }
    Canvas3D.create = create;
})(Canvas3D || (Canvas3D = {}));
//# sourceMappingURL=canvas3d.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(384).setImmediate))

/***/ }),
/* 159 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ computeIntraUnitBonds; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ computeInterUnitBonds; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ bonds_Bond; });

// UNUSED EXPORTS: IntraUnitBonds, InterUnitBonds

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js + 5 modules
var structure_structure = __webpack_require__(27);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/centroid-helper.js
var centroid_helper = __webpack_require__(195);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph.js + 1 modules
var graph = __webpack_require__(171);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit.js + 2 modules
var structure_unit = __webpack_require__(37);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph/inter-unit-graph.js
var inter_unit_graph = __webpack_require__(244);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/data.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var data_IntraUnitBonds;
(function (IntraUnitBonds) {
    IntraUnitBonds.Empty = graph["a" /* IntAdjacencyGraph */].create([], [], [], 0, { flags: [], order: [] });
})(data_IntraUnitBonds || (data_IntraUnitBonds = {}));
var data_InterUnitBonds = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(InterUnitBonds, _super);
    function InterUnitBonds() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    /** Get inter-unit bond given a bond-location */
    InterUnitBonds.prototype.getBondFromLocation = function (l) {
        return structure_unit["a" /* default */].isAtomic(l.aUnit) && structure_unit["a" /* default */].isAtomic(l.bUnit) ? this.getEdge(l.aIndex, l.aUnit, l.bIndex, l.bUnit) : undefined;
    };
    /** Get inter-unit bond index given a bond-location */
    InterUnitBonds.prototype.getBondIndexFromLocation = function (l) {
        return structure_unit["a" /* default */].isAtomic(l.aUnit) && structure_unit["a" /* default */].isAtomic(l.bUnit) ? this.getEdgeIndex(l.aIndex, l.aUnit, l.bIndex, l.bUnit) : -1;
    };
    return InterUnitBonds;
}(inter_unit_graph["a" /* InterUnitGraph */]));
(function (InterUnitBonds) {
    var UnitPairBonds = /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(UnitPairBonds, _super);
        function UnitPairBonds() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        return UnitPairBonds;
    }(inter_unit_graph["a" /* InterUnitGraph */].UnitPairEdges));
    InterUnitBonds.UnitPairBonds = UnitPairBonds;
})(data_InterUnitBonds || (data_InterUnitBonds = {}));

//# sourceMappingURL=data.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/common.js
var common = __webpack_require__(109);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic/bonds.js
var atomic_bonds = __webpack_require__(306);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/bonds/index-pair.js
var index_pair = __webpack_require__(173);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/bonds/comp.js
var comp = __webpack_require__(325);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/bonds/struct_conn.js
var struct_conn = __webpack_require__(267);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/intra-compute.js
/**
 * Copyright (c) 2017-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









function getGraph(atomA, atomB, _order, _flags, atomCount) {
    var builder = new graph["a" /* IntAdjacencyGraph */].EdgeBuilder(atomCount, atomA, atomB);
    var flags = new Uint16Array(builder.slotCount);
    var order = new Int8Array(builder.slotCount);
    for (var i = 0, _i = builder.edgeCount; i < _i; i++) {
        builder.addNextEdge();
        builder.assignProperty(flags, _flags[i]);
        builder.assignProperty(order, _order[i]);
    }
    return builder.createGraph({ flags: flags, order: order });
}
var __structConnAdded = new Set();
function _computeBonds(unit, props) {
    var MAX_RADIUS = 4;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var atomCount = unit.elements.length;
    var atoms = unit.elements, residueIndex = unit.residueIndex, chainIndex = unit.chainIndex;
    var _b = unit.model.atomicHierarchy.atoms, type_symbol = _b.type_symbol, label_atom_id = _b.label_atom_id, label_alt_id = _b.label_alt_id, label_comp_id = _b.label_comp_id;
    var label_seq_id = unit.model.atomicHierarchy.residues.label_seq_id;
    var index = unit.model.atomicHierarchy.index;
    var byEntityKey = unit.model.sequence.byEntityKey;
    var query3d = unit.lookup3d;
    var structConn = struct_conn["a" /* StructConn */].Provider.get(unit.model);
    var component = comp["a" /* ComponentBond */].Provider.get(unit.model);
    var indexPairs = index_pair["a" /* IndexPairBonds */].Provider.get(unit.model);
    var atomA = [];
    var atomB = [];
    var flags = [];
    var order = [];
    var lastResidue = -1;
    var componentMap = void 0;
    var structConnAdded = __structConnAdded;
    for (var _aI = 0; _aI < atomCount; _aI++) {
        var aI = atoms[_aI];
        if (!props.forceCompute && indexPairs) {
            var edgeProps = indexPairs.edgeProps;
            for (var i = indexPairs.offset[aI], il = indexPairs.offset[aI + 1]; i < il; ++i) {
                var _bI = mol_data_int["SortedArray"].indexOf(unit.elements, indexPairs.b[i]);
                if (_bI < 0)
                    continue;
                if (edgeProps.symmetryA[i] !== edgeProps.symmetryB[i])
                    continue;
                if (type_symbol.value(aI) === 'H' && type_symbol.value(indexPairs.b[i]) === 'H')
                    continue;
                atomA[atomA.length] = _aI;
                atomB[atomB.length] = _bI;
                order[order.length] = edgeProps.order[i];
                flags[flags.length] = 1 /* Covalent */;
            }
            continue; // assume `indexPairs` supplies all bonds
        }
        var structConnEntries = props.forceCompute ? void 0 : structConn && structConn.byAtomIndex.get(aI);
        var hasStructConn = false;
        if (structConnEntries) {
            for (var _c = 0, structConnEntries_1 = structConnEntries; _c < structConnEntries_1.length; _c++) {
                var se = structConnEntries_1[_c];
                var partnerA = se.partnerA, partnerB = se.partnerB;
                // symmetry must be the same for intra-unit bonds
                if (partnerA.symmetry !== partnerB.symmetry)
                    continue;
                var p = partnerA.atomIndex === aI ? partnerB : partnerA;
                var _bI = mol_data_int["SortedArray"].indexOf(unit.elements, p.atomIndex);
                if (_bI < 0)
                    continue;
                atomA[atomA.length] = _aI;
                atomB[atomB.length] = _bI;
                flags[flags.length] = se.flags;
                order[order.length] = se.order;
                if (!hasStructConn)
                    structConnAdded.clear();
                hasStructConn = true;
                structConnAdded.add(_bI);
            }
        }
        var raI = residueIndex[aI];
        var compId = label_comp_id.value(aI);
        if (!props.forceCompute && raI !== lastResidue) {
            if (!!component && component.entries.has(compId)) {
                var entitySeq = byEntityKey[index.getEntityFromChain(chainIndex[aI])];
                if (entitySeq && entitySeq.sequence.microHet.has(label_seq_id.value(raI))) {
                    // compute for sequence positions with micro-heterogeneity
                    componentMap = void 0;
                }
                else {
                    componentMap = component.entries.get(compId).map;
                }
            }
            else {
                componentMap = void 0;
            }
        }
        lastResidue = raI;
        var aeI = Object(common["c" /* getElementIdx */])(type_symbol.value(aI));
        var atomIdA = label_atom_id.value(aI);
        var componentPairs = componentMap ? componentMap.get(atomIdA) : void 0;
        var _d = query3d.find(x[aI], y[aI], z[aI], MAX_RADIUS), indices = _d.indices, count = _d.count, squaredDistances = _d.squaredDistances;
        var isHa = Object(common["f" /* isHydrogen */])(aeI);
        var thresholdA = Object(common["e" /* getElementThreshold */])(aeI);
        var altA = label_alt_id.value(aI);
        var metalA = common["b" /* MetalsSet */].has(aeI);
        for (var ni = 0; ni < count; ni++) {
            var _bI = indices[ni];
            if (hasStructConn && structConnAdded.has(_bI))
                continue;
            var bI = atoms[_bI];
            if (bI <= aI)
                continue;
            var altB = label_alt_id.value(bI);
            if (altA && altB && altA !== altB)
                continue;
            var beI = Object(common["c" /* getElementIdx */])(type_symbol.value(bI));
            var isHb = Object(common["f" /* isHydrogen */])(beI);
            if (isHa && isHb)
                continue;
            var isMetal = (metalA || common["b" /* MetalsSet */].has(beI)) && !(isHa || isHb);
            var rbI = residueIndex[bI];
            // handle "component dictionary" bonds.
            if (raI === rbI && componentPairs) {
                var e = componentPairs.get(label_atom_id.value(bI));
                if (e) {
                    atomA[atomA.length] = _aI;
                    atomB[atomB.length] = _bI;
                    order[order.length] = e.order;
                    var flag = e.flags;
                    if (isMetal) {
                        if (flag | 1 /* Covalent */)
                            flag ^= 1 /* Covalent */;
                        flag |= 2 /* MetallicCoordination */;
                    }
                    flags[flags.length] = flag;
                }
                continue;
            }
            var dist = Math.sqrt(squaredDistances[ni]);
            if (dist === 0)
                continue;
            var thresholdAB = Object(common["d" /* getElementPairThreshold */])(aeI, beI);
            var pairingThreshold = thresholdAB > 0
                ? thresholdAB
                : beI < 0
                    ? thresholdA
                    : (thresholdA + Object(common["e" /* getElementThreshold */])(beI)) / 2; // not sure if avg or min but max is too big
            if (dist <= pairingThreshold) {
                atomA[atomA.length] = _aI;
                atomB[atomB.length] = _bI;
                order[order.length] = Object(atomic_bonds["b" /* getIntraBondOrderFromTable */])(compId, atomIdA, label_atom_id.value(bI));
                flags[flags.length] = (isMetal ? 2 /* MetallicCoordination */ : 1 /* Covalent */) | 32 /* Computed */;
            }
        }
    }
    return getGraph(atomA, atomB, order, flags, atomCount);
}
function computeIntraUnitBonds(unit, props) {
    var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, common["a" /* DefaultBondComputationProps */]), props);
    if (p.noCompute) {
        // TODO add function that only adds bonds defined in structConn of chemCompBond
        //      and avoid using unit.lookup
        return data_IntraUnitBonds.Empty;
    }
    return _computeBonds(unit, p);
}

//# sourceMappingURL=intra-compute.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/structure.js + 6 modules
var structure_structure_structure = __webpack_require__(112);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/inter-compute.js
/**
 * Copyright (c) 2017-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var inter_compute_MAX_RADIUS = 4;
var tmpDistVecA = Object(linear_algebra["Vec3"])();
var tmpDistVecB = Object(linear_algebra["Vec3"])();
function getDistance(unitA, indexA, unitB, indexB) {
    unitA.conformation.position(indexA, tmpDistVecA);
    unitB.conformation.position(indexB, tmpDistVecB);
    return linear_algebra["Vec3"].distance(tmpDistVecA, tmpDistVecB);
}
var _imageTransform = linear_algebra["Mat4"].zero();
function findPairBonds(unitA, unitB, props, builder) {
    var atomsA = unitA.elements, residueIndexA = unitA.residueIndex;
    var _a = unitA.model.atomicConformation, xA = _a.x, yA = _a.y, zA = _a.z;
    var atomsB = unitB.elements, residueIndexB = unitB.residueIndex;
    var atomCount = unitA.elements.length;
    var _b = unitA.model.atomicHierarchy.atoms, type_symbolA = _b.type_symbol, label_alt_idA = _b.label_alt_id, label_atom_idA = _b.label_atom_id, label_comp_idA = _b.label_comp_id;
    var _c = unitB.model.atomicHierarchy.atoms, type_symbolB = _c.type_symbol, label_alt_idB = _c.label_alt_id, label_atom_idB = _c.label_atom_id, label_comp_idB = _c.label_comp_id;
    var auth_seq_idA = unitA.model.atomicHierarchy.residues.auth_seq_id;
    var auth_seq_idB = unitB.model.atomicHierarchy.residues.auth_seq_id;
    var occupancyA = unitA.model.atomicConformation.occupancy;
    var occupancyB = unitB.model.atomicConformation.occupancy;
    var hasOccupancy = occupancyA.isDefined && occupancyB.isDefined;
    var lookup3d = unitB.lookup3d;
    var structConn = unitA.model === unitB.model && struct_conn["a" /* StructConn */].Provider.get(unitA.model);
    var indexPairs = unitA.model === unitB.model && index_pair["a" /* IndexPairBonds */].Provider.get(unitA.model);
    // the lookup queries need to happen in the "unitB space".
    // that means imageA = inverseOperB(operA(aI))
    var imageTransform = linear_algebra["Mat4"].mul(_imageTransform, unitB.conformation.operator.inverse, unitA.conformation.operator.matrix);
    var isNotIdentity = !linear_algebra["Mat4"].isIdentity(imageTransform);
    var imageA = linear_algebra["Vec3"].zero();
    var _d = lookup3d.boundary.sphere, bCenter = _d.center, bRadius = _d.radius;
    var testDistanceSq = (bRadius + inter_compute_MAX_RADIUS) * (bRadius + inter_compute_MAX_RADIUS);
    builder.startUnitPair(unitA, unitB);
    var symmUnitA = unitA.conformation.operator.name;
    var symmUnitB = unitB.conformation.operator.name;
    for (var _aI = 0; _aI < atomCount; _aI++) {
        var aI = atomsA[_aI];
        linear_algebra["Vec3"].set(imageA, xA[aI], yA[aI], zA[aI]);
        if (isNotIdentity)
            linear_algebra["Vec3"].transformMat4(imageA, imageA, imageTransform);
        if (linear_algebra["Vec3"].squaredDistance(imageA, bCenter) > testDistanceSq)
            continue;
        if (!props.forceCompute && indexPairs) {
            var _e = indexPairs.edgeProps, order = _e.order, symmetryA = _e.symmetryA, symmetryB = _e.symmetryB;
            for (var i = indexPairs.offset[aI], il = indexPairs.offset[aI + 1]; i < il; ++i) {
                var _bI = mol_data_int["SortedArray"].indexOf(unitA.elements, indexPairs.b[i]);
                if (_bI < 0)
                    continue;
                if (symmetryA[i] === symmetryB[i])
                    continue;
                if (type_symbolA.value(aI) === 'H' && type_symbolB.value(indexPairs.b[i]) === 'H')
                    continue;
                if (symmUnitA === symmetryA[i] && symmUnitB === symmetryB[i]) {
                    builder.add(_aI, _bI, { order: order[i], flag: 1 /* Covalent */ });
                }
            }
            continue; // assume `indexPairs` supplies all bonds
        }
        var structConnEntries = props.forceCompute ? void 0 : structConn && structConn.byAtomIndex.get(aI);
        if (structConnEntries && structConnEntries.length) {
            var added = false;
            for (var _i = 0, structConnEntries_1 = structConnEntries; _i < structConnEntries_1.length; _i++) {
                var se = structConnEntries_1[_i];
                var partnerA = se.partnerA, partnerB = se.partnerB;
                var p = partnerA.atomIndex === aI ? partnerB : partnerA;
                var _bI = mol_data_int["SortedArray"].indexOf(unitB.elements, p.atomIndex);
                if (_bI < 0)
                    continue;
                // check if the bond is within MAX_RADIUS for this pair of units
                if (getDistance(unitA, aI, unitB, p.atomIndex) > inter_compute_MAX_RADIUS)
                    continue;
                builder.add(_aI, _bI, { order: se.order, flag: se.flags });
                added = true;
            }
            // assume, for an atom, that if any inter unit bond is given
            // all are given and thus we don't need to compute any other
            if (added)
                continue;
        }
        var occA = occupancyA.value(aI);
        var _f = lookup3d.find(imageA[0], imageA[1], imageA[2], inter_compute_MAX_RADIUS), indices = _f.indices, count = _f.count, squaredDistances = _f.squaredDistances;
        if (count === 0)
            continue;
        var aeI = Object(common["c" /* getElementIdx */])(type_symbolA.value(aI));
        var isHa = Object(common["f" /* isHydrogen */])(aeI);
        var thresholdA = Object(common["e" /* getElementThreshold */])(aeI);
        var altA = label_alt_idA.value(aI);
        var metalA = common["b" /* MetalsSet */].has(aeI);
        var atomIdA = label_atom_idA.value(aI);
        var compIdA = label_comp_idA.value(residueIndexA[aI]);
        for (var ni = 0; ni < count; ni++) {
            var _bI = indices[ni];
            var bI = atomsB[_bI];
            var altB = label_alt_idB.value(bI);
            if (altA && altB && altA !== altB)
                continue;
            // Do not include bonds between images of the same residue with partial occupancy.
            // TODO: is this condition good enough?
            // - It works for cases like 3WQJ (label_asym_id: I) which have partial occupancy.
            // - Does NOT work for cases like 1RB8 (DC 7) with full occupancy.
            if (hasOccupancy && occupancyB.value(bI) < 1 && occA < 1) {
                if (auth_seq_idA.value(aI) === auth_seq_idB.value(bI)) {
                    continue;
                }
            }
            var beI = Object(common["c" /* getElementIdx */])(type_symbolB.value(bI));
            var isHb = Object(common["f" /* isHydrogen */])(beI);
            if (isHa && isHb)
                continue;
            var isMetal = (metalA || common["b" /* MetalsSet */].has(beI)) && !(isHa || isHb);
            var dist = Math.sqrt(squaredDistances[ni]);
            if (dist === 0)
                continue;
            var thresholdAB = Object(common["d" /* getElementPairThreshold */])(aeI, beI);
            var pairingThreshold = thresholdAB > 0
                ? thresholdAB
                : beI < 0
                    ? thresholdA
                    : (thresholdA + Object(common["e" /* getElementThreshold */])(beI)) / 2; // not sure if avg or min but max is too big
            if (dist <= pairingThreshold) {
                var atomIdB = label_atom_idB.value(bI);
                var compIdB = label_comp_idB.value(residueIndexB[bI]);
                builder.add(_aI, _bI, {
                    order: Object(atomic_bonds["a" /* getInterBondOrderFromTable */])(compIdA, compIdB, atomIdA, atomIdB),
                    flag: (isMetal ? 2 /* MetallicCoordination */ : 1 /* Covalent */) | 32 /* Computed */
                });
            }
        }
    }
    builder.finishUnitPair();
}
function findBonds(structure, props) {
    var builder = new inter_unit_graph["a" /* InterUnitGraph */].Builder();
    if (props.noCompute) {
        // TODO add function that only adds bonds defined in structConn and avoids using
        //      structure.lookup and unit.lookup (expensive for large structure and not
        //      needed for archival files or files with an MD topology)
        return new data_InterUnitBonds(builder.getMap());
    }
    structure_structure_structure["a" /* default */].eachUnitPair(structure, function (unitA, unitB) {
        findPairBonds(unitA, unitB, props, builder);
    }, {
        maxRadius: inter_compute_MAX_RADIUS,
        validUnit: function (unit) { return structure_unit["a" /* default */].isAtomic(unit); },
        validUnitPair: function (unitA, unitB) { return props.validUnitPair(structure, unitA, unitB); }
    });
    return new data_InterUnitBonds(builder.getMap());
}
function computeInterUnitBonds(structure, props) {
    return findBonds(structure, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, common["a" /* DefaultBondComputationProps */]), { validUnitPair: (props && props.validUnitPair) || (function (s, a, b) {
            var mtA = a.model.atomicHierarchy.derived.residue.moleculeType;
            var mtB = b.model.atomicHierarchy.derived.residue.moleculeType;
            var notWater = ((!structure_unit["a" /* default */].isAtomic(a) || mtA[a.residueIndex[a.elements[0]]] !== 2 /* Water */) &&
                (!structure_unit["a" /* default */].isAtomic(b) || mtB[b.residueIndex[b.elements[0]]] !== 2 /* Water */));
            return structure_structure_structure["a" /* default */].validUnitPair(s, a, b) && notWater;
        }) }));
}

//# sourceMappingURL=inter-compute.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var bonds_Bond;
(function (Bond) {
    function Location(aStructure, aUnit, aIndex, bStructure, bUnit, bIndex) {
        return {
            kind: 'bond-location',
            aStructure: aStructure,
            aUnit: aUnit,
            aIndex: aIndex,
            bStructure: bStructure,
            bUnit: bUnit,
            bIndex: bIndex
        };
    }
    Bond.Location = Location;
    function isLocation(x) {
        return !!x && x.kind === 'bond-location';
    }
    Bond.isLocation = isLocation;
    function areLocationsEqual(locA, locB) {
        return (locA.aStructure.label === locB.aStructure.label && locA.bStructure.label === locB.bStructure.label &&
            locA.aIndex === locB.aIndex && locA.bIndex === locB.bIndex &&
            locA.aUnit.id === locB.aUnit.id && locA.bUnit.id === locB.bUnit.id);
    }
    Bond.areLocationsEqual = areLocationsEqual;
    function Loci(structure, bonds) {
        return { kind: 'bond-loci', structure: structure, bonds: bonds };
    }
    Bond.Loci = Loci;
    function isLoci(x) {
        return !!x && x.kind === 'bond-loci';
    }
    Bond.isLoci = isLoci;
    function areLociEqual(a, b) {
        if (a.structure !== b.structure)
            return false;
        if (a.bonds.length !== b.bonds.length)
            return false;
        for (var i = 0, il = a.bonds.length; i < il; ++i) {
            if (!areLocationsEqual(a.bonds[i], b.bonds[i]))
                return false;
        }
        return true;
    }
    Bond.areLociEqual = areLociEqual;
    function isLociEmpty(loci) {
        return loci.bonds.length === 0 ? true : false;
    }
    Bond.isLociEmpty = isLociEmpty;
    function remapLoci(loci, structure) {
        if (structure === loci.structure)
            return loci;
        var bonds = [];
        loci.bonds.forEach(function (l) {
            var unitA = structure.unitMap.get(l.aUnit.id);
            if (!unitA)
                return;
            var unitB = structure.unitMap.get(l.bUnit.id);
            if (!unitB)
                return;
            var elementA = l.aUnit.elements[l.aIndex];
            var indexA = mol_data_int["SortedArray"].indexOf(unitA.elements, elementA);
            if (indexA === -1)
                return;
            var elementB = l.bUnit.elements[l.bIndex];
            var indexB = mol_data_int["SortedArray"].indexOf(unitB.elements, elementB);
            if (indexB === -1)
                return;
            bonds.push(Location(loci.structure, unitA, indexA, loci.structure, unitB, indexB));
        });
        return Loci(structure, bonds);
    }
    Bond.remapLoci = remapLoci;
    function toStructureElementLoci(loci) {
        var elements = [];
        var map = new Map();
        for (var _i = 0, _a = loci.bonds; _i < _a.length; _i++) {
            var lociBond = _a[_i];
            var aIndex = lociBond.aIndex, aUnit = lociBond.aUnit, bIndex = lociBond.bIndex, bUnit = lociBond.bUnit;
            if (aUnit === bUnit) {
                if (map.has(aUnit.id))
                    map.get(aUnit.id).push(aIndex, bIndex);
                else
                    map.set(aUnit.id, [aIndex, bIndex]);
            }
            else {
                if (map.has(aUnit.id))
                    map.get(aUnit.id).push(aIndex);
                else
                    map.set(aUnit.id, [aIndex]);
                if (map.has(bUnit.id))
                    map.get(bUnit.id).push(bIndex);
                else
                    map.set(bUnit.id, [bIndex]);
            }
        }
        map.forEach(function (indices, id) {
            elements.push({
                unit: loci.structure.unitMap.get(id),
                indices: mol_data_int["SortedArray"].deduplicate(mol_data_int["SortedArray"].ofUnsortedArray(indices))
            });
        });
        return structure_structure["d" /* StructureElement */].Loci(loci.structure, elements);
    }
    Bond.toStructureElementLoci = toStructureElementLoci;
    function getType(structure, location) {
        if (location.aUnit === location.bUnit) {
            var bonds = location.aUnit.bonds;
            var idx = bonds.getEdgeIndex(location.aIndex, location.bIndex);
            if (idx < 0)
                return types["BondType"].create(0 /* None */);
            return types["BondType"].create(bonds.edgeProps.flags[idx]);
        }
        else {
            var bond = structure.interUnitBonds.getBondFromLocation(location);
            if (bond)
                return types["BondType"].create(bond.props.flag);
            return types["BondType"].create(0 /* None */);
        }
    }
    Bond.getType = getType;
    function getOrder(structure, location) {
        if (location.aUnit === location.bUnit) {
            var bonds = location.aUnit.bonds;
            var idx = bonds.getEdgeIndex(location.aIndex, location.bIndex);
            if (idx < 0)
                return 0;
            return bonds.edgeProps.order[idx];
        }
        else {
            var bond = structure.interUnitBonds.getBondFromLocation(location);
            if (bond)
                return bond.props.order;
            return 0;
        }
    }
    Bond.getOrder = getOrder;
    function getIntraUnitBondCount(structure) {
        var count = 0;
        for (var i = 0, il = structure.units.length; i < il; ++i) {
            var u = structure.units[i];
            if (structure_structure["g" /* Unit */].isAtomic(u))
                count += u.bonds.edgeCount / 2; // only count one direction
        }
        return count;
    }
    Bond.getIntraUnitBondCount = getIntraUnitBondCount;
    var ElementBondIterator = /** @class */ (function () {
        function ElementBondIterator() {
            this.current = {};
            this.hasNext = false;
        }
        ElementBondIterator.prototype.move = function () {
            this.advance();
            return this.current;
        };
        ElementBondIterator.prototype.setElement = function (structure, unit, index) {
            this.structure = structure;
            this.unit = unit;
            this.index = index;
            this.interBondIndices = structure.interUnitBonds.getEdgeIndices(index, unit);
            this.interBondCount = this.interBondIndices.length;
            this.interBondIndex = 0;
            this.intraBondEnd = unit.bonds.offset[index + 1];
            this.intraBondIndex = unit.bonds.offset[index];
            this.hasNext = this.interBondIndex < this.interBondCount || this.intraBondIndex < this.intraBondEnd;
        };
        ElementBondIterator.prototype.advance = function () {
            if (this.intraBondIndex < this.intraBondEnd) {
                this.current.otherUnit = this.unit;
                this.current.otherIndex = this.unit.bonds.b[this.intraBondIndex];
                this.current.type = this.unit.bonds.edgeProps.flags[this.intraBondIndex];
                this.current.order = this.unit.bonds.edgeProps.order[this.intraBondIndex];
                this.intraBondIndex += 1;
            }
            else if (this.interBondIndex < this.interBondCount) {
                var b = this.structure.interUnitBonds.edges[this.interBondIndex];
                this.current.otherUnit = b.unitA !== this.unit ? b.unitA : b.unitB;
                this.current.otherIndex = b.indexA !== this.index ? b.indexA : b.indexB;
                this.current.type = b.props.flag;
                this.current.order = b.props.order;
                this.interBondIndex += 1;
            }
            else {
                this.hasNext = false;
                return;
            }
            this.hasNext = this.interBondIndex < this.interBondCount || this.intraBondIndex < this.intraBondEnd;
        };
        return ElementBondIterator;
    }());
    Bond.ElementBondIterator = ElementBondIterator;
    function getBoundingSphere(loci, boundingSphere) {
        return centroid_helper["a" /* CentroidHelper */].fromPairProvider(loci.bonds.length, function (i, pA, pB) {
            var _a = loci.bonds[i], aUnit = _a.aUnit, aIndex = _a.aIndex, bUnit = _a.bUnit, bIndex = _a.bIndex;
            aUnit.conformation.position(aUnit.elements[aIndex], pA);
            bUnit.conformation.position(bUnit.elements[bIndex], pB);
        }, boundingSphere);
    }
    Bond.getBoundingSphere = getBoundingSphere;
})(bonds_Bond || (bonds_Bond = {}));

//# sourceMappingURL=bonds.js.map

/***/ }),
/* 160 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ behavior_VolumeStreaming; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/volume.js
var mol_model_volume = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/isosurface.js
var isosurface = __webpack_require__(241);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/behavior.js
var behavior = __webpack_require__(68);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/lru-cache.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from LiteMol.
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var lru_cache_LRUCache;
(function (LRUCache) {
    function entry(key, data) {
        return { key: key, data: data };
    }
    function create(capacity) {
        return {
            entries: Object(generic["b" /* LinkedList */])(),
            capacity: Math.max(1, capacity)
        };
    }
    LRUCache.create = create;
    function get(cache, key) {
        for (var e = cache.entries.first; e; e = e.next) {
            if (e.value.key === key) {
                cache.entries.remove(e);
                cache.entries.addLast(e.value);
                return e.value.data;
            }
        }
        return void 0;
    }
    LRUCache.get = get;
    function set(cache, key, data) {
        var removed = undefined;
        if (cache.entries.count >= cache.capacity) {
            var first = cache.entries.first;
            removed = first.value.data;
            cache.entries.remove(first);
        }
        cache.entries.addLast(entry(key, data));
        return removed;
    }
    LRUCache.set = set;
})(lru_cache_LRUCache || (lru_cache_LRUCache = {}));
//# sourceMappingURL=lru-cache.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/url.js
var mol_util_url = __webpack_require__(262);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js + 8 modules
var cif = __webpack_require__(31);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/volume/density-server.js
var density_server = __webpack_require__(363);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/assets.js
var assets = __webpack_require__(114);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/behavior.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















var behavior_VolumeStreaming = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(VolumeStreaming, _super);
    function VolumeStreaming() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return VolumeStreaming;
}(objects["a" /* PluginStateObject */].CreateBehavior({ name: 'Volume Streaming' })));

(function (VolumeStreaming) {
    VolumeStreaming.RootTag = 'volume-streaming-info';
    function channelParam(label, color, defaultValue, stats, defaults) {
        if (defaults === void 0) { defaults = {}; }
        return param_definition["ParamDefinition"].Group({
            isoValue: Object(isosurface["c" /* createIsoValueParam */])(typeof defaults.isoValue !== 'undefined' ? defaults.isoValue : defaultValue, stats),
            color: param_definition["ParamDefinition"].Color(typeof defaults.color !== 'undefined' ? defaults.color : color),
            wireframe: param_definition["ParamDefinition"].Boolean(typeof defaults.wireframe !== 'undefined' ? defaults.wireframe : false),
            opacity: param_definition["ParamDefinition"].Numeric(typeof defaults.opacity !== 'undefined' ? defaults.opacity : 0.3, { min: 0, max: 1, step: 0.01 })
        }, { label: label, isExpanded: true });
    }
    var fakeSampling = {
        byteOffset: 0,
        rate: 1,
        sampleCount: [1, 1, 1],
        valuesInfo: [{ mean: 0, min: -1, max: 1, sigma: 0.1 }, { mean: 0, min: -1, max: 1, sigma: 0.1 }]
    };
    function createParams(options) {
        if (options === void 0) { options = {}; }
        var data = options.data, defaultView = options.defaultView, channelParams = options.channelParams;
        var map = new Map();
        if (data)
            data.entries.forEach(function (d) { return map.set(d.dataId, d); });
        var names = data ? data.entries.map(function (d) { return [d.dataId, d.dataId]; }) : [];
        var defaultKey = data ? data.entries[0].dataId : '';
        return {
            entry: param_definition["ParamDefinition"].Mapped(defaultKey, names, function (name) { return param_definition["ParamDefinition"].Group(createEntryParams({ entryData: map.get(name), defaultView: defaultView, structure: data && data.structure, channelParams: channelParams })); }),
        };
    }
    VolumeStreaming.createParams = createParams;
    function createEntryParams(options) {
        var entryData = options.entryData, defaultView = options.defaultView, structure = options.structure, _a = options.channelParams, channelParams = _a === void 0 ? {} : _a;
        // fake the info
        var info = entryData || { kind: 'em', header: { sampling: [fakeSampling], availablePrecisions: [{ precision: 0, maxVoxels: 0 }] }, emDefaultContourLevel: mol_model_volume["b" /* Volume */].IsoValue.relative(0) };
        var box = (structure && structure.boundary.box) || geometry["b" /* Box3D */].empty();
        return {
            view: param_definition["ParamDefinition"].MappedStatic(defaultView || (info.kind === 'em' ? 'cell' : 'selection-box'), {
                'off': param_definition["ParamDefinition"].Group({}),
                'box': param_definition["ParamDefinition"].Group({
                    bottomLeft: param_definition["ParamDefinition"].Vec3(box.min),
                    topRight: param_definition["ParamDefinition"].Vec3(box.max),
                }, { description: 'Static box defined by cartesian coords.', isFlat: true }),
                'selection-box': param_definition["ParamDefinition"].Group({
                    radius: param_definition["ParamDefinition"].Numeric(5, { min: 0, max: 50, step: 0.5 }, { description: 'Radius in \u212B within which the volume is shown.' }),
                    bottomLeft: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(0, 0, 0), {}, { isHidden: true }),
                    topRight: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(0, 0, 0), {}, { isHidden: true }),
                }, { description: 'Box around focused element.', isFlat: true }),
                'cell': param_definition["ParamDefinition"].Group({}),
            }, { options: VolumeStreaming.ViewTypeOptions, description: 'Controls what of the volume is displayed. "Off" hides the volume alltogether. "Bounded box" shows the volume inside the given box. "Around Interaction" shows the volume around the focused element/atom. "Whole Structure" shows the volume for the whole structure.' }),
            detailLevel: param_definition["ParamDefinition"].Select(Math.min(3, info.header.availablePrecisions.length - 1), info.header.availablePrecisions.map(function (p, i) { return [i, i + 1 + " [ " + (Math.pow(p.maxVoxels, 1 / 3) | 0) + "^3 cells ]"]; }), { description: 'Determines the maximum number of voxels. Depending on the size of the volume options are in the range from 0 (0.52M voxels) to 6 (25.17M voxels).' }),
            channels: info.kind === 'em'
                ? param_definition["ParamDefinition"].Group({
                    'em': channelParam('EM', Object(mol_util_color["Color"])(0x638F8F), info.emDefaultContourLevel || mol_model_volume["b" /* Volume */].IsoValue.relative(1), info.header.sampling[0].valuesInfo[0], channelParams['em'])
                }, { isFlat: true })
                : param_definition["ParamDefinition"].Group({
                    '2fo-fc': channelParam('2Fo-Fc', Object(mol_util_color["Color"])(0x3362B2), mol_model_volume["b" /* Volume */].IsoValue.relative(1.5), info.header.sampling[0].valuesInfo[0], channelParams['2fo-fc']),
                    'fo-fc(+ve)': channelParam('Fo-Fc(+ve)', Object(mol_util_color["Color"])(0x33BB33), mol_model_volume["b" /* Volume */].IsoValue.relative(3), info.header.sampling[0].valuesInfo[1], channelParams['fo-fc(+ve)']),
                    'fo-fc(-ve)': channelParam('Fo-Fc(-ve)', Object(mol_util_color["Color"])(0xBB3333), mol_model_volume["b" /* Volume */].IsoValue.relative(-3), info.header.sampling[0].valuesInfo[1], channelParams['fo-fc(-ve)']),
                }, { isFlat: true }),
        };
    }
    VolumeStreaming.createEntryParams = createEntryParams;
    VolumeStreaming.ViewTypeOptions = [['off', 'Off'], ['box', 'Bounded Box'], ['selection-box', 'Around Focus'], ['cell', 'Whole Structure']];
    VolumeStreaming.ChannelTypeOptions = [['em', 'em'], ['2fo-fc', '2fo-fc'], ['fo-fc(+ve)', 'fo-fc(+ve)'], ['fo-fc(-ve)', 'fo-fc(-ve)']];
    var Behavior = /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(Behavior, _super);
        function Behavior(plugin, data) {
            var _this = _super.call(this, plugin, {}) || this;
            _this.plugin = plugin;
            _this.data = data;
            _this.cache = lru_cache_LRUCache.create(25);
            _this.params = {};
            _this.lastLoci = mol_model_loci["EmptyLoci"];
            _this.ref = '';
            _this.channels = {};
            _this.infoMap = new Map();
            _this.data.entries.forEach(function (info) { return _this.infoMap.set(info.dataId, info); });
            return _this;
        }
        Object.defineProperty(Behavior.prototype, "info", {
            get: function () {
                return this.infoMap.get(this.params.entry.name);
            },
            enumerable: false,
            configurable: true
        });
        Behavior.prototype.queryData = function (box) {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var url, a, b, entry, urlAsset, asset, data, removed;
                return Object(tslib_es6["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            url = Object(mol_util_url["a" /* urlCombine */])(this.data.serverUrl, this.info.kind + "/" + this.info.dataId.toLowerCase());
                            if (box) {
                                a = box.min, b = box.max;
                                url += "/box"
                                    + ("/" + a.map(function (v) { return Math.round(1000 * v) / 1000; }).join(','))
                                    + ("/" + b.map(function (v) { return Math.round(1000 * v) / 1000; }).join(','));
                            }
                            else {
                                url += "/cell";
                            }
                            url += "?detail=" + this.params.entry.params.detailLevel;
                            entry = lru_cache_LRUCache.get(this.cache, url);
                            if (entry)
                                return [2 /*return*/, entry.data];
                            urlAsset = assets["Asset"].getUrlAsset(this.plugin.managers.asset, url);
                            return [4 /*yield*/, this.plugin.runTask(this.plugin.managers.asset.resolve(urlAsset, 'binary'))];
                        case 1:
                            asset = _a.sent();
                            return [4 /*yield*/, this.parseCif(asset.data)];
                        case 2:
                            data = _a.sent();
                            if (!data)
                                return [2 /*return*/];
                            removed = lru_cache_LRUCache.set(this.cache, url, { data: data, asset: asset });
                            if (removed)
                                removed.asset.dispose();
                            return [2 /*return*/, data];
                    }
                });
            });
        };
        Behavior.prototype.parseCif = function (data) {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var parsed, ret, i, block, densityServerCif, volume;
                return Object(tslib_es6["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0: return [4 /*yield*/, this.plugin.runTask(cif["a" /* CIF */].parseBinary(data))];
                        case 1:
                            parsed = _a.sent();
                            if (parsed.isError) {
                                this.plugin.log.error('VolumeStreaming, parsing CIF: ' + parsed.toString());
                                return [2 /*return*/];
                            }
                            if (parsed.result.blocks.length < 2) {
                                this.plugin.log.error('VolumeStreaming: Invalid data.');
                                return [2 /*return*/];
                            }
                            ret = {};
                            i = 1;
                            _a.label = 2;
                        case 2:
                            if (!(i < parsed.result.blocks.length)) return [3 /*break*/, 5];
                            block = parsed.result.blocks[i];
                            densityServerCif = cif["a" /* CIF */].schema.densityServer(block);
                            return [4 /*yield*/, this.plugin.runTask(Object(density_server["a" /* volumeFromDensityServerData */])(densityServerCif))];
                        case 3:
                            volume = _a.sent();
                            ret[block.header] = volume;
                            _a.label = 4;
                        case 4:
                            i++;
                            return [3 /*break*/, 2];
                        case 5: return [2 /*return*/, ret];
                    }
                });
            });
        };
        Behavior.prototype.updateDynamicBox = function (box) {
            if (this.params.entry.params.view.name !== 'selection-box')
                return;
            var state = this.plugin.state.data;
            var newParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, this.params), { entry: {
                    name: this.params.entry.name,
                    params: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, this.params.entry.params), { view: {
                            name: 'selection-box',
                            params: {
                                radius: this.params.entry.params.view.params.radius,
                                bottomLeft: box.min,
                                topRight: box.max
                            }
                        } })
                } });
            var update = state.build().to(this.ref).update(newParams);
            commands["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotUpdateCurrent: true } });
        };
        Behavior.prototype.getStructureRoot = function () {
            return this.plugin.state.data.select(mol_state["StateSelection"].Generators.byRef(this.ref).rootOfType([objects["a" /* PluginStateObject */].Molecule.Structure]))[0];
        };
        Behavior.prototype.register = function (ref) {
            var _this = this;
            this.ref = ref;
            this.subscribeObservable(this.plugin.state.events.object.removed, function (o) {
                if (!objects["a" /* PluginStateObject */].Molecule.Structure.is(o.obj) || !mol_model_structure["StructureElement"].Loci.is(_this.lastLoci))
                    return;
                if (_this.lastLoci.structure === o.obj.data) {
                    _this.lastLoci = mol_model_loci["EmptyLoci"];
                }
            });
            this.subscribeObservable(this.plugin.state.events.object.updated, function (o) {
                if (!objects["a" /* PluginStateObject */].Molecule.Structure.is(o.oldObj) || !mol_model_structure["StructureElement"].Loci.is(_this.lastLoci))
                    return;
                if (_this.lastLoci.structure === o.oldObj.data) {
                    _this.lastLoci = mol_model_loci["EmptyLoci"];
                }
            });
            this.subscribeObservable(this.plugin.managers.structure.focus.behaviors.current, function (entry) {
                if (!_this.plugin.state.data.tree.children.has(_this.ref))
                    return;
                var loci = entry ? entry.loci : mol_model_loci["EmptyLoci"];
                if (_this.params.entry.params.view.name !== 'selection-box') {
                    _this.lastLoci = loci;
                }
                else {
                    _this.updateInteraction(loci);
                }
            });
        };
        Behavior.prototype.unregister = function () {
            var entry = this.cache.entries.first;
            while (entry) {
                entry.value.data.asset.dispose();
                entry = entry.next;
            }
        };
        Behavior.prototype.getBoxFromLoci = function (loci) {
            var _a, _b;
            if (mol_model_loci["Loci"].isEmpty(loci)) {
                return geometry["b" /* Box3D */].empty();
            }
            var parent = this.plugin.helpers.substructureParent.get(loci.structure, true);
            if (!parent)
                return geometry["b" /* Box3D */].empty();
            var root = this.getStructureRoot();
            if (!root || ((_a = root.obj) === null || _a === void 0 ? void 0 : _a.data) !== ((_b = parent.obj) === null || _b === void 0 ? void 0 : _b.data))
                return geometry["b" /* Box3D */].empty();
            var extendedLoci = mol_model_structure["StructureElement"].Loci.extendToWholeResidues(loci);
            var box = mol_model_structure["StructureElement"].Loci.getBoundary(extendedLoci).box;
            if (mol_model_structure["StructureElement"].Loci.size(extendedLoci) === 1) {
                geometry["b" /* Box3D */].expand(box, box, linear_algebra["Vec3"].create(1, 1, 1));
            }
            return box;
        };
        Behavior.prototype.updateInteraction = function (loci) {
            if (mol_model_loci["Loci"].areEqual(this.lastLoci, loci)) {
                this.lastLoci = mol_model_loci["EmptyLoci"];
                this.updateDynamicBox(geometry["b" /* Box3D */].empty());
                return;
            }
            this.lastLoci = loci;
            if (Object(mol_model_loci["isEmptyLoci"])(loci)) {
                this.updateDynamicBox(geometry["b" /* Box3D */].empty());
                return;
            }
            var box = this.getBoxFromLoci(loci);
            this.updateDynamicBox(box);
        };
        Behavior.prototype.update = function (params) {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var switchedToSelection, box, emptyData, r, data, _a, info;
                return Object(tslib_es6["__generator"])(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            switchedToSelection = params.entry.params.view.name === 'selection-box' && this.params && this.params.entry && this.params.entry.params && this.params.entry.params.view && this.params.entry.params.view.name !== 'selection-box';
                            this.params = params;
                            box = void 0, emptyData = false;
                            switch (params.entry.params.view.name) {
                                case 'off':
                                    emptyData = true;
                                    break;
                                case 'box':
                                    box = geometry["b" /* Box3D */].create(params.entry.params.view.params.bottomLeft, params.entry.params.view.params.topRight);
                                    emptyData = geometry["b" /* Box3D */].volume(box) < 0.0001;
                                    break;
                                case 'selection-box': {
                                    if (switchedToSelection) {
                                        box = this.getBoxFromLoci(this.lastLoci) || geometry["b" /* Box3D */].empty();
                                    }
                                    else {
                                        box = geometry["b" /* Box3D */].create(linear_algebra["Vec3"].clone(params.entry.params.view.params.bottomLeft), linear_algebra["Vec3"].clone(params.entry.params.view.params.topRight));
                                    }
                                    r = params.entry.params.view.params.radius;
                                    emptyData = geometry["b" /* Box3D */].volume(box) < 0.0001;
                                    geometry["b" /* Box3D */].expand(box, box, linear_algebra["Vec3"].create(r, r, r));
                                    break;
                                }
                                case 'cell':
                                    box = this.info.kind === 'x-ray'
                                        ? this.data.structure.boundary.box
                                        : void 0;
                                    break;
                            }
                            if (!emptyData) return [3 /*break*/, 1];
                            _a = {};
                            return [3 /*break*/, 3];
                        case 1: return [4 /*yield*/, this.queryData(box)];
                        case 2:
                            _a = _b.sent();
                            _b.label = 3;
                        case 3:
                            data = _a;
                            if (!data)
                                return [2 /*return*/, false];
                            info = params.entry.params.channels;
                            if (this.info.kind === 'x-ray') {
                                this.channels['2fo-fc'] = this.createChannel(data['2FO-FC'] || mol_model_volume["b" /* Volume */].One, info['2fo-fc'], this.info.header.sampling[0].valuesInfo[0]);
                                this.channels['fo-fc(+ve)'] = this.createChannel(data['FO-FC'] || mol_model_volume["b" /* Volume */].One, info['fo-fc(+ve)'], this.info.header.sampling[0].valuesInfo[1]);
                                this.channels['fo-fc(-ve)'] = this.createChannel(data['FO-FC'] || mol_model_volume["b" /* Volume */].One, info['fo-fc(-ve)'], this.info.header.sampling[0].valuesInfo[1]);
                            }
                            else {
                                this.channels['em'] = this.createChannel(data['EM'] || mol_model_volume["b" /* Volume */].One, info['em'], this.info.header.sampling[0].valuesInfo[0]);
                            }
                            return [2 /*return*/, true];
                    }
                });
            });
        };
        Behavior.prototype.createChannel = function (data, info, stats) {
            var i = info;
            return {
                data: data,
                color: i.color,
                wireframe: i.wireframe,
                opacity: i.opacity,
                isoValue: i.isoValue.kind === 'relative' ? i.isoValue : mol_model_volume["b" /* Volume */].IsoValue.toRelative(i.isoValue, stats)
            };
        };
        Behavior.prototype.getDescription = function () {
            if (this.params.entry.params.view.name === 'selection-box')
                return 'Selection';
            if (this.params.entry.params.view.name === 'box')
                return 'Static Box';
            if (this.params.entry.params.view.name === 'cell')
                return 'Cell';
            return '';
        };
        return Behavior;
    }(behavior["PluginBehavior"].WithSubscribers));
    VolumeStreaming.Behavior = Behavior;
})(behavior_VolumeStreaming || (behavior_VolumeStreaming = {}));
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 161 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Lab; });
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(43);
/* harmony import */ var _hcl__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(233);
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(46);
/* harmony import */ var _mol_math_interpolate__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(78);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * Color conversion code adapted from chroma.js (https://github.com/gka/chroma.js)
 * Copyright (c) 2011-2018, Gregor Aisch, BSD license
 */





/**
 * CIE LAB color
 *
 * - L* [0..100] - lightness from black to white
 * - a [-100..100] - green (-) to red (+)
 * - b [-100..100] - blue (-) to yellow (+)
 *
 * see https://en.wikipedia.org/wiki/CIELAB_color_space
 */
function Lab() {
    return Lab.zero();
}
(function (Lab) {
    function zero() {
        var out = [0.1, 0.0, 0.0];
        out[0] = 0;
        return out;
    }
    Lab.zero = zero;
    function create(l, a, b) {
        var out = zero();
        out[0] = l;
        out[1] = a;
        out[2] = b;
        return out;
    }
    Lab.create = create;
    function fromColor(out, color) {
        var _a = _color__WEBPACK_IMPORTED_MODULE_0__["Color"].toRgb(color), r = _a[0], g = _a[1], b = _a[2];
        var _b = rgbToXyz(r, g, b), x = _b[0], y = _b[1], z = _b[2];
        var l = 116 * y - 16;
        out[0] = l < 0 ? 0 : l;
        out[1] = 500 * (x - y);
        out[2] = 200 * (y - z);
        return out;
    }
    Lab.fromColor = fromColor;
    function fromHcl(out, hcl) {
        return _hcl__WEBPACK_IMPORTED_MODULE_1__[/* Hcl */ "a"].toLab(out, hcl);
    }
    Lab.fromHcl = fromHcl;
    function toColor(lab) {
        var y = (lab[0] + 16) / 116;
        var x = isNaN(lab[1]) ? y : y + lab[1] / 500;
        var z = isNaN(lab[2]) ? y : y - lab[2] / 200;
        y = Yn * lab_xyz(y);
        x = Xn * lab_xyz(x);
        z = Zn * lab_xyz(z);
        var r = xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z); // D65 -> sRGB
        var g = xyz_rgb(-0.9692660 * x + 1.8760108 * y + 0.0415560 * z);
        var b = xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z);
        return _color__WEBPACK_IMPORTED_MODULE_0__["Color"].fromRgb(Math.round(Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_3__[/* clamp */ "a"])(r, 0, 255)), Math.round(Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_3__[/* clamp */ "a"])(g, 0, 255)), Math.round(Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_3__[/* clamp */ "a"])(b, 0, 255)));
    }
    Lab.toColor = toColor;
    function toHcl(out, lab) {
        var l = lab[0], a = lab[1], b = lab[2];
        var c = Math.sqrt(a * a + b * b);
        var h = (Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_2__[/* radToDeg */ "f"])(Math.atan2(b, a)) + 360) % 360;
        if (Math.round(c * 10000) === 0)
            h = Number.NaN;
        out[0] = h;
        out[1] = c;
        out[2] = l;
        return out;
    }
    Lab.toHcl = toHcl;
    function copy(out, c) {
        out[0] = c[0];
        out[1] = c[1];
        out[2] = c[2];
        return out;
    }
    Lab.copy = copy;
    function darken(out, c, amount) {
        out[0] = c[0] - Kn * amount;
        out[1] = c[1];
        out[2] = c[2];
        return out;
    }
    Lab.darken = darken;
    function lighten(out, c, amount) {
        return darken(out, c, -amount);
    }
    Lab.lighten = lighten;
    var tmpSaturateHcl = [0, 0, 0];
    function saturate(out, c, amount) {
        toHcl(tmpSaturateHcl, c);
        return _hcl__WEBPACK_IMPORTED_MODULE_1__[/* Hcl */ "a"].toLab(out, _hcl__WEBPACK_IMPORTED_MODULE_1__[/* Hcl */ "a"].saturate(tmpSaturateHcl, tmpSaturateHcl, amount));
    }
    Lab.saturate = saturate;
    function desaturate(out, c, amount) {
        return saturate(out, c, -amount);
    }
    Lab.desaturate = desaturate;
    // Corresponds roughly to RGB brighter/darker
    var Kn = 18;
    /** D65 standard referent */
    var Xn = 0.950470;
    var Yn = 1;
    var Zn = 1.088830;
    var T0 = 0.137931034; // 4 / 29
    var T1 = 0.206896552; // 6 / 29
    var T2 = 0.12841855; // 3 * t1 * t1
    var T3 = 0.008856452; // t1 * t1 * t1
    /** convert component from xyz to rgb */
    function xyz_rgb(c) {
        return 255 * (c <= 0.00304 ? 12.92 * c : 1.055 * Math.pow(c, 1 / 2.4) - 0.055);
    }
    /** convert component from lab to xyz */
    function lab_xyz(t) {
        return t > T1 ? t * t * t : T2 * (t - T0);
    }
    /** convert component from rgb to xyz */
    function rgb_xyz(c) {
        if ((c /= 255) <= 0.04045)
            return c / 12.92;
        return Math.pow((c + 0.055) / 1.055, 2.4);
    }
    /** convert component from xyz to lab */
    function xyz_lab(t) {
        if (t > T3)
            return Math.pow(t, 1 / 3);
        return t / T2 + T0;
    }
    function rgbToXyz(r, g, b) {
        r = rgb_xyz(r);
        g = rgb_xyz(g);
        b = rgb_xyz(b);
        var x = xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / Xn);
        var y = xyz_lab((0.2126729 * r + 0.7151522 * g + 0.0721750 * b) / Yn);
        var z = xyz_lab((0.0193339 * r + 0.1191920 * g + 0.9503041 * b) / Zn);
        return [x, y, z];
    }
})(Lab || (Lab = {}));
//# sourceMappingURL=lab.js.map

/***/ }),
/* 162 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createStructureRepresentationParams", function() { return createStructureRepresentationParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getStructureThemeTypes", function() { return getStructureThemeTypes; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createStructureColorThemeParams", function() { return createStructureColorThemeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createStructureSizeThemeParams", function() { return createStructureSizeThemeParams; });
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function createStructureRepresentationParams(ctx, structure, props) {
    if (props === void 0) { props = {}; }
    var p = props;
    if (typeof p.type === 'string' || typeof p.color === 'string' || typeof p.size === 'string')
        return createParamsByName(ctx, structure || _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Structure"].Empty, props);
    return createParamsProvider(ctx, structure || _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Structure"].Empty, props);
}
function getStructureThemeTypes(ctx, structure) {
    var themeCtx = ctx.representation.structure.themes;
    if (!structure)
        return themeCtx.colorThemeRegistry.types;
    return themeCtx.colorThemeRegistry.getApplicableTypes({ structure: structure });
}
function createStructureColorThemeParams(ctx, structure, typeName, themeName, params) {
    var _a = ctx.representation.structure, registry = _a.registry, themes = _a.themes;
    var repr = registry.get(typeName || registry.default.name);
    var color = themes.colorThemeRegistry.get(themeName || repr.defaultColorTheme.name);
    var colorDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(color.getParams({ structure: structure || _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Structure"].Empty }));
    if (color.name === repr.defaultColorTheme.name)
        Object.assign(colorDefaultParams, repr.defaultColorTheme.props);
    return { name: color.name, params: Object.assign(colorDefaultParams, params) };
}
function createStructureSizeThemeParams(ctx, structure, typeName, themeName, params) {
    var _a = ctx.representation.structure, registry = _a.registry, themes = _a.themes;
    var repr = registry.get(typeName || registry.default.name);
    var size = themes.sizeThemeRegistry.get(themeName || repr.defaultSizeTheme.name);
    var sizeDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(size.getParams({ structure: structure || _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Structure"].Empty }));
    if (size.name === repr.defaultSizeTheme.name)
        Object.assign(sizeDefaultParams, repr.defaultSizeTheme.props);
    return { name: size.name, params: Object.assign(sizeDefaultParams, params) };
}
function createParamsByName(ctx, structure, props) {
    var typeProvider = (props.type && ctx.representation.structure.registry.get(props.type))
        || ctx.representation.structure.registry.default.provider;
    var colorProvider = (props.color && ctx.representation.structure.themes.colorThemeRegistry.get(props.color))
        || ctx.representation.structure.themes.colorThemeRegistry.get(typeProvider.defaultColorTheme.name);
    var sizeProvider = (props.size && ctx.representation.structure.themes.sizeThemeRegistry.get(props.size))
        || ctx.representation.structure.themes.sizeThemeRegistry.get(typeProvider.defaultSizeTheme.name);
    return createParamsProvider(ctx, structure, {
        type: typeProvider,
        typeParams: props.typeParams,
        color: colorProvider,
        colorParams: props.colorParams,
        size: sizeProvider,
        sizeParams: props.sizeParams
    });
}
function createParamsProvider(ctx, structure, props) {
    if (props === void 0) { props = {}; }
    var themeCtx = ctx.representation.structure.themes;
    var themeDataCtx = { structure: structure };
    var repr = props.type || ctx.representation.structure.registry.default.provider;
    var reprDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(repr.getParams(themeCtx, structure));
    var reprParams = Object.assign(reprDefaultParams, props.typeParams);
    var color = props.color || themeCtx.colorThemeRegistry.get(repr.defaultColorTheme.name);
    var colorDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(color.getParams(themeDataCtx));
    if (color.name === repr.defaultColorTheme.name)
        Object.assign(colorDefaultParams, repr.defaultColorTheme.props);
    var colorParams = Object.assign(colorDefaultParams, props.colorParams);
    var size = props.size || themeCtx.sizeThemeRegistry.get(repr.defaultSizeTheme.name);
    var sizeDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(size.getParams(themeDataCtx));
    if (size.name === repr.defaultSizeTheme.name)
        Object.assign(sizeDefaultParams, repr.defaultSizeTheme.props);
    var sizeParams = Object.assign(sizeDefaultParams, props.sizeParams);
    return ({
        type: { name: repr.name, params: reprParams },
        colorTheme: { name: color.name, params: colorParams },
        sizeTheme: { name: size.name, params: sizeParams }
    });
}
//# sourceMappingURL=structure-representation-params.js.map

/***/ }),
/* 163 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "QueryRuntimeTable", function() { return /* reexport */ QueryRuntimeTable; });
__webpack_require__.d(__webpack_exports__, "DefaultQueryRuntimeTable", function() { return /* reexport */ DefaultQueryRuntimeTable; });
__webpack_require__.d(__webpack_exports__, "QueryCompilerCtx", function() { return /* reexport */ base_QueryCompilerCtx; });
__webpack_require__.d(__webpack_exports__, "QueryCompiledSymbol", function() { return /* reexport */ QueryCompiledSymbol; });
__webpack_require__.d(__webpack_exports__, "CompiledQueryFn", function() { return /* reexport */ CompiledQueryFn; });
__webpack_require__.d(__webpack_exports__, "QueryRuntimeArguments", function() { return /* reexport */ QueryRuntimeArguments; });
__webpack_require__.d(__webpack_exports__, "QuerySymbolRuntime", function() { return /* reexport */ QuerySymbolRuntime; });
__webpack_require__.d(__webpack_exports__, "compile", function() { return /* reexport */ compile; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/expression.js
var language_expression = __webpack_require__(132);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var structure = __webpack_require__(4);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/base.js
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var QueryRuntimeTable = /** @class */ (function () {
    function QueryRuntimeTable() {
        this.map = new Map();
    }
    QueryRuntimeTable.prototype.removeSymbol = function (runtime) {
        this.map.delete(runtime.symbol.id);
    };
    QueryRuntimeTable.prototype.addSymbol = function (runtime) {
        if (this.map.has(runtime.symbol.id)) {
            console.warn("Symbol '" + runtime.symbol.id + "' already added. Call removeSymbol/removeCustomProps re-adding the symbol.");
        }
        this.map.set(runtime.symbol.id, runtime);
    };
    QueryRuntimeTable.prototype.addCustomProp = function (desc) {
        if (!desc.symbols)
            return;
        for (var _a = 0, _b = Object.keys(desc.symbols); _a < _b.length; _a++) {
            var k = _b[_a];
            this.addSymbol(desc.symbols[k]);
        }
    };
    QueryRuntimeTable.prototype.removeCustomProp = function (desc) {
        if (!desc.symbols)
            return;
        for (var _a = 0, _b = Object.keys(desc.symbols); _a < _b.length; _a++) {
            var k = _b[_a];
            this.removeSymbol(desc.symbols[k]);
        }
    };
    QueryRuntimeTable.prototype.getRuntime = function (id) {
        return this.map.get(id);
    };
    return QueryRuntimeTable;
}());

var DefaultQueryRuntimeTable = new QueryRuntimeTable();
var base_QueryCompilerCtx = /** @class */ (function () {
    function QueryCompilerCtx(table) {
        this.table = table;
        this.constQueryContext = new structure["QueryContext"](structure["Structure"].Empty);
    }
    return QueryCompilerCtx;
}());

var QueryCompiledSymbol;
(function (QueryCompiledSymbol) {
    function Const(value) {
        return { kind: 'const', value: value };
    }
    QueryCompiledSymbol.Const = Const;
    function Dynamic(runtime) {
        return { kind: 'dynamic', runtime: runtime };
    }
    QueryCompiledSymbol.Dynamic = Dynamic;
})(QueryCompiledSymbol || (QueryCompiledSymbol = {}));
var CompiledQueryFn;
(function (CompiledQueryFn) {
    function Const(value) {
        return { isConst: true, fn: function CompiledQueryFn_Const(ctx) { return value; } };
    }
    CompiledQueryFn.Const = Const;
    function Dynamic(fn) {
        return { isConst: false, fn: fn };
    }
    CompiledQueryFn.Dynamic = Dynamic;
})(CompiledQueryFn || (CompiledQueryFn = {}));
var QueryRuntimeArguments;
(function (QueryRuntimeArguments) {
    function forEachEval(xs, queryCtx, f, ctx) {
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                f(xs[i](queryCtx), i, ctx);
        }
        else {
            var i = 0;
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                f(xs[k](queryCtx), i++, ctx);
            }
        }
        return ctx;
    }
    QueryRuntimeArguments.forEachEval = forEachEval;
})(QueryRuntimeArguments || (QueryRuntimeArguments = {}));
var QuerySymbolRuntime;
(function (QuerySymbolRuntime) {
    function Const(symbol, fn) {
        return new base_SymbolRuntimeImpl(symbol, fn, true);
    }
    QuerySymbolRuntime.Const = Const;
    function Dynamic(symbol, fn) {
        return new base_SymbolRuntimeImpl(symbol, fn, false);
    }
    QuerySymbolRuntime.Dynamic = Dynamic;
})(QuerySymbolRuntime || (QuerySymbolRuntime = {}));
var base_SymbolRuntimeImpl = /** @class */ (function () {
    function SymbolRuntimeImpl(symbol, fn, isConst) {
        this.symbol = symbol;
        this.fn = fn;
        this.isConst = isConst;
    }
    SymbolRuntimeImpl.prototype.compile = function (ctx, inputArgs) {
        var args, constArgs = false;
        if (!inputArgs) {
            args = void 0;
            constArgs = true;
        }
        else if (language_expression["a" /* default */].isArgumentsArray(inputArgs)) {
            args = [];
            constArgs = false;
            for (var _a = 0, inputArgs_1 = inputArgs; _a < inputArgs_1.length; _a++) {
                var arg = inputArgs_1[_a];
                var compiled = _compile(ctx, arg);
                constArgs = constArgs && compiled.isConst;
                args.push(compiled.fn);
            }
        }
        else {
            args = Object.create(null);
            constArgs = false;
            for (var _b = 0, _c = Object.keys(inputArgs); _b < _c.length; _b++) {
                var key = _c[_b];
                var compiled = _compile(ctx, inputArgs[key]);
                constArgs = constArgs && compiled.isConst;
                args[key] = compiled.fn;
            }
        }
        if (this.isConst) {
            if (this.isConst && constArgs) {
                return CompiledQueryFn.Const(this.fn(ctx.constQueryContext, args));
            }
            return CompiledQueryFn.Dynamic(createDynamicFn(this.fn, args));
        }
        return CompiledQueryFn.Dynamic(createDynamicFn(this.fn, args));
    };
    return SymbolRuntimeImpl;
}());
function createDynamicFn(fn, args) {
    return function DynamicFn(ctx) { return fn(ctx, args); };
}
function _compile(ctx, expression) {
    if (language_expression["a" /* default */].isLiteral(expression)) {
        return CompiledQueryFn.Const(expression);
    }
    if (language_expression["a" /* default */].isSymbol(expression)) {
        var runtime = ctx.table.getRuntime(expression.name);
        if (!runtime)
            return CompiledQueryFn.Const(expression.name);
        return runtime.compile(ctx);
    }
    if (!language_expression["a" /* default */].isSymbol(expression.head)) {
        throw new Error('Can only apply symbols.');
    }
    var compiler = ctx.table.getRuntime(expression.head.name);
    if (!compiler) {
        throw new Error("Symbol '" + expression.head.name + "' is not implemented.");
    }
    return compiler.compile(ctx, expression.args);
}
function compile(expression) {
    var ctx = new base_QueryCompilerCtx(DefaultQueryRuntimeTable);
    return _compile(ctx, expression).fn;
}
//# sourceMappingURL=base.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol-table.js + 1 modules
var symbol_table = __webpack_require__(12);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var set = __webpack_require__(90);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string.js
var string = __webpack_require__(41);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic.js
var atomic = __webpack_require__(119);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/internal.js
var internal = __webpack_require__(268);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/table.js
/**
 * Copyright (c) 2018-2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var C = QuerySymbolRuntime.Const;
var D = QuerySymbolRuntime.Dynamic;
var symbols = [
    // ============= TYPES =============
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.bool, function core_type_bool(ctx, v) { return !!v[0](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.num, function core_type_num(ctx, v) { return +v[0](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.str, function core_type_str(ctx, v) { return '' + v[0](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.list, function core_type_list(ctx, xs) { return QueryRuntimeArguments.forEachEval(xs, ctx, function (v, i, list) { return list[i] = v; }, []); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.set, function core_type_set(ctx, xs) { return QueryRuntimeArguments.forEachEval(xs, ctx, function core_type_set_argEval(v, i, set) { return set.add(v); }, new Set()); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.regex, function core_type_regex(ctx, v) { return new RegExp(v[0](ctx), (v[1] && v[1](ctx)) || ''); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.bitflags, function core_type_bitflags(ctx, v) { return +v[0](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.type.compositeKey, function core_type_compositeKey(ctx, xs) { return QueryRuntimeArguments.forEachEval(xs, ctx, function (v, i, list) { return list[i] = '' + v; }, []).join('-'); }),
    // ============= LOGIC ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.logic.not, function (ctx, v) { return !v[0](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.logic.and, function (ctx, xs) {
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                if (!xs[i](ctx))
                    return false;
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                if (!xs[k](ctx))
                    return false;
            }
        }
        return true;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.logic.or, function (ctx, xs) {
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                if (xs[i](ctx))
                    return true;
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                if (xs[k](ctx))
                    return true;
            }
        }
        return false;
    }),
    // ============= RELATIONAL ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.eq, function (ctx, v) { return v[0](ctx) === v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.neq, function (ctx, v) { return v[0](ctx) !== v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.lt, function (ctx, v) { return v[0](ctx) < v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.lte, function (ctx, v) { return v[0](ctx) <= v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.gr, function (ctx, v) { return v[0](ctx) > v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.gre, function (ctx, v) { return v[0](ctx) >= v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.rel.inRange, function (ctx, v) {
        var x = v[0](ctx);
        return x >= v[1](ctx) && x <= v[2](ctx);
    }),
    // ============= ARITHMETIC ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.add, function (ctx, xs) {
        var ret = 0;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret += xs[i](ctx);
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret += xs[k](ctx);
            }
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.sub, function (ctx, xs) {
        var ret = 0;
        if (typeof xs.length === 'number') {
            if (xs.length === 1)
                return -xs[0](ctx);
            ret = xs[0](ctx) || 0;
            for (var i = 1, _i = xs.length; i < _i; i++)
                ret -= xs[i](ctx);
        }
        else {
            var keys = Object.keys(xs);
            if (keys.length === 1)
                return -xs[keys[0]](ctx);
            ret = xs[keys[0]](ctx) || 0;
            for (var i = 1, _i = keys.length; i < _i; i++)
                ret -= xs[keys[i]](ctx);
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.mult, function (ctx, xs) {
        var ret = 1;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret *= xs[i](ctx);
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret *= xs[k](ctx);
            }
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.div, function (ctx, v) { return v[0](ctx) / v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.pow, function (ctx, v) { return Math.pow(v[0](ctx), v[1](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.mod, function (ctx, v) { return v[0](ctx) % v[1](ctx); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.min, function (ctx, xs) {
        var ret = Number.POSITIVE_INFINITY;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret = Math.min(xs[i](ctx), ret);
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret = Math.min(xs[k](ctx), ret);
            }
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.max, function (ctx, xs) {
        var ret = Number.NEGATIVE_INFINITY;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret = Math.max(xs[i](ctx), ret);
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret = Math.max(xs[k](ctx), ret);
            }
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.floor, function (ctx, v) { return Math.floor(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.ceil, function (ctx, v) { return Math.ceil(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.roundInt, function (ctx, v) { return Math.round(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.abs, function (ctx, v) { return Math.abs(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.sqrt, function (ctx, v) { return Math.sqrt(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.cbrt, function (ctx, v) { return Math.cbrt(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.sin, function (ctx, v) { return Math.sin(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.cos, function (ctx, v) { return Math.cos(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.tan, function (ctx, v) { return Math.tan(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.asin, function (ctx, v) { return Math.asin(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.acos, function (ctx, v) { return Math.acos(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.atan, function (ctx, v) { return Math.atan(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.sinh, function (ctx, v) { return Math.sinh(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.cosh, function (ctx, v) { return Math.cosh(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.tanh, function (ctx, v) { return Math.tanh(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.exp, function (ctx, v) { return Math.exp(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.log, function (ctx, v) { return Math.log(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.log10, function (ctx, v) { return Math.log10(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.math.atan2, function (ctx, v) { return Math.atan2(v[0](ctx), v[1](ctx)); }),
    // ============= STRING ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.str.match, function (ctx, v) { return v[0](ctx).test(v[1](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.str.concat, function (ctx, xs) {
        var ret = [];
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret.push(xs[i](ctx).toString());
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret.push(xs[k](ctx).toString());
            }
        }
        return ret.join('');
    }),
    // ============= LIST ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.list.getAt, function (ctx, v) { return v[0](ctx)[v[1](ctx)]; }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.list.equal, function (ctx, v) { return Object(array["arrayEqual"])(v[0](ctx), v[1](ctx)); }),
    // ============= SET ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.set.has, function core_set_has(ctx, v) { return v[0](ctx).has(v[1](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.set.isSubset, function core_set_isSubset(ctx, v) { return set["a" /* SetUtils */].isSuperset(v[1](ctx), v[0](ctx)); }),
    // ============= FLAGS ================
    C(symbol_table["a" /* MolScriptSymbolTable */].core.flags.hasAny, function (ctx, v) {
        var test = v[1](ctx);
        var tested = v[0](ctx);
        if (!test)
            return !!tested;
        return (tested & test) !== 0;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].core.flags.hasAll, function (ctx, v) {
        var test = v[1](ctx);
        var tested = v[0](ctx);
        if (!test)
            return !tested;
        return (tested & test) === test;
    }),
    // Structure
    // ============= TYPES ================
    C(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.elementSymbol, function (ctx, v) { return Object(types["ElementSymbol"])(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.atomName, function (ctx, v) { return Object(string["g" /* upperCaseAny */])(v[0](ctx)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.bondFlags, function (ctx, xs) {
        var ret = 0 /* None */;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret = bondFlag(ret, xs[i](ctx));
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret = bondFlag(ret, xs[k](ctx));
            }
        }
        return ret;
    }),
    C(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.ringFingerprint, function (ctx, xs) { return structure["UnitRing"].elementFingerprint(getArray(ctx, xs)); }),
    C(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.type.secondaryStructureFlags, function (ctx, xs) {
        var ret = 0 /* None */;
        if (typeof xs.length === 'number') {
            for (var i = 0, _i = xs.length; i < _i; i++)
                ret = secondaryStructureFlag(ret, xs[i](ctx));
        }
        else {
            for (var _a = 0, _b = Object.keys(xs); _a < _b.length; _a++) {
                var k = _b[_a];
                ret = secondaryStructureFlag(ret, xs[k](ctx));
            }
        }
        return ret;
    }),
    // TODO:
    // C(MolScript.structureQuery.type.entityType, (ctx, v) => StructureRuntime.Common.entityType(v[0](ctx))),
    // C(MolScript.structureQuery.type.authResidueId, (ctx, v) => ResidueIdentifier.auth(v[0](ctx), v[1](ctx), v[2] && v[2](ctx))),
    // C(MolScript.structureQuery.type.labelResidueId, (ctx, v) => ResidueIdentifier.label(v[0](ctx), v[1](ctx), v[2](ctx), v[3] && v[3](ctx))),
    // ============= SLOTS ================
    // TODO: slots might not be needed after all: reducer simply pushes/pops current element
    // C(MolScript.structureQuery.slot.element, (ctx, _) => ctx_.element),
    // C(MolScript.structureQuery.slot.elementSetReduce, (ctx, _) => ctx_.element),
    // ============= FILTERS ================
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.pick, function (ctx, xs) { return structure["Queries"].filters.pick(xs[0], xs['test'])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.first, function (ctx, xs) { return structure["Queries"].filters.first(xs[0])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.withSameAtomProperties, function (ctx, xs) { return structure["Queries"].filters.withSameAtomProperties(xs[0], xs['source'], xs['property'])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.intersectedBy, function (ctx, xs) { return structure["Queries"].filters.areIntersectedBy(xs[0], xs['by'])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.within, function (ctx, xs) { return structure["Queries"].filters.within({
        query: xs[0],
        target: xs['target'],
        minRadius: xs['min-radius'],
        maxRadius: xs['max-radius'],
        elementRadius: xs['atom-radius'],
        invert: xs['invert']
    })(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.filter.isConnectedTo, function (ctx, xs) { return structure["Queries"].filters.isConnectedTo({
        query: xs[0],
        target: xs['target'],
        disjunct: xs['disjunct'],
        invert: xs['invert'],
        bondTest: xs['bond-test']
    })(ctx); }),
    // ============= GENERATORS ================
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.atomGroups, function structureQuery_generator_atomGroups(ctx, xs) {
        return structure["Queries"].generators.atoms({
            entityTest: xs['entity-test'],
            chainTest: xs['chain-test'],
            residueTest: xs['residue-test'],
            atomTest: xs['atom-test'],
            groupBy: xs['group-by']
        })(ctx);
    }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.all, function structureQuery_generator_all(ctx) { return structure["Queries"].generators.all(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.empty, function structureQuery_generator_empty(ctx) { return structure["Queries"].generators.none(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.bondedAtomicPairs, function structureQuery_generator_bondedAtomicPairs(ctx, xs) {
        return structure["Queries"].generators.bondedAtomicPairs(xs && xs[0])(ctx);
    }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.generator.rings, function structureQuery_generator_rings(ctx, xs) {
        var _a, _b;
        return structure["Queries"].generators.rings((_a = xs === null || xs === void 0 ? void 0 : xs['fingerprint']) === null || _a === void 0 ? void 0 : _a.call(xs, ctx), (_b = xs === null || xs === void 0 ? void 0 : xs['only-aromatic']) === null || _b === void 0 ? void 0 : _b.call(xs, ctx))(ctx);
    }),
    // ============= MODIFIERS ================
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.includeSurroundings, function structureQuery_modifier_includeSurroundings(ctx, xs) {
        return structure["Queries"].modifiers.includeSurroundings(xs[0], {
            radius: xs['radius'](ctx),
            wholeResidues: !!(xs['as-whole-residues'] && xs['as-whole-residues'](ctx)),
            elementRadius: xs['atom-radius']
        })(ctx);
    }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.wholeResidues, function structureQuery_modifier_wholeResidues(ctx, xs) { return structure["Queries"].modifiers.wholeResidues(xs[0])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.union, function structureQuery_modifier_union(ctx, xs) { return structure["Queries"].modifiers.union(xs[0])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.expandProperty, function structureQuery_modifier_expandProperty(ctx, xs) { return structure["Queries"].modifiers.expandProperty(xs[0], xs['property'])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.exceptBy, function structureQuery_modifier_exceptBy(ctx, xs) { return structure["Queries"].modifiers.exceptBy(xs[0], xs['by'])(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.modifier.includeConnected, function structureQuery_modifier_includeConnected(ctx, xs) {
        return structure["Queries"].modifiers.includeConnected({
            query: xs[0],
            bondTest: xs['bond-test'],
            wholeResidues: !!(xs['as-whole-residues'] && xs['as-whole-residues'](ctx)),
            layerCount: (xs['layer-count'] && xs['layer-count'](ctx)) || 1
        })(ctx);
    }),
    // ============= COMBINATORS ================
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.combinator.merge, function (ctx, xs) { return structure["Queries"].combinators.merge(xs)(ctx); }),
    // ============= ATOM PROPERTIES ================
    // ~~~ CORE ~~~
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.elementSymbol, atomProp(structure["StructureProperties"].atom.type_symbol)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.vdw, function (ctx, xs) { return Object(atomic["VdwRadius"])(structure["StructureProperties"].atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.mass, function (ctx, xs) { return Object(atomic["AtomWeight"])(structure["StructureProperties"].atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.atomicNumber, function (ctx, xs) { return Object(atomic["AtomNumber"])(structure["StructureProperties"].atom.type_symbol((xs && xs[0] && xs[0](ctx)) || ctx.element)); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.x, atomProp(structure["StructureProperties"].atom.x)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.y, atomProp(structure["StructureProperties"].atom.y)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.z, atomProp(structure["StructureProperties"].atom.z)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.sourceIndex, atomProp(structure["StructureProperties"].atom.sourceIndex)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.operatorName, atomProp(structure["StructureProperties"].unit.operator_name)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.modelIndex, atomProp(structure["StructureProperties"].unit.model_index)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.modelLabel, atomProp(structure["StructureProperties"].unit.model_label)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.core.atomKey, function (ctx, xs) {
        var e = (xs && xs[0] && xs[0](ctx)) || ctx.element;
        return Object(util["f" /* cantorPairing */])(e.unit.id, e.element);
    }),
    // TODO:
    // D(MolScript.structureQuery.atomProperty.core.bondCount, (ctx, _) => ),
    // ~~~ TOPOLOGY ~~~
    // TODO
    // ~~~ MACROMOLECULAR ~~~
    // TODO:
    // // identifiers
    // labelResidueId: prop((env, v) => ResidueIdentifier.labelOfResidueIndex(env.context.model, getAddress(env, v).residue)),
    // authResidueId: prop((env, v) => ResidueIdentifier.authOfResidueIndex(env.context.model, getAddress(env, v).residue)),
    // keys
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.residueKey, function (ctx, xs) { return structure["StructureElement"].residueIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.chainKey, function (ctx, xs) { return structure["StructureElement"].chainIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityKey, function (ctx, xs) { return structure["StructureElement"].entityIndex((xs && xs[0] && xs[0](ctx)) || ctx.element); }),
    // mmCIF
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.id, atomProp(structure["StructureProperties"].atom.id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.isHet, function (ctx, xs) { return structure["StructureProperties"].residue.group_PDB((xs && xs[0] && xs[0](ctx)) || ctx.element) !== 'ATOM'; }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_atom_id, atomProp(structure["StructureProperties"].atom.label_atom_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_alt_id, atomProp(structure["StructureProperties"].atom.label_alt_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_comp_id, atomProp(structure["StructureProperties"].atom.label_comp_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_seq_id, atomProp(structure["StructureProperties"].residue.label_seq_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_asym_id, atomProp(structure["StructureProperties"].chain.label_asym_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.label_entity_id, atomProp(structure["StructureProperties"].entity.id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_atom_id, atomProp(structure["StructureProperties"].atom.auth_atom_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_comp_id, atomProp(structure["StructureProperties"].atom.auth_comp_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_seq_id, atomProp(structure["StructureProperties"].residue.auth_seq_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.auth_asym_id, atomProp(structure["StructureProperties"].chain.auth_asym_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.pdbx_PDB_ins_code, atomProp(structure["StructureProperties"].residue.pdbx_PDB_ins_code)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.pdbx_formal_charge, atomProp(structure["StructureProperties"].atom.pdbx_formal_charge)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.occupancy, atomProp(structure["StructureProperties"].atom.occupancy)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.B_iso_or_equiv, atomProp(structure["StructureProperties"].atom.B_iso_or_equiv)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityType, atomProp(structure["StructureProperties"].entity.type)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entitySubtype, atomProp(structure["StructureProperties"].entity.subtype)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityPrdId, atomProp(structure["StructureProperties"].entity.prd_id)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.entityDescription, atomProp(structure["StructureProperties"].entity.pdbx_description)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.objectPrimitive, atomProp(structure["StructureProperties"].unit.object_primitive)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.isNonStandard, atomProp(structure["StructureProperties"].residue.isNonStandard)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.secondaryStructureKey, atomProp(structure["StructureProperties"].residue.secondary_structure_key)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.secondaryStructureFlags, atomProp(structure["StructureProperties"].residue.secondary_structure_type)),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.atomProperty.macromolecular.chemCompType, atomProp(structure["StructureProperties"].residue.chem_comp_type)),
    // ============= BOND PROPERTIES ================
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.order, function (ctx, xs) { return ctx.atomicBond.order; }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.flags, function (ctx, xs) { return ctx.atomicBond.type; }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.atomA, function (ctx, xs) { return ctx.atomicBond.a; }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.atomB, function (ctx, xs) { return ctx.atomicBond.b; }),
    D(symbol_table["a" /* MolScriptSymbolTable */].structureQuery.bondProperty.length, function (ctx, xs) { return ctx.atomicBond.length; }),
    // Internal
    D(symbol_table["a" /* MolScriptSymbolTable */].internal.generator.bundleElement, function internal_generator_bundleElement(ctx, xs) { return Object(internal["bundleElementImpl"])(xs.groupedUnits(ctx), xs.ranges(ctx), xs.set(ctx)); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].internal.generator.bundle, function internal_generator_bundle(ctx, xs) { return Object(internal["bundleGenerator"])(xs.elements(ctx))(ctx); }),
    D(symbol_table["a" /* MolScriptSymbolTable */].internal.generator.current, function internal_generator_current(ctx, xs) { return ctx.tryGetCurrentSelection(); }),
];
function atomProp(p) {
    return function (ctx, xs) { return p((xs && xs[0] && xs[0](ctx)) || ctx.element); };
}
function bondFlag(current, f) {
    return current | (types["BondType"].isName(f) ? types["BondType"].fromName(f) : 0 /* None */);
}
function secondaryStructureFlag(current, f) {
    switch (f.toLowerCase()) {
        case 'helix': return current | 2 /* Helix */;
        case 'alpha': return current | 2 /* Helix */ | 4096 /* HelixAlpha */;
        case 'pi': return current | 2 /* Helix */ | 32768 /* HelixPi */;
        case '310': return current | 2 /* Helix */ | 2048 /* Helix3Ten */;
        case 'beta': return current | 4 /* Beta */;
        case 'strand': return current | 4 /* Beta */ | 4194304 /* BetaStrand */;
        case 'sheet': return current | 4 /* Beta */ | 8388608 /* BetaSheet */;
        case 'turn': return current | 16 /* Turn */;
        case 'bend': return current | 8 /* Bend */;
        case 'coil': return current | 536870912 /* NA */;
        default: return current;
    }
}
function getArray(ctx, xs) {
    var ret = [];
    if (!xs)
        return ret;
    if (typeof xs.length === 'number') {
        for (var i = 0, _i = xs.length; i < _i; i++)
            ret.push(xs[i](ctx));
    }
    else {
        var keys = Object.keys(xs);
        for (var i = 1, _i = keys.length; i < _i; i++)
            ret.push(xs[keys[i]](ctx));
    }
    return ret;
}
(function () {
    for (var _a = 0, symbols_1 = symbols; _a < symbols_1.length; _a++) {
        var s = symbols_1[_a];
        DefaultQueryRuntimeTable.addSymbol(s);
    }
})();
//# sourceMappingURL=table.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/compiler.js
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


//# sourceMappingURL=compiler.js.map

/***/ }),
/* 164 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return VisualUpdateState; });
/* unused harmony export DefaultQualityThresholds */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getStructureQuality; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getQualityProps; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var VisualUpdateState;
(function (VisualUpdateState) {
    function create() {
        return {
            updateTransform: false,
            updateMatrix: false,
            updateColor: false,
            updateSize: false,
            createGeometry: false,
            createNew: false,
            info: {}
        };
    }
    VisualUpdateState.create = create;
    function reset(state) {
        state.updateTransform = false;
        state.updateMatrix = false;
        state.updateColor = false;
        state.updateSize = false;
        state.createGeometry = false;
        state.createNew = false;
    }
    VisualUpdateState.reset = reset;
})(VisualUpdateState || (VisualUpdateState = {}));
var DefaultQualityThresholds = {
    lowestElementCount: 500000,
    lowerElementCount: 200000,
    lowElementCount: 60000,
    mediumElementCount: 20000,
    highElementCount: 2000,
    coarseGrainedFactor: 10,
    elementCountFactor: 1
};
function getStructureQuality(structure, tresholds) {
    if (tresholds === void 0) { tresholds = {}; }
    var t = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultQualityThresholds), tresholds);
    var score = structure.elementCount * t.elementCountFactor;
    if (structure.isCoarseGrained)
        score *= t.coarseGrainedFactor;
    if (score > t.lowestElementCount) {
        return 'lowest';
    }
    else if (score > t.lowerElementCount) {
        return 'lower';
    }
    else if (score > t.lowElementCount) {
        return 'low';
    }
    else if (score > t.mediumElementCount) {
        return 'medium';
    }
    else if (score > t.highElementCount) {
        return 'high';
    }
    else {
        return 'higher';
    }
}
function getQualityProps(props, data) {
    var quality = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.quality, 'auto');
    var detail = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.detail, 1);
    var radialSegments = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.radialSegments, 12);
    var linearSegments = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.linearSegments, 8);
    var resolution = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.resolution, 2);
    var doubleSided = Object(_mol_util__WEBPACK_IMPORTED_MODULE_1__[/* defaults */ "i"])(props.doubleSided, true);
    var volume = 0;
    if (quality === 'auto' && data instanceof _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"]) {
        quality = getStructureQuality(data.root);
        volume = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Box3D */ "b"].volume(data.boundary.box);
    }
    switch (quality) {
        case 'highest':
            detail = 3;
            radialSegments = 36;
            linearSegments = 18;
            resolution = Math.max(volume / 500000000, 0.1);
            doubleSided = true;
            break;
        case 'higher':
            detail = 3;
            radialSegments = 28;
            linearSegments = 14;
            resolution = Math.max(volume / 400000000, 0.3);
            doubleSided = true;
            break;
        case 'high':
            detail = 2;
            radialSegments = 20;
            linearSegments = 10;
            resolution = Math.max(volume / 300000000, 0.5);
            doubleSided = true;
            break;
        case 'medium':
            detail = 1;
            radialSegments = 12;
            linearSegments = 8;
            resolution = Math.max(volume / 200000000, 1);
            doubleSided = true;
            break;
        case 'low':
            detail = 0;
            radialSegments = 8;
            linearSegments = 3;
            resolution = Math.max(volume / 150000000, 2);
            doubleSided = false;
            break;
        case 'lower':
            detail = 0;
            radialSegments = 4;
            linearSegments = 2;
            resolution = Math.max(volume / 100000000, 4);
            doubleSided = false;
            break;
        case 'lowest':
            detail = 0;
            radialSegments = 2;
            linearSegments = 1;
            resolution = Math.max(volume / 75000000, 8);
            doubleSided = false;
            break;
        case 'custom':
            // use defaults or given props as set above
            break;
    }
    resolution = Math.min(resolution, 20);
    if (props.alpha !== undefined && props.alpha < 1) {
        doubleSided = false;
    }
    return {
        detail: detail,
        radialSegments: radialSegments,
        linearSegments: linearSegments,
        resolution: resolution,
        doubleSided: doubleSided
    };
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 165 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ Time; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ coordinates_Coordinates; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/coordinates/coordinates.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


//

function Time(value, unit) {
    return { value: value, unit: unit };
}
//

var coordinates_Coordinates;
(function (Coordinates) {
    function create(frames, deltaTime, timeOffset) {
        var hasCell = !!frames[0].cell;
        var hasVelocities = !!frames[0].velocities;
        var hasForces = !!frames[0].forces;
        return {
            id: mol_util["c" /* UUID */].create22(),
            frames: frames,
            hasCell: hasCell,
            hasVelocities: hasVelocities,
            hasForces: hasForces,
            deltaTime: deltaTime,
            timeOffset: timeOffset
        };
    }
    Coordinates.create = create;
    function getAtomicConformation(frame, atomId) {
        return {
            id: mol_util["c" /* UUID */].create22(),
            atomId: atomId,
            occupancy: db["Column"].ofConst(1, frame.elementCount, db["Column"].Schema.int),
            B_iso_or_equiv: db["Column"].ofConst(0, frame.elementCount, db["Column"].Schema.float),
            xyzDefined: true,
            x: frame.x,
            y: frame.y,
            z: frame.z,
        };
    }
    Coordinates.getAtomicConformation = getAtomicConformation;
    function reorderCoords(xs, index) {
        var ret = new Float32Array(xs.length);
        for (var i = 0, _i = xs.length; i < _i; i++) {
            ret[i] = xs[index[i]];
        }
        return ret;
    }
    function getAtomicConformationReordered(frame, atomId, srcIndex) {
        return {
            id: mol_util["c" /* UUID */].create22(),
            atomId: atomId,
            occupancy: db["Column"].ofConst(1, frame.elementCount, db["Column"].Schema.int),
            B_iso_or_equiv: db["Column"].ofConst(0, frame.elementCount, db["Column"].Schema.float),
            xyzDefined: true,
            x: reorderCoords(frame.x, srcIndex),
            y: reorderCoords(frame.y, srcIndex),
            z: reorderCoords(frame.z, srcIndex)
        };
    }
    Coordinates.getAtomicConformationReordered = getAtomicConformationReordered;
})(coordinates_Coordinates || (coordinates_Coordinates = {}));
//# sourceMappingURL=coordinates.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/coordinates.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

//# sourceMappingURL=coordinates.js.map

/***/ }),
/* 166 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* reexport */ context_QueryContext; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ Queries; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* reexport */ query_selection["a" /* StructureSelection */]; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* reexport */ query_StructureQuery; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-model/structure/query/queries/generators.js
var generators_namespaceObject = {};
__webpack_require__.r(generators_namespaceObject);
__webpack_require__.d(generators_namespaceObject, "none", function() { return none; });
__webpack_require__.d(generators_namespaceObject, "all", function() { return generators_all; });
__webpack_require__.d(generators_namespaceObject, "residues", function() { return residues; });
__webpack_require__.d(generators_namespaceObject, "chains", function() { return chains; });
__webpack_require__.d(generators_namespaceObject, "atoms", function() { return atoms; });
__webpack_require__.d(generators_namespaceObject, "rings", function() { return rings; });
__webpack_require__.d(generators_namespaceObject, "querySelection", function() { return querySelection; });
__webpack_require__.d(generators_namespaceObject, "bondedAtomicPairs", function() { return bondedAtomicPairs; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-model/structure/query/queries/modifiers.js
var modifiers_namespaceObject = {};
__webpack_require__.r(modifiers_namespaceObject);
__webpack_require__.d(modifiers_namespaceObject, "wholeResidues", function() { return modifiers_wholeResidues; });
__webpack_require__.d(modifiers_namespaceObject, "includeSurroundings", function() { return includeSurroundings; });
__webpack_require__.d(modifiers_namespaceObject, "querySelection", function() { return modifiers_querySelection; });
__webpack_require__.d(modifiers_namespaceObject, "intersectBy", function() { return intersectBy; });
__webpack_require__.d(modifiers_namespaceObject, "exceptBy", function() { return exceptBy; });
__webpack_require__.d(modifiers_namespaceObject, "union", function() { return union; });
__webpack_require__.d(modifiers_namespaceObject, "expandProperty", function() { return expandProperty; });
__webpack_require__.d(modifiers_namespaceObject, "includeConnected", function() { return includeConnected; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-model/structure/query/queries/filters.js
var filters_namespaceObject = {};
__webpack_require__.r(filters_namespaceObject);
__webpack_require__.d(filters_namespaceObject, "pick", function() { return pick; });
__webpack_require__.d(filters_namespaceObject, "first", function() { return first; });
__webpack_require__.d(filters_namespaceObject, "getCurrentStructureProperties", function() { return getCurrentStructureProperties; });
__webpack_require__.d(filters_namespaceObject, "withSameAtomProperties", function() { return withSameAtomProperties; });
__webpack_require__.d(filters_namespaceObject, "areIntersectedBy", function() { return areIntersectedBy; });
__webpack_require__.d(filters_namespaceObject, "within", function() { return within; });
__webpack_require__.d(filters_namespaceObject, "isConnectedTo", function() { return isConnectedTo; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-model/structure/query/queries/combinators.js
var combinators_namespaceObject = {};
__webpack_require__.r(combinators_namespaceObject);
__webpack_require__.d(combinators_namespaceObject, "merge", function() { return merge; });
__webpack_require__.d(combinators_namespaceObject, "intersect", function() { return intersect; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/selection.js
var query_selection = __webpack_require__(38);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js + 5 modules
var structure_structure = __webpack_require__(27);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/internal.js
var internal = __webpack_require__(268);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/context.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var context_QueryContext = /** @class */ (function () {
    function QueryContext(structure, options) {
        this.currentElementStack = [];
        this.currentAtomicBondStack = [];
        this.currentStructureStack = [];
        this.inputStructureStack = [];
        this.timeCreated = Object(now["b" /* now */])();
        /** Current element */
        this.element = structure_structure["d" /* StructureElement */].Location.create(void 0);
        this.currentStructure = void 0;
        /** Current bond between atoms */
        this.atomicBond = new context_QueryContextBondInfo();
        /** Supply this from the outside. Used by the internal.generator.current symbol */
        this.currentSelection = void 0;
        this.inputStructure = structure;
        this.timeoutMs = (options && options.timeoutMs) || 0;
        this.currentSelection = options && options.currentSelection;
    }
    QueryContext.prototype.pushCurrentElement = function () {
        this.currentElementStack[this.currentElementStack.length] = this.element;
        this.element = structure_structure["d" /* StructureElement */].Location.create(void 0);
        return this.element;
    };
    QueryContext.prototype.popCurrentElement = function () {
        this.element = this.currentElementStack.pop();
    };
    QueryContext.prototype.pushCurrentBond = function () {
        if (this.atomicBond)
            this.currentAtomicBondStack.push(this.atomicBond);
        this.atomicBond = new context_QueryContextBondInfo();
        return this.atomicBond;
    };
    QueryContext.prototype.popCurrentBond = function () {
        if (this.currentAtomicBondStack.length > 0) {
            this.atomicBond = this.currentAtomicBondStack.pop();
        }
        else {
            this.atomicBond = void 0;
        }
    };
    QueryContext.prototype.pushCurrentStructure = function () {
        if (this.currentStructure)
            this.currentStructureStack.push(this.currentStructure);
    };
    QueryContext.prototype.popCurrentStructure = function () {
        if (this.currentStructureStack.length)
            this.currentStructure = this.currentStructureStack.pop();
        else
            this.currentStructure = void 0;
    };
    QueryContext.prototype.pushInputStructure = function (structure) {
        this.inputStructureStack.push(this.inputStructure);
        this.inputStructure = structure;
    };
    QueryContext.prototype.popInputStructure = function () {
        if (this.inputStructureStack.length === 0)
            throw new Error('Must push before pop.');
        this.inputStructure = this.inputStructureStack.pop();
    };
    QueryContext.prototype.throwIfTimedOut = function () {
        if (this.timeoutMs === 0)
            return;
        if (Object(now["b" /* now */])() - this.timeCreated > this.timeoutMs) {
            throw new Error("The query took too long to execute (> " + this.timeoutMs / 1000 + "s).");
        }
    };
    QueryContext.prototype.tryGetCurrentSelection = function () {
        if (!this.currentSelection)
            throw new Error('The current selection is not assigned.');
        return this.currentSelection;
    };
    return QueryContext;
}());

var context_QueryContextBondInfo = /** @class */ (function () {
    function QueryContextBondInfo() {
        this.a = structure_structure["d" /* StructureElement */].Location.create(void 0);
        this.aIndex = 0;
        this.b = structure_structure["d" /* StructureElement */].Location.create(void 0);
        this.bIndex = 0;
        this.type = 0 /* None */;
        this.order = 0;
        this.testFn = internal["defaultBondTest"];
    }
    QueryContextBondInfo.prototype.setStructure = function (s) {
        this.a.structure = s;
        this.b.structure = s;
    };
    QueryContextBondInfo.prototype.setTestFn = function (fn) {
        this.testFn = fn || internal["defaultBondTest"];
    };
    QueryContextBondInfo.prototype.test = function (ctx, trySwap) {
        if (this.testFn(ctx))
            return true;
        if (trySwap) {
            this.swap();
            return this.testFn(ctx);
        }
        return false;
    };
    QueryContextBondInfo.prototype.swap = function () {
        // const sA = this.a.structure;
        // this.a.structure = this.b.structure;
        // this.b.structure = sA;
        var idxA = this.aIndex;
        this.aIndex = this.bIndex;
        this.bIndex = idxA;
        var unitA = this.a.unit;
        this.a.unit = this.b.unit;
        this.b.unit = unitA;
        var eA = this.a.element;
        this.a.element = this.b.element;
        this.b.element = eA;
    };
    Object.defineProperty(QueryContextBondInfo.prototype, "length", {
        get: function () {
            return structure_structure["d" /* StructureElement */].Location.distance(this.a, this.b);
        },
        enumerable: false,
        configurable: true
    });
    return QueryContextBondInfo;
}());
//# sourceMappingURL=context.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/query.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var query_StructureQuery;
(function (StructureQuery) {
    function run(query, structure, options) {
        return query(new context_QueryContext(structure, options));
    }
    StructureQuery.run = run;
})(query_StructureQuery || (query_StructureQuery = {}));

//# sourceMappingURL=query.js.map
// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/utils/structure-set.js
var structure_set = __webpack_require__(156);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/utils/builders.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var builders_UniqueStructuresBuilder = /** @class */ (function () {
    function UniqueStructuresBuilder(source) {
        this.source = source;
        this.set = Object(generic["a" /* HashSet */])(structure_structure["c" /* Structure */].hashCode, structure_structure["c" /* Structure */].areUnitAndIndicesEqual);
        this.structures = [];
        this.allSingletons = true;
    }
    UniqueStructuresBuilder.prototype.add = function (s) {
        if (!s.elementCount)
            return;
        if (s.elementCount !== 1)
            this.allSingletons = false;
        if (this.set.add(s)) {
            this.structures[this.structures.length] = s;
        }
    };
    UniqueStructuresBuilder.prototype.getSelection = function () {
        if (this.allSingletons)
            return query_selection["a" /* StructureSelection */].Singletons(this.source, Object(structure_set["e" /* structureUnion */])(this.source, this.structures));
        return query_selection["a" /* StructureSelection */].Sequence(this.source, this.structures);
    };
    return UniqueStructuresBuilder;
}());

var builders_LinearGroupingBuilder = /** @class */ (function () {
    function LinearGroupingBuilder(source) {
        this.source = source;
        this.builders = [];
        this.builderMap = new Map();
    }
    LinearGroupingBuilder.prototype.add = function (key, unit, element) {
        var b = this.builderMap.get(key);
        if (!b) {
            b = this.source.subsetBuilder(true);
            this.builders[this.builders.length] = b;
            this.builderMap.set(key, b);
        }
        b.addToUnit(unit, element);
    };
    LinearGroupingBuilder.prototype.allSingletons = function () {
        for (var i = 0, _i = this.builders.length; i < _i; i++) {
            if (this.builders[i].elementCount > 1)
                return false;
        }
        return true;
    };
    LinearGroupingBuilder.prototype.singletonSelection = function () {
        var builder = this.source.subsetBuilder(true);
        var loc = structure_structure["d" /* StructureElement */].Location.create(this.source);
        for (var i = 0, _i = this.builders.length; i < _i; i++) {
            this.builders[i].setSingletonLocation(loc);
            builder.addToUnit(loc.unit.id, loc.element);
        }
        return query_selection["a" /* StructureSelection */].Singletons(this.source, builder.getStructure());
    };
    LinearGroupingBuilder.prototype.fullSelection = function () {
        var structures = new Array(this.builders.length);
        for (var i = 0, _i = this.builders.length; i < _i; i++) {
            structures[i] = this.builders[i].getStructure();
        }
        return query_selection["a" /* StructureSelection */].Sequence(this.source, structures);
    };
    LinearGroupingBuilder.prototype.getSelection = function () {
        var len = this.builders.length;
        if (len === 0)
            return query_selection["a" /* StructureSelection */].Empty(this.source);
        if (this.allSingletons())
            return this.singletonSelection();
        return this.fullSelection();
    };
    return LinearGroupingBuilder;
}());

//# sourceMappingURL=builders.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/structure.js + 6 modules
var structure_structure_structure = __webpack_require__(112);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/generators.js
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var none = function (ctx) { return query_selection["a" /* StructureSelection */].Sequence(ctx.inputStructure, []); };
var generators_all = function (ctx) { return query_selection["a" /* StructureSelection */].Singletons(ctx.inputStructure, ctx.inputStructure); };
function residues(params) { return atoms(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { groupBy: function (ctx) { return structure_structure["e" /* StructureProperties */].residue.key(ctx.element); } })); }
function chains(params) { return atoms(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { groupBy: function (ctx) { return structure_structure["e" /* StructureProperties */].chain.key(ctx.element); } })); }
function _true(ctx) { return true; }
function _zero(ctx) { return 0; }
function atoms(params) {
    if (!params || (!params.atomTest && !params.residueTest && !params.chainTest && !params.entityTest && !params.unitTest && !params.groupBy))
        return generators_all;
    if (!!params.atomTest && !params.residueTest && !params.chainTest && !params.entityTest && !params.unitTest && !params.groupBy)
        return atomGroupsLinear(params.atomTest);
    var normalized = {
        unitTest: params.unitTest || _true,
        entityTest: params.entityTest || _true,
        chainTest: params.chainTest || _true,
        residueTest: params.residueTest || _true,
        atomTest: params.atomTest || _true,
        groupBy: params.groupBy || _zero,
    };
    if (!params.groupBy)
        return atomGroupsSegmented(normalized);
    return atomGroupsGrouped(normalized);
}
function atomGroupsLinear(atomTest) {
    return function query_atomGroupsLinear(ctx) {
        var inputStructure = ctx.inputStructure;
        var units = inputStructure.units;
        var l = ctx.pushCurrentElement();
        var builder = inputStructure.subsetBuilder(true);
        l.structure = inputStructure;
        for (var _a = 0, units_1 = units; _a < units_1.length; _a++) {
            var unit = units_1[_a];
            l.unit = unit;
            var elements = unit.elements;
            builder.beginUnit(unit.id);
            for (var j = 0, _j = elements.length; j < _j; j++) {
                l.element = elements[j];
                if (atomTest(ctx))
                    builder.addElement(l.element);
            }
            builder.commitUnit();
            ctx.throwIfTimedOut();
        }
        ctx.popCurrentElement();
        return query_selection["a" /* StructureSelection */].Singletons(inputStructure, builder.getStructure());
    };
}
function atomGroupsSegmented(_a) {
    var unitTest = _a.unitTest, entityTest = _a.entityTest, chainTest = _a.chainTest, residueTest = _a.residueTest, atomTest = _a.atomTest;
    return function query_atomGroupsSegmented(ctx) {
        var inputStructure = ctx.inputStructure;
        var units = inputStructure.units;
        var l = ctx.pushCurrentElement();
        var builder = inputStructure.subsetBuilder(true);
        l.structure = inputStructure;
        for (var _a = 0, units_2 = units; _a < units_2.length; _a++) {
            var unit = units_2[_a];
            l.unit = unit;
            if (!unitTest(ctx))
                continue;
            var elements = unit.elements, model = unit.model;
            builder.beginUnit(unit.id);
            if (unit.kind === 0 /* Atomic */) {
                var chainsIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements);
                var residuesIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements);
                while (chainsIt.hasNext) {
                    var chainSegment = chainsIt.move();
                    l.element = elements[chainSegment.start];
                    // test entity and chain
                    if (!entityTest(ctx) || !chainTest(ctx))
                        continue;
                    residuesIt.setSegment(chainSegment);
                    while (residuesIt.hasNext) {
                        var residueSegment = residuesIt.move();
                        l.element = elements[residueSegment.start];
                        // test residue
                        if (!residueTest(ctx))
                            continue;
                        for (var j = residueSegment.start, _j = residueSegment.end; j < _j; j++) {
                            l.element = elements[j];
                            // test atom
                            if (atomTest(ctx)) {
                                builder.addElement(l.element);
                            }
                        }
                    }
                }
            }
            else {
                var chainElementSegments = (1 /* Spheres */ ? model.coarseHierarchy.spheres : undefined).chainElementSegments;
                var chainsIt = mol_data_int["Segmentation"].transientSegments(chainElementSegments, elements);
                while (chainsIt.hasNext) {
                    var chainSegment = chainsIt.move();
                    l.element = elements[chainSegment.start];
                    // test entity and chain
                    if (!entityTest(ctx) || !chainTest(ctx))
                        continue;
                    for (var j = chainSegment.start, _j = chainSegment.end; j < _j; j++) {
                        l.element = elements[j];
                        // test residue/coarse element
                        if (residueTest(ctx)) {
                            builder.addElement(l.element);
                        }
                    }
                }
            }
            builder.commitUnit();
            ctx.throwIfTimedOut();
        }
        ctx.popCurrentElement();
        return query_selection["a" /* StructureSelection */].Singletons(inputStructure, builder.getStructure());
    };
}
function atomGroupsGrouped(_a) {
    var unitTest = _a.unitTest, entityTest = _a.entityTest, chainTest = _a.chainTest, residueTest = _a.residueTest, atomTest = _a.atomTest, groupBy = _a.groupBy;
    return function query_atomGroupsGrouped(ctx) {
        var inputStructure = ctx.inputStructure;
        var units = inputStructure.units;
        var l = ctx.pushCurrentElement();
        var builder = new builders_LinearGroupingBuilder(inputStructure);
        l.structure = inputStructure;
        for (var _a = 0, units_3 = units; _a < units_3.length; _a++) {
            var unit = units_3[_a];
            l.unit = unit;
            if (!unitTest(ctx))
                continue;
            var elements = unit.elements, model = unit.model;
            if (unit.kind === 0 /* Atomic */) {
                var chainsIt = mol_data_int["Segmentation"].transientSegments(model.atomicHierarchy.chainAtomSegments, elements);
                var residuesIt = mol_data_int["Segmentation"].transientSegments(model.atomicHierarchy.residueAtomSegments, elements);
                while (chainsIt.hasNext) {
                    var chainSegment = chainsIt.move();
                    l.element = elements[chainSegment.start];
                    // test entity and chain
                    if (!entityTest(ctx) || !chainTest(ctx))
                        continue;
                    residuesIt.setSegment(chainSegment);
                    while (residuesIt.hasNext) {
                        var residueSegment = residuesIt.move();
                        l.element = elements[residueSegment.start];
                        // test residue
                        if (!residueTest(ctx))
                            continue;
                        for (var j = residueSegment.start, _j = residueSegment.end; j < _j; j++) {
                            l.element = elements[j];
                            // test atom
                            if (atomTest(ctx)) {
                                builder.add(groupBy(ctx), unit.id, l.element);
                            }
                        }
                    }
                }
            }
            else {
                var chainElementSegments = (1 /* Spheres */ ? model.coarseHierarchy.spheres : undefined).chainElementSegments;
                var chainsIt = mol_data_int["Segmentation"].transientSegments(chainElementSegments, elements);
                while (chainsIt.hasNext) {
                    var chainSegment = chainsIt.move();
                    l.element = elements[chainSegment.start];
                    // test entity and chain
                    if (!entityTest(ctx) || !chainTest(ctx))
                        continue;
                    for (var j = chainSegment.start, _j = chainSegment.end; j < _j; j++) {
                        l.element = elements[j];
                        // test residue/coarse element
                        if (residueTest(ctx)) {
                            builder.add(groupBy(ctx), unit.id, l.element);
                        }
                    }
                }
            }
            ctx.throwIfTimedOut();
        }
        ctx.popCurrentElement();
        return builder.getSelection();
    };
}
function getRingStructure(unit, ring, inputStructure) {
    var elements = new Int32Array(ring.length);
    for (var i = 0, _i = ring.length; i < _i; i++)
        elements[i] = unit.elements[ring[i]];
    return structure_structure_structure["a" /* default */].create([unit.getChild(mol_data_int["SortedArray"].ofSortedArray(elements))], { parent: inputStructure });
}
function rings(fingerprints, onlyAromatic) {
    return function query_rings(ctx) {
        var units = ctx.inputStructure.units;
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        if (!fingerprints || fingerprints.length === 0) {
            for (var _a = 0, units_4 = units; _a < units_4.length; _a++) {
                var u = units_4[_a];
                if (!structure_structure["g" /* Unit */].isAtomic(u))
                    continue;
                if (onlyAromatic) {
                    for (var _b = 0, _c = u.rings.aromaticRings; _b < _c.length; _b++) {
                        var r = _c[_b];
                        ret.add(getRingStructure(u, u.rings.all[r], ctx.inputStructure));
                    }
                }
                else {
                    for (var _d = 0, _e = u.rings.all; _d < _e.length; _d++) {
                        var r = _e[_d];
                        ret.add(getRingStructure(u, r, ctx.inputStructure));
                    }
                }
            }
        }
        else {
            var uniqueFps = generic["c" /* UniqueArray */].create();
            for (var i = 0; i < fingerprints.length; i++)
                generic["c" /* UniqueArray */].add(uniqueFps, fingerprints[i], fingerprints[i]);
            for (var _f = 0, units_5 = units; _f < units_5.length; _f++) {
                var u = units_5[_f];
                if (!structure_structure["g" /* Unit */].isAtomic(u))
                    continue;
                var rings_1 = u.rings;
                for (var _g = 0, _h = uniqueFps.array; _g < _h.length; _g++) {
                    var fp = _h[_g];
                    if (!rings_1.byFingerprint.has(fp))
                        continue;
                    for (var _k = 0, _l = rings_1.byFingerprint.get(fp); _k < _l.length; _k++) {
                        var r = _l[_k];
                        if (onlyAromatic && !rings_1.aromaticRings.includes(r))
                            continue;
                        ret.add(getRingStructure(u, rings_1.all[r], ctx.inputStructure));
                    }
                }
            }
        }
        return ret.getSelection();
    };
}
function querySelection(selection, query, inComplement) {
    if (inComplement === void 0) { inComplement = false; }
    return function query_querySelection(ctx) {
        var targetSel = selection(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(targetSel) === 0)
            return targetSel;
        var target = inComplement
            ? Object(structure_set["d" /* structureSubtract */])(ctx.inputStructure, query_selection["a" /* StructureSelection */].unionStructure(targetSel))
            : query_selection["a" /* StructureSelection */].unionStructure(targetSel);
        if (target.elementCount === 0)
            return query_selection["a" /* StructureSelection */].Empty(ctx.inputStructure);
        ctx.throwIfTimedOut();
        ctx.pushInputStructure(target);
        var result = query(ctx);
        ctx.popInputStructure();
        return query_selection["a" /* StructureSelection */].withInputStructure(result, ctx.inputStructure);
    };
}
function bondedAtomicPairs(bondTest) {
    return function query_bondedAtomicPairs(ctx) {
        var structure = ctx.inputStructure;
        var interBonds = structure.interUnitBonds;
        // Note: each bond is called twice, that's why we need the unique builder.
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        ctx.pushCurrentBond();
        var atomicBond = ctx.atomicBond;
        atomicBond.setTestFn(bondTest);
        atomicBond.setStructure(structure);
        // Process intra unit bonds
        for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
            var unit = _b[_a];
            if (unit.kind !== 0 /* Atomic */)
                continue;
            var _c = unit.bonds, intraBondOffset = _c.offset, intraBondB = _c.b, _d = _c.edgeProps, flags = _d.flags, order = _d.order;
            atomicBond.a.unit = unit;
            atomicBond.b.unit = unit;
            for (var i = 0, _i = unit.elements.length; i < _i; i++) {
                atomicBond.aIndex = i;
                atomicBond.a.element = unit.elements[i];
                // check intra unit bonds
                for (var lI = intraBondOffset[i], _lI = intraBondOffset[i + 1]; lI < _lI; lI++) {
                    atomicBond.bIndex = intraBondB[lI];
                    atomicBond.b.element = unit.elements[intraBondB[lI]];
                    atomicBond.type = flags[lI];
                    atomicBond.order = order[lI];
                    // No need to "swap test" because each bond direction will be visited eventually.
                    if (atomicBond.test(ctx, false)) {
                        var b = structure.subsetBuilder(false);
                        b.beginUnit(unit.id);
                        b.addElement(atomicBond.a.element);
                        b.addElement(atomicBond.b.element);
                        b.commitUnit();
                        ret.add(b.getStructure());
                    }
                }
            }
        }
        // Process inter unit bonds
        for (var _e = 0, _f = interBonds.edges; _e < _f.length; _e++) {
            var bond = _f[_e];
            atomicBond.a.unit = bond.unitA;
            atomicBond.a.element = bond.unitA.elements[bond.indexA];
            atomicBond.aIndex = bond.indexA;
            atomicBond.b.unit = bond.unitB;
            atomicBond.b.element = bond.unitB.elements[bond.indexB];
            atomicBond.bIndex = bond.indexB;
            atomicBond.order = bond.props.order;
            atomicBond.type = bond.props.flag;
            // No need to "swap test" because each bond direction will be visited eventually.
            if (atomicBond.test(ctx, false)) {
                var b = structure.subsetBuilder(false);
                b.addToUnit(atomicBond.a.unit.id, atomicBond.a.element);
                b.addToUnit(atomicBond.b.unit.id, atomicBond.b.element);
                ret.add(b.getStructure());
            }
        }
        ctx.popCurrentBond();
        return ret.getSelection();
    };
}
//# sourceMappingURL=generators.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/symmetry.js
var symmetry = __webpack_require__(239);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/unique-subset-builder.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var unique_subset_builder_StructureUniqueSubsetBuilder = /** @class */ (function () {
    function StructureUniqueSubsetBuilder(parent) {
        this.parent = parent;
        this.ids = [];
        this.unitMap = mol_data_int["IntMap"].Mutable();
        this.parentId = -1;
        this.currentUnit = generic["c" /* UniqueArray */].create();
        this.elementCount = 0;
    }
    StructureUniqueSubsetBuilder.prototype.addToUnit = function (parentId, e) {
        var unit = this.unitMap.get(parentId);
        if (!!unit) {
            if (generic["c" /* UniqueArray */].add(unit, e, e))
                this.elementCount++;
        }
        else {
            var arr = generic["c" /* UniqueArray */].create();
            generic["c" /* UniqueArray */].add(arr, e, e);
            this.unitMap.set(parentId, arr);
            this.ids[this.ids.length] = parentId;
            this.elementCount++;
        }
    };
    StructureUniqueSubsetBuilder.prototype.has = function (parentId, e) {
        var unit = this.unitMap.get(parentId);
        if (!unit)
            return false;
        return generic["c" /* UniqueArray */].has(unit, e);
    };
    StructureUniqueSubsetBuilder.prototype.beginUnit = function (parentId) {
        this.parentId = parentId;
        if (this.unitMap.has(parentId)) {
            this.currentUnit = this.unitMap.get(parentId);
        }
        else {
            this.currentUnit = this.currentUnit.array.length > 0 ? generic["c" /* UniqueArray */].create() : this.currentUnit;
        }
    };
    StructureUniqueSubsetBuilder.prototype.addElement = function (e) {
        if (generic["c" /* UniqueArray */].add(this.currentUnit, e, e))
            this.elementCount++;
    };
    StructureUniqueSubsetBuilder.prototype.commitUnit = function () {
        if (this.currentUnit.array.length === 0 || this.unitMap.has(this.parentId))
            return;
        this.ids[this.ids.length] = this.parentId;
        this.unitMap.set(this.parentId, this.currentUnit);
        this.parentId = -1;
    };
    StructureUniqueSubsetBuilder.prototype.getStructure = function () {
        if (this.isEmpty)
            return structure_structure_structure["a" /* default */].Empty;
        var newUnits = [];
        Object(util["q" /* sortArray */])(this.ids);
        var symmGroups = symmetry["a" /* default */].UnitEquivalenceBuilder();
        for (var i = 0, _i = this.ids.length; i < _i; i++) {
            var id = this.ids[i];
            var parent_1 = this.parent.unitMap.get(id);
            var unit = this.unitMap.get(id).array;
            var l = unit.length;
            // if the length is the same, just copy the old unit.
            if (unit.length === parent_1.elements.length) {
                newUnits[newUnits.length] = parent_1;
                symmGroups.add(parent_1.id, parent_1);
                continue;
            }
            if (l > 1)
                Object(util["q" /* sortArray */])(unit);
            var child = parent_1.getChild(mol_data_int["SortedArray"].ofSortedArray(unit));
            var pivot = symmGroups.add(child.id, child);
            if (child !== pivot)
                child = pivot.applyOperator(child.id, child.conformation.operator, true);
            newUnits[newUnits.length] = child;
        }
        return structure_structure_structure["a" /* default */].create(newUnits, { parent: this.parent });
    };
    Object.defineProperty(StructureUniqueSubsetBuilder.prototype, "isEmpty", {
        get: function () {
            return this.elementCount === 0;
        },
        enumerable: false,
        configurable: true
    });
    return StructureUniqueSubsetBuilder;
}());

//# sourceMappingURL=unique-subset-builder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/modifiers.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







function getWholeResidues(ctx, source, structure) {
    var builder = source.subsetBuilder(true);
    for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        if (unit.kind !== 0 /* Atomic */) {
            // just copy non-atomic units.
            builder.setUnit(unit.id, unit.elements);
            continue;
        }
        var residueAtomSegments = unit.model.atomicHierarchy.residueAtomSegments;
        var elements = unit.elements;
        builder.beginUnit(unit.id);
        var residuesIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
        while (residuesIt.hasNext) {
            var rI = residuesIt.move().index;
            for (var j = residueAtomSegments.offsets[rI], _j = residueAtomSegments.offsets[rI + 1]; j < _j; j++) {
                builder.addElement(j);
            }
        }
        builder.commitUnit();
        ctx.throwIfTimedOut();
    }
    return builder.getStructure();
}
function modifiers_wholeResidues(query) {
    return function query_wholeResidues(ctx) {
        var inner = query(ctx);
        if (query_selection["a" /* StructureSelection */].isSingleton(inner)) {
            return query_selection["a" /* StructureSelection */].Singletons(ctx.inputStructure, getWholeResidues(ctx, ctx.inputStructure, inner.structure));
        }
        else {
            var builder = new builders_UniqueStructuresBuilder(ctx.inputStructure);
            for (var _a = 0, _b = inner.structures; _a < _b.length; _a++) {
                var s = _b[_a];
                builder.add(getWholeResidues(ctx, ctx.inputStructure, s));
            }
            return builder.getSelection();
        }
    };
}
function getIncludeSurroundings(ctx, source, structure, params) {
    var builder = new unique_subset_builder_StructureUniqueSubsetBuilder(source);
    var lookup = source.lookup3d;
    var r = params.radius;
    for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        var _c = unit.conformation, x = _c.x, y = _c.y, z = _c.z;
        var elements = unit.elements;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            lookup.findIntoBuilder(x(e), y(e), z(e), r, builder);
        }
        ctx.throwIfTimedOut();
    }
    return !!params.wholeResidues ? getWholeResidues(ctx, source, builder.getStructure()) : builder.getStructure();
}
function getIncludeSurroundingsWithRadius(ctx, source, structure, params) {
    var builder = new unique_subset_builder_StructureUniqueSubsetBuilder(source);
    var lookup = source.lookup3d;
    var elementRadius = params.elementRadius, elementRadiusClosure = params.elementRadiusClosure, sourceMaxRadius = params.sourceMaxRadius, radius = params.radius;
    ctx.pushCurrentElement();
    ctx.element.structure = structure;
    for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        ctx.element.unit = unit;
        var _c = unit.conformation, x = _c.x, y = _c.y, z = _c.z;
        var elements = unit.elements;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            ctx.element.element = e;
            var eRadius = elementRadius(ctx);
            lookup.findIntoBuilderWithRadius(x(e), y(e), z(e), eRadius, sourceMaxRadius, radius, elementRadiusClosure, builder);
        }
        ctx.throwIfTimedOut();
    }
    ctx.popCurrentElement();
    return !!params.wholeResidues ? getWholeResidues(ctx, source, builder.getStructure()) : builder.getStructure();
}
function createElementRadiusFn(ctx, eRadius) {
    return function (e) {
        ctx.element.structure = e.structure;
        ctx.element.unit = e.unit;
        ctx.element.element = e.element;
        return eRadius(ctx);
    };
}
function findStructureRadius(ctx, eRadius) {
    var r = 0;
    ctx.element.structure = ctx.inputStructure;
    for (var _a = 0, _b = ctx.inputStructure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        ctx.element.unit = unit;
        var elements = unit.elements;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            ctx.element.element = e;
            var eR = eRadius(ctx);
            if (eR > r)
                r = eR;
        }
    }
    ctx.throwIfTimedOut();
    return r;
}
function includeSurroundings(query, params) {
    return function query_includeSurroundings(ctx) {
        var inner = query(ctx);
        if (params.elementRadius) {
            var prms = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { elementRadius: params.elementRadius, elementRadiusClosure: createElementRadiusFn(ctx, params.elementRadius), sourceMaxRadius: findStructureRadius(ctx, params.elementRadius) });
            if (query_selection["a" /* StructureSelection */].isSingleton(inner)) {
                var surr = getIncludeSurroundingsWithRadius(ctx, ctx.inputStructure, inner.structure, prms);
                var ret = query_selection["a" /* StructureSelection */].Singletons(ctx.inputStructure, surr);
                return ret;
            }
            else {
                var builder = new builders_UniqueStructuresBuilder(ctx.inputStructure);
                for (var _a = 0, _b = inner.structures; _a < _b.length; _a++) {
                    var s = _b[_a];
                    builder.add(getIncludeSurroundingsWithRadius(ctx, ctx.inputStructure, s, prms));
                }
                return builder.getSelection();
            }
        }
        if (query_selection["a" /* StructureSelection */].isSingleton(inner)) {
            var surr = getIncludeSurroundings(ctx, ctx.inputStructure, inner.structure, params);
            var ret = query_selection["a" /* StructureSelection */].Singletons(ctx.inputStructure, surr);
            return ret;
        }
        else {
            var builder = new builders_UniqueStructuresBuilder(ctx.inputStructure);
            for (var _c = 0, _d = inner.structures; _c < _d.length; _c++) {
                var s = _d[_c];
                builder.add(getIncludeSurroundings(ctx, ctx.inputStructure, s, params));
            }
            return builder.getSelection();
        }
    };
}
function modifiers_querySelection(selection, query) {
    return function query_querySelection(ctx) {
        var targetSel = selection(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(targetSel) === 0)
            return targetSel;
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        var add = function (s) { return ret.add(s); };
        query_selection["a" /* StructureSelection */].forEach(targetSel, function (s, sI) {
            ctx.pushInputStructure(s);
            query_selection["a" /* StructureSelection */].forEach(query(ctx), add);
            ctx.popInputStructure();
            if (sI % 10 === 0)
                ctx.throwIfTimedOut();
        });
        return ret.getSelection();
    };
}
function intersectBy(query, by) {
    return function query_intersectBy(ctx) {
        var selection = query(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(selection) === 0)
            return selection;
        var bySel = by(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(bySel) === 0)
            return query_selection["a" /* StructureSelection */].Empty(ctx.inputStructure);
        var unionBy = query_selection["a" /* StructureSelection */].unionStructure(bySel);
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
            var ii = Object(structure_set["c" /* structureIntersect */])(unionBy, s);
            if (ii.elementCount !== 0)
                ret.add(ii);
            if (sI % 50 === 0)
                ctx.throwIfTimedOut();
        });
        return ret.getSelection();
    };
}
function exceptBy(query, by) {
    return function query_exceptBy(ctx) {
        var selection = query(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(selection) === 0)
            return selection;
        var bySel = by(ctx);
        if (query_selection["a" /* StructureSelection */].structureCount(bySel) === 0)
            return selection;
        var subtractBy = query_selection["a" /* StructureSelection */].unionStructure(bySel);
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
            var diff = Object(structure_set["d" /* structureSubtract */])(s, subtractBy);
            if (diff.elementCount !== 0)
                ret.add(diff);
            if (sI % 50 === 0)
                ctx.throwIfTimedOut();
        });
        return ret.getSelection();
    };
}
function union(query) {
    return function query_union(ctx) {
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        ret.add(query_selection["a" /* StructureSelection */].unionStructure(query(ctx)));
        return ret.getSelection();
    };
}
function expandProperty(query, property) {
    return function query_expandProperty(ctx) {
        var src = query(ctx);
        var propertyToStructureIndexMap = new Map();
        var builders = [];
        ctx.pushCurrentElement();
        query_selection["a" /* StructureSelection */].forEach(src, function (s, sI) {
            ctx.element.structure = s;
            for (var _a = 0, _b = s.units; _a < _b.length; _a++) {
                var unit = _b[_a];
                ctx.element.unit = unit;
                var elements = unit.elements;
                for (var i = 0, _i = elements.length; i < _i; i++) {
                    ctx.element.element = elements[i];
                    var p = property(ctx);
                    var arr = void 0;
                    if (propertyToStructureIndexMap.has(p))
                        arr = propertyToStructureIndexMap.get(p);
                    else {
                        arr = generic["c" /* UniqueArray */].create();
                        propertyToStructureIndexMap.set(p, arr);
                    }
                    generic["c" /* UniqueArray */].add(arr, sI, sI);
                }
            }
            builders[sI] = ctx.inputStructure.subsetBuilder(true);
            if (sI % 10 === 0)
                ctx.throwIfTimedOut();
        });
        ctx.element.structure = ctx.inputStructure;
        for (var _a = 0, _b = ctx.inputStructure.units; _a < _b.length; _a++) {
            var unit = _b[_a];
            ctx.element.unit = unit;
            var elements = unit.elements;
            for (var i = 0, _i = elements.length; i < _i; i++) {
                ctx.element.element = elements[i];
                var p = property(ctx);
                if (!propertyToStructureIndexMap.has(p))
                    continue;
                var indices = propertyToStructureIndexMap.get(p).array;
                for (var _sI = 0, __sI = indices.length; _sI < __sI; _sI++) {
                    builders[indices[_sI]].addToUnit(unit.id, elements[i]);
                }
            }
        }
        ctx.popCurrentElement();
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        for (var _c = 0, builders_1 = builders; _c < builders_1.length; _c++) {
            var b = builders_1[_c];
            ret.add(b.getStructure());
        }
        return ret.getSelection();
    };
}
function includeConnected(_a) {
    var query = _a.query, layerCount = _a.layerCount, wholeResidues = _a.wholeResidues, bondTest = _a.bondTest;
    var lc = Math.max(layerCount, 0);
    return function query_includeConnected(ctx) {
        var builder = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        var src = query(ctx);
        ctx.pushCurrentBond();
        ctx.atomicBond.setTestFn(bondTest);
        query_selection["a" /* StructureSelection */].forEach(src, function (s, sI) {
            var incl = s;
            for (var i = 0; i < lc; i++) {
                incl = includeConnectedStep(ctx, wholeResidues, incl);
            }
            builder.add(incl);
            if (sI % 10 === 0)
                ctx.throwIfTimedOut();
        });
        ctx.popCurrentBond();
        return builder.getSelection();
    };
}
function includeConnectedStep(ctx, wholeResidues, structure) {
    var expanded = expandConnected(ctx, structure);
    if (wholeResidues)
        return getWholeResidues(ctx, ctx.inputStructure, expanded);
    return expanded;
}
function expandConnected(ctx, structure) {
    var inputStructure = ctx.inputStructure;
    var interBonds = inputStructure.interUnitBonds;
    var builder = new unique_subset_builder_StructureUniqueSubsetBuilder(inputStructure);
    var atomicBond = ctx.atomicBond;
    // Process intra unit bonds
    for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        if (unit.kind !== 0 /* Atomic */) {
            // add the whole unit
            builder.beginUnit(unit.id);
            for (var i = 0, _i = unit.elements.length; i < _i; i++) {
                builder.addElement(unit.elements[i]);
            }
            builder.commitUnit();
            continue;
        }
        var inputUnitA = inputStructure.unitMap.get(unit.id);
        var _c = inputUnitA.bonds, intraBondOffset = _c.offset, intraBondB = _c.b, _d = _c.edgeProps, flags = _d.flags, order = _d.order;
        atomicBond.setStructure(inputStructure);
        // Process intra unit bonds
        atomicBond.a.unit = inputUnitA;
        atomicBond.b.unit = inputUnitA;
        for (var i = 0, _i = unit.elements.length; i < _i; i++) {
            // add the current element
            builder.addToUnit(unit.id, unit.elements[i]);
            var aIndex = mol_data_int["SortedArray"].indexOf(inputUnitA.elements, unit.elements[i]);
            // check intra unit bonds
            for (var lI = intraBondOffset[aIndex], _lI = intraBondOffset[aIndex + 1]; lI < _lI; lI++) {
                var bIndex = intraBondB[lI];
                var bElement = inputUnitA.elements[bIndex];
                // Check if the element is already present:
                if (mol_data_int["SortedArray"].has(unit.elements, bElement) || builder.has(unit.id, bElement))
                    continue;
                atomicBond.aIndex = aIndex;
                atomicBond.a.element = unit.elements[i];
                atomicBond.bIndex = bIndex;
                atomicBond.b.element = bElement;
                atomicBond.type = flags[lI];
                atomicBond.order = order[lI];
                if (atomicBond.test(ctx, true)) {
                    builder.addToUnit(unit.id, bElement);
                }
            }
        }
        // Process inter unit bonds
        for (var _e = 0, _f = interBonds.getConnectedUnits(inputUnitA); _e < _f.length; _e++) {
            var bondedUnit = _f[_e];
            var currentUnitB = structure.unitMap.get(bondedUnit.unitB.id);
            for (var _g = 0, _h = bondedUnit.connectedIndices; _g < _h.length; _g++) {
                var aI = _h[_g];
                // check if the element is in the expanded structure
                if (!mol_data_int["SortedArray"].has(unit.elements, inputUnitA.elements[aI]))
                    continue;
                for (var _k = 0, _l = bondedUnit.getEdges(aI); _k < _l.length; _k++) {
                    var bond = _l[_k];
                    var bElement = bondedUnit.unitB.elements[bond.indexB];
                    // Check if the element is already present:
                    if ((currentUnitB && mol_data_int["SortedArray"].has(currentUnitB.elements, bElement)) || builder.has(bondedUnit.unitB.id, bElement))
                        continue;
                    atomicBond.a.unit = inputUnitA;
                    atomicBond.aIndex = aI;
                    atomicBond.a.element = inputUnitA.elements[aI];
                    atomicBond.b.unit = bondedUnit.unitB;
                    atomicBond.bIndex = bond.indexB;
                    atomicBond.b.element = bElement;
                    atomicBond.type = bond.props.flag;
                    atomicBond.order = bond.props.order;
                    if (atomicBond.test(ctx, true)) {
                        builder.addToUnit(bondedUnit.unitB.id, bElement);
                    }
                }
            }
        }
    }
    return builder.getStructure();
}
// TODO: unionBy (skip this one?), cluster
//# sourceMappingURL=modifiers.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var mol_util_set = __webpack_require__(90);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/utils/structure-distance.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function checkStructureMinMaxDistance(ctx, a, b, minDist, maxDist, elementRadius) {
    if (a.elementCount === 0 || b.elementCount === 0)
        return true;
    if (a.elementCount <= b.elementCount)
        return structure_distance_MinMaxDist.check(ctx, a, b, minDist, maxDist, elementRadius);
    return structure_distance_MinMaxDist.check(ctx, b, a, minDist, maxDist, elementRadius);
}
function checkStructureMaxRadiusDistance(ctx, a, b, maxDist, elementRadius) {
    if (a.elementCount === 0 || b.elementCount === 0)
        return true;
    if (a.elementCount <= b.elementCount)
        return structure_distance_MaxRadiusDist.check(ctx, a, b, maxDist, elementRadius);
    return structure_distance_MaxRadiusDist.check(ctx, b, a, maxDist, elementRadius);
}
var structure_distance_MinMaxDist;
(function (MinMaxDist) {
    var distVec = linear_algebra["Vec3"].zero();
    function inUnit(ctx, unit, p, eRadius, minDist, maxDist, elementRadius) {
        var elements = unit.elements, position = unit.conformation.position, dV = distVec;
        ctx.element.unit = unit;
        var withinRange = false;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            ctx.element.element = e;
            var d = Math.max(0, linear_algebra["Vec3"].distance(p, position(e, dV)) - eRadius - elementRadius(ctx));
            if (d < minDist)
                return 0 /* BelowMin */;
            if (d < maxDist)
                withinRange = true;
        }
        return withinRange ? 1 /* WithinMax */ : 2 /* Miss */;
    }
    function toPoint(ctx, s, point, radius, minDist, maxDist, elementRadius) {
        var units = s.units;
        var withinRange = false;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var iu = inUnit(ctx, units[i], point, radius, minDist, maxDist, elementRadius);
            if (iu === 0 /* BelowMin */)
                return 0 /* BelowMin */;
            if (iu === 1 /* WithinMax */)
                withinRange = true;
        }
        return withinRange ? 1 /* WithinMax */ : 2 /* Miss */;
    }
    MinMaxDist.toPoint = toPoint;
    var distPivot = linear_algebra["Vec3"].zero();
    function check(ctx, a, b, minDist, maxDist, elementRadius) {
        if (a.elementCount === 0 || b.elementCount === 0)
            return 0;
        var units = a.units;
        var withinRange = false;
        ctx.element.structure = a;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var unit = units[i];
            var elements = unit.elements, position = unit.conformation.position;
            ctx.element.unit = unit;
            for (var i_1 = 0, _i_1 = elements.length; i_1 < _i_1; i_1++) {
                var e = elements[i_1];
                ctx.element.element = e;
                var tp = toPoint(ctx, b, position(e, distPivot), elementRadius(ctx), minDist, maxDist, elementRadius);
                if (tp === 0 /* BelowMin */)
                    return 0 /* BelowMin */;
                if (tp === 1 /* WithinMax */)
                    withinRange = true;
            }
        }
        return withinRange;
    }
    MinMaxDist.check = check;
})(structure_distance_MinMaxDist || (structure_distance_MinMaxDist = {}));
var structure_distance_MaxRadiusDist;
(function (MaxRadiusDist) {
    var distVec = linear_algebra["Vec3"].zero();
    function inUnit(ctx, unit, p, eRadius, maxDist, elementRadius) {
        var elements = unit.elements, position = unit.conformation.position, dV = distVec;
        ctx.element.unit = unit;
        for (var i = 0, _i = elements.length; i < _i; i++) {
            var e = elements[i];
            ctx.element.element = e;
            if (Math.max(0, linear_algebra["Vec3"].distance(p, position(e, dV)) - eRadius - elementRadius(ctx)) <= maxDist)
                return true;
        }
        return false;
    }
    function toPoint(ctx, s, point, radius, maxDist, elementRadius) {
        var units = s.units;
        for (var i = 0, _i = units.length; i < _i; i++) {
            if (inUnit(ctx, units[i], point, radius, maxDist, elementRadius))
                return true;
        }
        return false;
    }
    MaxRadiusDist.toPoint = toPoint;
    var distPivot = linear_algebra["Vec3"].zero();
    function check(ctx, a, b, maxDist, elementRadius) {
        if (a.elementCount === 0 || b.elementCount === 0)
            return 0;
        var units = a.units;
        ctx.element.structure = a;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var unit = units[i];
            ctx.element.unit = unit;
            var elements = unit.elements, position = unit.conformation.position;
            for (var i_2 = 0, _i_2 = elements.length; i_2 < _i_2; i_2++) {
                var e = elements[i_2];
                ctx.element.element = e;
                if (toPoint(ctx, b, position(e, distPivot), elementRadius(ctx), maxDist, elementRadius))
                    return true;
            }
        }
        return false;
    }
    MaxRadiusDist.check = check;
})(structure_distance_MaxRadiusDist || (structure_distance_MaxRadiusDist = {}));
//# sourceMappingURL=structure-distance.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/filters.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */








function pick(query, pred) {
    return function (ctx) {
        var sel = query(ctx);
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        ctx.pushCurrentElement();
        query_selection["a" /* StructureSelection */].forEach(sel, function (s, i) {
            ctx.currentStructure = s;
            if (pred(ctx))
                ret.add(s);
            if (i % 100)
                ctx.throwIfTimedOut();
        });
        ctx.popCurrentStructure();
        return ret.getSelection();
    };
}
function first(query) {
    return function (ctx) {
        var sel = query(ctx);
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        if (sel.kind === 'singletons') {
            if (sel.structure.elementCount > 0) {
                var u = sel.structure.units[0];
                var s = structure_structure_structure["a" /* default */].create([u.getChild(mol_data_int["SortedArray"].ofSingleton(u.elements[0]))], { parent: ctx.inputStructure });
                ret.add(s);
            }
        }
        else {
            if (sel.structures.length > 0) {
                ret.add(sel.structures[0]);
            }
        }
        return ret.getSelection();
    };
}
function getCurrentStructureProperties(ctx, props, set) {
    var units = ctx.currentStructure.units;
    var l = ctx.pushCurrentElement();
    l.structure = ctx.currentStructure;
    for (var _a = 0, units_1 = units; _a < units_1.length; _a++) {
        var unit = units_1[_a];
        l.unit = unit;
        var elements = unit.elements;
        var fn = void 0;
        if (structure_structure["g" /* Unit */].isAtomic(unit))
            fn = props.atomic;
        else
            fn = props.coarse;
        if (!fn)
            continue;
        for (var j = 0, _j = elements.length; j < _j; j++) {
            l.element = elements[j];
            set.add(fn(ctx));
        }
        ctx.throwIfTimedOut();
    }
    ctx.popCurrentElement();
    return set;
}
function getSelectionProperties(ctx, query, props) {
    var set = new Set();
    var sel = query(ctx);
    ctx.pushCurrentElement();
    query_selection["a" /* StructureSelection */].forEach(sel, function (s, i) {
        ctx.currentStructure = s;
        getCurrentStructureProperties(ctx, props, set);
        if (i % 10)
            ctx.throwIfTimedOut();
    });
    ctx.popCurrentElement();
    return set;
}
function withSameAtomProperties(query, propertySource, props) {
    return function (ctx) {
        var sel = query(ctx);
        var propSet = getSelectionProperties(ctx, propertySource, props);
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        ctx.pushCurrentStructure();
        query_selection["a" /* StructureSelection */].forEach(sel, function (s, i) {
            ctx.currentStructure = s;
            var currentProps = getCurrentStructureProperties(ctx, props, new Set());
            if (mol_util_set["a" /* SetUtils */].isSuperset(currentProps, propSet)) {
                ret.add(s);
            }
            if (i % 10)
                ctx.throwIfTimedOut();
        });
        ctx.popCurrentStructure();
        return ret.getSelection();
    };
}
function areIntersectedBy(query, by) {
    return function (ctx) {
        var mask = query_selection["a" /* StructureSelection */].unionStructure(by(ctx));
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        query_selection["a" /* StructureSelection */].forEach(query(ctx), function (s, i) {
            if (Object(structure_set["b" /* structureAreIntersecting */])(mask, s))
                ret.add(s);
            if (i % 10)
                ctx.throwIfTimedOut();
        });
        return ret.getSelection();
    };
}
function within(params) {
    return function (queryCtx) {
        var ctx = {
            queryCtx: queryCtx,
            selection: params.query(queryCtx),
            target: params.target(queryCtx),
            maxRadius: params.maxRadius,
            minRadius: params.minRadius ? Math.max(0, params.minRadius) : 0,
            elementRadius: params.elementRadius,
            invert: !!params.invert,
        };
        if (ctx.minRadius === 0 && typeof params.minRadius === 'undefined') {
            return withinMaxRadiusLookup(ctx);
        }
        else if (ctx.minRadius === 0) {
            return withinMaxRadius(ctx);
        }
        else {
            return withinMinMaxRadius(ctx);
        }
    };
}
function withinMaxRadiusLookup(_a) {
    var queryCtx = _a.queryCtx, selection = _a.selection, target = _a.target, maxRadius = _a.maxRadius, invert = _a.invert;
    var targetLookup = query_selection["a" /* StructureSelection */].unionStructure(target).lookup3d;
    var ret = query_selection["a" /* StructureSelection */].LinearBuilder(queryCtx.inputStructure);
    var pos = linear_algebra["Vec3"].zero();
    query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
        var units = s.units;
        var withinRadius = false;
        for (var i = 0, _i = units.length; i < _i; i++) {
            var unit = units[i];
            var elements = unit.elements, _a = unit.conformation, position = _a.position, r = _a.r;
            for (var i_1 = 0, _i_1 = elements.length; i_1 < _i_1; i_1++) {
                var e = elements[i_1];
                position(e, pos);
                if (targetLookup.check(pos[0], pos[1], pos[2], maxRadius + r(e))) {
                    withinRadius = true;
                    break;
                }
            }
            if (withinRadius)
                break;
        }
        if (invert)
            withinRadius = !withinRadius;
        if (withinRadius)
            ret.add(s);
        if (sI % 10 === 0)
            queryCtx.throwIfTimedOut();
    });
    return ret.getSelection();
}
function withinMaxRadius(_a) {
    var queryCtx = _a.queryCtx, selection = _a.selection, target = _a.target, maxRadius = _a.maxRadius, invert = _a.invert, elementRadius = _a.elementRadius;
    var targetStructure = query_selection["a" /* StructureSelection */].unionStructure(target);
    var ret = query_selection["a" /* StructureSelection */].LinearBuilder(queryCtx.inputStructure);
    queryCtx.pushCurrentElement();
    query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
        var withinRadius = checkStructureMaxRadiusDistance(queryCtx, targetStructure, s, maxRadius, elementRadius);
        if (invert)
            withinRadius = !withinRadius;
        if (withinRadius)
            ret.add(s);
        if (sI % 10 === 0)
            queryCtx.throwIfTimedOut();
    });
    queryCtx.popCurrentElement();
    return ret.getSelection();
}
function withinMinMaxRadius(_a) {
    var queryCtx = _a.queryCtx, selection = _a.selection, target = _a.target, minRadius = _a.minRadius, maxRadius = _a.maxRadius, invert = _a.invert, elementRadius = _a.elementRadius;
    var targetStructure = query_selection["a" /* StructureSelection */].unionStructure(target);
    var ret = query_selection["a" /* StructureSelection */].LinearBuilder(queryCtx.inputStructure);
    queryCtx.pushCurrentElement();
    query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
        var withinRadius = checkStructureMinMaxDistance(queryCtx, targetStructure, s, minRadius, maxRadius, elementRadius);
        if (invert)
            withinRadius = !withinRadius;
        if (withinRadius)
            ret.add(s);
        if (sI % 10 === 0)
            queryCtx.throwIfTimedOut();
    });
    queryCtx.popCurrentElement();
    return ret.getSelection();
}
function checkConnected(ctx, structure) {
    var queryCtx = ctx.queryCtx, input = ctx.input, target = ctx.target, disjunct = ctx.disjunct;
    var atomicBond = queryCtx.atomicBond;
    var interBonds = input.interUnitBonds;
    atomicBond.setStructure(input);
    for (var _a = 0, _b = structure.units; _a < _b.length; _a++) {
        var unit = _b[_a];
        if (!structure_structure["g" /* Unit */].isAtomic(unit))
            continue;
        var inputUnit = input.unitMap.get(unit.id);
        var _c = inputUnit.bonds, offset = _c.offset, b = _c.b, _d = _c.edgeProps, flags = _d.flags, order = _d.order;
        var bondedUnits = interBonds.getConnectedUnits(unit);
        var buCount = bondedUnits.length;
        var srcElements = unit.elements;
        var inputElements = inputUnit.elements;
        for (var i = 0, _i = srcElements.length; i < _i; i++) {
            var inputIndex = mol_data_int["SortedArray"].indexOf(inputElements, srcElements[i]);
            atomicBond.a.unit = inputUnit;
            atomicBond.b.unit = inputUnit;
            // tElement.unit = unit;
            for (var l = offset[inputIndex], _l = offset[inputIndex + 1]; l < _l; l++) {
                // tElement.element = inputElements[b[l]];
                atomicBond.b.element = inputUnit.elements[b[l]];
                if (disjunct && mol_data_int["SortedArray"].has(unit.elements, atomicBond.b.element))
                    continue;
                if (!target.hasElement(atomicBond.b))
                    continue;
                atomicBond.aIndex = inputIndex;
                atomicBond.a.element = srcElements[i];
                atomicBond.bIndex = b[l];
                atomicBond.type = flags[l];
                atomicBond.order = order[l];
                if (atomicBond.test(queryCtx, true))
                    return true;
            }
            for (var li = 0; li < buCount; li++) {
                var lu = bondedUnits[li];
                var bElements = lu.unitB.elements;
                var bonds = lu.getEdges(inputIndex);
                for (var bi = 0, _bi = bonds.length; bi < _bi; bi++) {
                    var bond = bonds[bi];
                    atomicBond.b.unit = lu.unitB;
                    atomicBond.b.element = bElements[bond.indexB];
                    if (!target.hasElement(atomicBond.b))
                        continue;
                    if (disjunct && structure.hasElement(atomicBond.b))
                        continue;
                    atomicBond.a.unit = inputUnit;
                    atomicBond.aIndex = inputIndex;
                    atomicBond.a.element = srcElements[i];
                    atomicBond.bIndex = bond.indexB;
                    atomicBond.type = bond.props.flag;
                    atomicBond.order = bond.props.order;
                    if (atomicBond.test(queryCtx, true))
                        return true;
                }
            }
        }
    }
    return false;
}
function isConnectedTo(_a) {
    var query = _a.query, target = _a.target, disjunct = _a.disjunct, invert = _a.invert, bondTest = _a.bondTest;
    return function (ctx) {
        var targetSel = target(ctx);
        if (query_selection["a" /* StructureSelection */].isEmpty(targetSel))
            return targetSel;
        var selection = query(ctx);
        if (query_selection["a" /* StructureSelection */].isEmpty(selection))
            return selection;
        var connCtx = {
            queryCtx: ctx,
            input: ctx.inputStructure,
            disjunct: disjunct,
            target: query_selection["a" /* StructureSelection */].unionStructure(targetSel)
        };
        var ret = query_selection["a" /* StructureSelection */].LinearBuilder(ctx.inputStructure);
        ctx.pushCurrentBond();
        ctx.atomicBond.setTestFn(bondTest);
        query_selection["a" /* StructureSelection */].forEach(selection, function (s, sI) {
            if (checkConnected(connCtx, s)) {
                ret.add(s);
            }
            else if (invert) {
                ret.add(s);
            }
            if (sI % 5 === 0)
                ctx.throwIfTimedOut();
        });
        ctx.popCurrentBond();
        return ret.getSelection();
    };
}
//# sourceMappingURL=filters.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/queries/combinators.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




function merge(queries) {
    if (queries.length === 0) {
        return none;
    }
    else if (queries.length === 1) {
        return queries[0];
    }
    return function (ctx) {
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        var _loop_1 = function (i) {
            query_selection["a" /* StructureSelection */].forEach(queries[i](ctx), function (s, j) {
                ret.add(s);
                if (i % 100)
                    ctx.throwIfTimedOut();
            });
        };
        for (var i = 0; i < queries.length; i++) {
            _loop_1(i);
        }
        return ret.getSelection();
    };
}
function intersect(queries) {
    if (queries.length === 0) {
        return none;
    }
    else if (queries.length === 1) {
        return queries[0];
    }
    return function (ctx) {
        var selections = [];
        for (var i = 0; i < queries.length; i++)
            selections.push(queries[i](ctx));
        var pivotIndex = 0, pivotLength = query_selection["a" /* StructureSelection */].structureCount(selections[0]);
        for (var i = 1; i < selections.length; i++) {
            var len = query_selection["a" /* StructureSelection */].structureCount(selections[i]);
            if (len < pivotLength) {
                pivotIndex = i;
                pivotLength = len;
            }
        }
        ctx.throwIfTimedOut();
        var pivotSet = Object(generic["a" /* HashSet */])(function (s) { return s.hashCode; }, structure_structure["c" /* Structure */].areUnitAndIndicesEqual);
        query_selection["a" /* StructureSelection */].forEach(selections[pivotIndex], function (s) { return pivotSet.add(s); });
        var ret = query_selection["a" /* StructureSelection */].UniqueBuilder(ctx.inputStructure);
        for (var pI = 0; pI < selections.length; pI++) {
            if (pI === pivotIndex)
                continue;
            query_selection["a" /* StructureSelection */].forEach(selections[pI], function (s) {
                if (pivotSet.has(s))
                    ret.add(s);
            });
            ctx.throwIfTimedOut();
        }
        return ret.getSelection();
    };
}
// TODO: distanceCluster
//# sourceMappingURL=combinators.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query/predicates.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var Predicates;
(function (Predicates) {
    function isSetLike(x) { return !!x && !!x.has; }
    function eq(p, value) { return function (l) { return p(l) === value; }; }
    Predicates.eq = eq;
    function lt(p, value) { return function (l) { return p(l) < value; }; }
    Predicates.lt = lt;
    function lte(p, value) { return function (l) { return p(l) <= value; }; }
    Predicates.lte = lte;
    function gt(p, value) { return function (l) { return p(l) > value; }; }
    Predicates.gt = gt;
    function gte(p, value) { return function (l) { return p(l) >= value; }; }
    Predicates.gte = gte;
    function _true(ctx) { return true; }
    function _false(ctx) { return false; }
    function inSet(p, values) {
        if (isSetLike(values)) {
            return function (l) { return values.has(p(l)); };
        }
        else {
            if (values.length === 0)
                return _false;
            var set_1 = new Set();
            for (var i = 0; i < values.length; i++)
                set_1.add(values[i]);
            return function (l) { return set_1.has(p(l)); };
        }
    }
    Predicates.inSet = inSet;
    function and() {
        var ps = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            ps[_i] = arguments[_i];
        }
        switch (ps.length) {
            case 0: return _true;
            case 1: return ps[0];
            case 2: {
                var a_1 = ps[0], b_1 = ps[1];
                return function (l) { return a_1(l) && b_1(l); };
            }
            case 3: {
                var a_2 = ps[0], b_2 = ps[1], c_1 = ps[2];
                return function (l) { return a_2(l) && b_2(l) && c_1(l); };
            }
            case 4: {
                var a_3 = ps[0], b_3 = ps[1], c_2 = ps[2], d_1 = ps[3];
                return function (l) { return a_3(l) && b_3(l) && c_2(l) && d_1(l); };
            }
            case 5: {
                var a_4 = ps[0], b_4 = ps[1], c_3 = ps[2], d_2 = ps[3], e_1 = ps[4];
                return function (l) { return a_4(l) && b_4(l) && c_3(l) && d_2(l) && e_1(l); };
            }
            case 6: {
                var a_5 = ps[0], b_5 = ps[1], c_4 = ps[2], d_3 = ps[3], e_2 = ps[4], f_1 = ps[5];
                return function (l) { return a_5(l) && b_5(l) && c_4(l) && d_3(l) && e_2(l) && f_1(l); };
            }
            default: {
                var count_1 = ps.length;
                return function (l) {
                    for (var i = 0; i < count_1; i++)
                        if (!ps[i])
                            return false;
                    return true;
                };
            }
        }
    }
    Predicates.and = and;
    function or() {
        var ps = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            ps[_i] = arguments[_i];
        }
        switch (ps.length) {
            case 0: return _false;
            case 1: return ps[0];
            case 2: {
                var a_6 = ps[0], b_6 = ps[1];
                return function (l) { return a_6(l) || b_6(l); };
            }
            case 3: {
                var a_7 = ps[0], b_7 = ps[1], c_5 = ps[2];
                return function (l) { return a_7(l) || b_7(l) || c_5(l); };
            }
            case 4: {
                var a_8 = ps[0], b_8 = ps[1], c_6 = ps[2], d_4 = ps[3];
                return function (l) { return a_8(l) || b_8(l) || c_6(l) || d_4(l); };
            }
            case 5: {
                var a_9 = ps[0], b_9 = ps[1], c_7 = ps[2], d_5 = ps[3], e_3 = ps[4];
                return function (l) { return a_9(l) || b_9(l) || c_7(l) || d_5(l) || e_3(l); };
            }
            case 6: {
                var a_10 = ps[0], b_10 = ps[1], c_8 = ps[2], d_6 = ps[3], e_4 = ps[4], f_2 = ps[5];
                return function (l) { return a_10(l) || b_10(l) || c_8(l) || d_6(l) || e_4(l) || f_2(l); };
            }
            default: {
                var count_2 = ps.length;
                return function (l) {
                    for (var i = 0; i < count_2; i++)
                        if (ps[i])
                            return true;
                    return false;
                };
            }
        }
    }
    Predicates.or = or;
})(Predicates || (Predicates = {}));
/* harmony default export */ var predicates = (Predicates);
//# sourceMappingURL=predicates.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/query.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */









var Queries = {
    generators: generators_namespaceObject,
    filters: filters_namespaceObject,
    modifiers: modifiers_namespaceObject,
    combinators: combinators_namespaceObject,
    pred: predicates,
    internal: internal
};

//# sourceMappingURL=query.js.map

/***/ }),
/* 167 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InnerSubscriber; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


var InnerSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](InnerSubscriber, _super);
    function InnerSubscriber(parent, outerValue, outerIndex) {
        var _this = _super.call(this) || this;
        _this.parent = parent;
        _this.outerValue = outerValue;
        _this.outerIndex = outerIndex;
        _this.index = 0;
        return _this;
    }
    InnerSubscriber.prototype._next = function (value) {
        this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this);
    };
    InnerSubscriber.prototype._error = function (error) {
        this.parent.notifyError(error, this);
        this.unsubscribe();
    };
    InnerSubscriber.prototype._complete = function () {
        this.parent.notifyComplete(this);
        this.unsubscribe();
    };
    return InnerSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));

//# sourceMappingURL=InnerSubscriber.js.map


/***/ }),
/* 168 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _unit__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(37);
/* harmony import */ var _model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(119);
/* harmony import */ var _mol_model_props_computed_secondary_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(152);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function p(p) { return p; }
var constant = {
    true: p(function (l) { return true; }),
    false: p(function (l) { return false; }),
    zero: p(function (l) { return 0; })
};
function notAtomic() {
    throw 'Property only available for atomic models.';
}
function notCoarse(kind) {
    if (!!kind)
        throw "Property only available for coarse models (" + kind + ").";
    throw "Property only available for coarse models.";
}
// TODO: remove the type checks?
var atom = {
    key: p(function (l) { return l.element; }),
    // Conformation
    x: p(function (l) { return l.unit.conformation.x(l.element); }),
    y: p(function (l) { return l.unit.conformation.y(l.element); }),
    z: p(function (l) { return l.unit.conformation.z(l.element); }),
    id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicConformation.atomId.value(l.element); }),
    occupancy: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicConformation.occupancy.value(l.element); }),
    B_iso_or_equiv: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicConformation.B_iso_or_equiv.value(l.element); }),
    sourceIndex: p(function (l) { return _unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit)
        ? l.unit.model.atomicHierarchy.atoms.sourceIndex.value(l.element)
        // TODO: when implemented, this should map to the source index.
        : l.element; }),
    // Hierarchy
    type_symbol: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.type_symbol.value(l.element); }),
    label_atom_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.label_atom_id.value(l.element); }),
    auth_atom_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.auth_atom_id.value(l.element); }),
    label_alt_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.label_alt_id.value(l.element); }),
    label_comp_id: p(compId),
    auth_comp_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.auth_comp_id.value(l.unit.residueIndex[l.element]); }),
    pdbx_formal_charge: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.atoms.pdbx_formal_charge.value(l.element); }),
    // Derived
    vdw_radius: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : Object(_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__["VdwRadius"])(l.unit.model.atomicHierarchy.atoms.type_symbol.value(l.element)); }),
};
function compId(l) {
    if (!_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit))
        notAtomic();
    return l.unit.model.atomicHierarchy.atoms.label_comp_id.value(l.element);
}
function seqId(l) {
    return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.residues.label_seq_id.value(l.unit.residueIndex[l.element]);
}
function hasMicroheterogeneity(l) {
    if (!_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit))
        notAtomic();
    var entitySeq = l.unit.model.sequence.byEntityKey[eK(l)];
    return entitySeq && entitySeq.sequence.microHet.has(seqId(l));
}
function microheterogeneityCompIds(l) {
    if (!_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit))
        notAtomic();
    var entitySeq = l.unit.model.sequence.byEntityKey[eK(l)];
    if (entitySeq) {
        return entitySeq.sequence.microHet.get(seqId(l)) || [compId(l)];
    }
    else {
        return [compId(l)];
    }
}
var residue = {
    key: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.residueIndex[l.element]; }),
    group_PDB: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.residues.group_PDB.value(l.unit.residueIndex[l.element]); }),
    label_seq_id: p(seqId),
    auth_seq_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.residues.auth_seq_id.value(l.unit.residueIndex[l.element]); }),
    pdbx_PDB_ins_code: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.residues.pdbx_PDB_ins_code.value(l.unit.residueIndex[l.element]); }),
    // Properties
    isNonStandard: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : microheterogeneityCompIds(l).some(function (c) { return l.unit.model.properties.chemicalComponentMap.get(c).mon_nstd_flag[0] !== 'y'; }); }),
    hasMicroheterogeneity: p(hasMicroheterogeneity),
    microheterogeneityCompIds: p(microheterogeneityCompIds),
    secondary_structure_type: p(function (l) {
        var _a, _b;
        if (!_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit))
            notAtomic();
        var secStruc = (_a = _mol_model_props_computed_secondary_structure__WEBPACK_IMPORTED_MODULE_2__[/* SecondaryStructureProvider */ "a"].get(l.structure).value) === null || _a === void 0 ? void 0 : _a.get(l.unit.id);
        return (_b = secStruc === null || secStruc === void 0 ? void 0 : secStruc.type[l.unit.residueIndex[l.element]]) !== null && _b !== void 0 ? _b : 536870912 /* NA */;
    }),
    secondary_structure_key: p(function (l) {
        var _a, _b;
        if (!_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit))
            notAtomic();
        var secStruc = (_a = _mol_model_props_computed_secondary_structure__WEBPACK_IMPORTED_MODULE_2__[/* SecondaryStructureProvider */ "a"].get(l.structure).value) === null || _a === void 0 ? void 0 : _a.get(l.unit.id);
        return (_b = secStruc === null || secStruc === void 0 ? void 0 : secStruc.key[l.unit.residueIndex[l.element]]) !== null && _b !== void 0 ? _b : -1;
    }),
    chem_comp_type: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.properties.chemicalComponentMap.get(compId(l)).type; }),
};
var chain = {
    key: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.chainIndex[l.element]; }),
    label_asym_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.chains.label_asym_id.value(l.unit.chainIndex[l.element]); }),
    auth_asym_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.chains.auth_asym_id.value(l.unit.chainIndex[l.element]); }),
    label_entity_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isAtomic(l.unit) ? notAtomic() : l.unit.model.atomicHierarchy.chains.label_entity_id.value(l.unit.chainIndex[l.element]); })
};
var coarse = {
    key: atom.key,
    entityKey: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isCoarse(l.unit) ? notCoarse() : l.unit.coarseElements.entityKey[l.element]; }),
    x: atom.x,
    y: atom.y,
    z: atom.z,
    asym_id: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isCoarse(l.unit) ? notCoarse() : l.unit.coarseElements.asym_id.value(l.element); }),
    seq_id_begin: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isCoarse(l.unit) ? notCoarse() : l.unit.coarseElements.seq_id_begin.value(l.element); }),
    seq_id_end: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isCoarse(l.unit) ? notCoarse() : l.unit.coarseElements.seq_id_end.value(l.element); }),
    sphere_radius: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isSpheres(l.unit) ? notCoarse('spheres') : l.unit.coarseConformation.radius[l.element]; }),
    sphere_rmsf: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isSpheres(l.unit) ? notCoarse('spheres') : l.unit.coarseConformation.rmsf[l.element]; }),
    gaussian_weight: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isGaussians(l.unit) ? notCoarse('gaussians') : l.unit.coarseConformation.weight[l.element]; }),
    gaussian_covariance_matrix: p(function (l) { return !_unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].isGaussians(l.unit) ? notCoarse('gaussians') : l.unit.coarseConformation.covariance_matrix[l.element]; })
};
function eK(l) {
    switch (l.unit.kind) {
        case 0 /* Atomic */:
            return l.unit.model.atomicHierarchy.index.getEntityFromChain(l.unit.chainIndex[l.element]);
        case 1 /* Spheres */:
            return l.unit.model.coarseHierarchy.spheres.entityKey[l.element];
        case 2 /* Gaussians */:
            return l.unit.model.coarseHierarchy.gaussians.entityKey[l.element];
    }
}
var entity = {
    key: p(eK),
    id: p(function (l) { return l.unit.model.entities.data.id.value(eK(l)); }),
    type: p(function (l) { return l.unit.model.entities.data.type.value(eK(l)); }),
    src_method: p(function (l) { return l.unit.model.entities.data.src_method.value(eK(l)); }),
    pdbx_description: p(function (l) { return l.unit.model.entities.data.pdbx_description.value(eK(l)); }),
    formula_weight: p(function (l) { return l.unit.model.entities.data.formula_weight.value(eK(l)); }),
    pdbx_number_of_molecules: p(function (l) { return l.unit.model.entities.data.pdbx_number_of_molecules.value(eK(l)); }),
    details: p(function (l) { return l.unit.model.entities.data.details.value(eK(l)); }),
    pdbx_mutation: p(function (l) { return l.unit.model.entities.data.pdbx_mutation.value(eK(l)); }),
    pdbx_fragment: p(function (l) { return l.unit.model.entities.data.pdbx_fragment.value(eK(l)); }),
    pdbx_ec: p(function (l) { return l.unit.model.entities.data.pdbx_ec.value(eK(l)); }),
    subtype: p(function (l) { return l.unit.model.entities.subtype.value(eK(l)); }),
    prd_id: p(function (l) { return l.unit.model.entities.prd_id.value(eK(l)); }),
};
var _emptyList = [];
var unit = {
    id: p(function (l) { return l.unit.id; }),
    chainGroupId: p(function (l) { return l.unit.chainGroupId; }),
    multiChain: p(function (l) { return _unit__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Traits.is(l.unit.traits, 1 /* MultiChain */); }),
    object_primitive: p(function (l) { return l.unit.objectPrimitive; }),
    operator_name: p(function (l) { return l.unit.conformation.operator.name; }),
    model_index: p(function (l) { return l.unit.model.modelNum; }),
    model_label: p(function (l) { return l.unit.model.label; }),
    model_entry_id: p(function (l) { return l.unit.model.entryId; }),
    hkl: p(function (l) { return l.unit.conformation.operator.hkl; }),
    spgrOp: p(function (l) { return l.unit.conformation.operator.spgrOp; }),
    model_num: p(function (l) { return l.unit.model.modelNum; }),
    pdbx_struct_assembly_id: p(function (l) { var _a; return ((_a = l.unit.conformation.operator.assembly) === null || _a === void 0 ? void 0 : _a.id) || _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SymmetryOperator */ "h"].DefaultName; }),
    pdbx_struct_oper_list_ids: p(function (l) { var _a; return ((_a = l.unit.conformation.operator.assembly) === null || _a === void 0 ? void 0 : _a.operList) || _emptyList; }),
    struct_ncs_oper_id: p(function (l) { return l.unit.conformation.operator.ncsId; }),
};
var StructureProperties = {
    constant: constant,
    atom: atom,
    residue: residue,
    chain: chain,
    entity: entity,
    unit: unit,
    coarse: coarse
};
/* harmony default export */ __webpack_exports__["a"] = (StructureProperties);
//# sourceMappingURL=properties.js.map

/***/ }),
/* 169 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return filter; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function filter(predicate, thisArg) {
    return function filterOperatorFunction(source) {
        return source.lift(new FilterOperator(predicate, thisArg));
    };
}
var FilterOperator = /*@__PURE__*/ (function () {
    function FilterOperator(predicate, thisArg) {
        this.predicate = predicate;
        this.thisArg = thisArg;
    }
    FilterOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg));
    };
    return FilterOperator;
}());
var FilterSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](FilterSubscriber, _super);
    function FilterSubscriber(destination, predicate, thisArg) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.thisArg = thisArg;
        _this.count = 0;
        return _this;
    }
    FilterSubscriber.prototype._next = function (value) {
        var result;
        try {
            result = this.predicate.call(this.thisArg, value, this.count++);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        if (result) {
            this.destination.next(value);
        }
    };
    return FilterSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
//# sourceMappingURL=filter.js.map


/***/ }),
/* 170 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "PluginBehavior", function() { return /* reexport */ behavior["PluginBehavior"]; });
__webpack_require__.d(__webpack_exports__, "BuiltInPluginBehaviors", function() { return /* binding */ BuiltInPluginBehaviors; });
__webpack_require__.d(__webpack_exports__, "PluginBehaviors", function() { return /* binding */ PluginBehaviors; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin/behavior/static/representation.js
var representation_namespaceObject = {};
__webpack_require__.r(representation_namespaceObject);
__webpack_require__.d(representation_namespaceObject, "registerDefault", function() { return registerDefault; });
__webpack_require__.d(representation_namespaceObject, "SyncRepresentationToCanvas", function() { return SyncRepresentationToCanvas; });
__webpack_require__.d(representation_namespaceObject, "SyncStructureRepresentation3DState", function() { return SyncStructureRepresentation3DState; });
__webpack_require__.d(representation_namespaceObject, "UpdateRepresentationVisibility", function() { return UpdateRepresentationVisibility; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin/behavior/static/camera.js
var camera_namespaceObject = {};
__webpack_require__.r(camera_namespaceObject);
__webpack_require__.d(camera_namespaceObject, "registerDefault", function() { return camera_registerDefault; });
__webpack_require__.d(camera_namespaceObject, "Reset", function() { return Reset; });
__webpack_require__.d(camera_namespaceObject, "SetSnapshot", function() { return SetSnapshot; });
__webpack_require__.d(camera_namespaceObject, "Focus", function() { return Focus; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin/behavior/static/misc.js
var misc_namespaceObject = {};
__webpack_require__.r(misc_namespaceObject);
__webpack_require__.d(misc_namespaceObject, "registerDefault", function() { return misc_registerDefault; });
__webpack_require__.d(misc_namespaceObject, "Canvas3DSetSettings", function() { return Canvas3DSetSettings; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/camera.js
var dynamic_camera_namespaceObject = {};
__webpack_require__.r(dynamic_camera_namespaceObject);
__webpack_require__.d(dynamic_camera_namespaceObject, "FocusLoci", function() { return FocusLoci; });

// NAMESPACE OBJECT: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props.js
var custom_props_namespaceObject = {};
__webpack_require__.r(custom_props_namespaceObject);
__webpack_require__.d(custom_props_namespaceObject, "StructureInfo", function() { return StructureInfo; });
__webpack_require__.d(custom_props_namespaceObject, "AccessibleSurfaceArea", function() { return accessible_surface_area_AccessibleSurfaceArea; });
__webpack_require__.d(custom_props_namespaceObject, "Interactions", function() { return Interactions; });
__webpack_require__.d(custom_props_namespaceObject, "SecondaryStructure", function() { return SecondaryStructure; });
__webpack_require__.d(custom_props_namespaceObject, "ValenceModel", function() { return ValenceModel; });
__webpack_require__.d(custom_props_namespaceObject, "CrossLinkRestraint", function() { return cross_link_restraint_CrossLinkRestraint; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/behavior.js
var behavior = __webpack_require__(68);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/state.js
var static_state = __webpack_require__(216);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/representation.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function registerDefault(ctx) {
    SyncRepresentationToCanvas(ctx);
    SyncStructureRepresentation3DState(ctx); // should be AFTER SyncRepresentationToCanvas
    UpdateRepresentationVisibility(ctx);
}
function SyncRepresentationToCanvas(ctx) {
    var events = ctx.state.data.events;
    events.object.created.subscribe(function (e) {
        var _a;
        if (!objects["a" /* PluginStateObject */].isRepresentation3D(e.obj))
            return;
        updateVisibility(e.state.cells.get(e.ref), e.obj.data.repr);
        e.obj.data.repr.setState({ syncManually: true });
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.add(e.obj.data.repr);
    });
    events.object.updated.subscribe(function (e) {
        var _a, _b;
        if (e.oldObj && objects["a" /* PluginStateObject */].isRepresentation3D(e.oldObj)) {
            (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.remove(e.oldObj.data.repr);
            e.oldObj.data.repr.destroy();
        }
        if (!objects["a" /* PluginStateObject */].isRepresentation3D(e.obj)) {
            return;
        }
        updateVisibility(e.state.cells.get(e.ref), e.obj.data.repr);
        if (e.action === 'recreate') {
            e.obj.data.repr.setState({ syncManually: true });
        }
        (_b = ctx.canvas3d) === null || _b === void 0 ? void 0 : _b.add(e.obj.data.repr);
    });
    events.object.removed.subscribe(function (e) {
        var _a;
        if (!objects["a" /* PluginStateObject */].isRepresentation3D(e.obj))
            return;
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.remove(e.obj.data.repr);
        e.obj.data.repr.destroy();
    });
}
function SyncStructureRepresentation3DState(ctx) {
    // TODO: figure out how to do transform composition here?
    var events = ctx.state.data.events;
    events.object.created.subscribe(function (e) {
        var _a;
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState.is(e.obj))
            return;
        var data = e.obj.data;
        data.source.data.repr.setState(data.state);
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.update(data.source.data.repr);
    });
    events.object.updated.subscribe(function (e) {
        var _a;
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState.is(e.obj))
            return;
        var data = e.obj.data;
        data.source.data.repr.setState(data.state);
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.update(data.source.data.repr);
    });
    events.object.removed.subscribe(function (e) {
        var _a;
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState.is(e.obj))
            return;
        var data = e.obj.data;
        data.source.data.repr.setState(data.initialState);
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.update(data.source.data.repr);
    });
}
function UpdateRepresentationVisibility(ctx) {
    ctx.state.data.events.cell.stateUpdated.subscribe(function (e) {
        var _a;
        var cell = e.state.cells.get(e.ref);
        if (!objects["a" /* PluginStateObject */].isRepresentation3D(cell.obj))
            return;
        updateVisibility(cell, cell.obj.data.repr);
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.syncVisibility();
    });
}
function updateVisibility(cell, r) {
    r.setState({ visible: !cell.state.isHidden });
}
//# sourceMappingURL=representation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/camera.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function camera_registerDefault(ctx) {
    Reset(ctx);
    Focus(ctx);
    SetSnapshot(ctx);
}
function Reset(ctx) {
    commands["PluginCommands"].Camera.Reset.subscribe(ctx, function (options) {
        ctx.managers.camera.reset(options === null || options === void 0 ? void 0 : options.snapshot, options === null || options === void 0 ? void 0 : options.durationMs);
    });
}
function SetSnapshot(ctx) {
    commands["PluginCommands"].Camera.SetSnapshot.subscribe(ctx, function (_a) {
        var snapshot = _a.snapshot, durationMs = _a.durationMs;
        ctx.managers.camera.setSnapshot(snapshot, durationMs);
    });
}
function Focus(ctx) {
    commands["PluginCommands"].Camera.Focus.subscribe(ctx, function (_a) {
        var center = _a.center, radius = _a.radius, durationMs = _a.durationMs;
        ctx.managers.camera.focusSphere({ center: center, radius: radius }, { durationMs: durationMs });
        ctx.events.canvas3d.settingsUpdated.next();
    });
}
//# sourceMappingURL=camera.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/canvas3d.js
var canvas3d = __webpack_require__(158);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/misc.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function misc_registerDefault(ctx) {
    Canvas3DSetSettings(ctx);
}
function Canvas3DSetSettings(ctx) {
    commands["PluginCommands"].Canvas3D.ResetSettings.subscribe(ctx, function () {
        var _a;
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.setProps(canvas3d["DefaultCanvas3DParams"]);
    });
    commands["PluginCommands"].Canvas3D.SetSettings.subscribe(ctx, function (e) {
        var _a;
        if (!ctx.canvas3d)
            return;
        (_a = ctx.canvas3d) === null || _a === void 0 ? void 0 : _a.setProps(e.settings);
        ctx.events.canvas3d.settingsUpdated.next();
    });
}
//# sourceMappingURL=misc.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/representation.js
var representation = __webpack_require__(223);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/input/input-observer.js
var input_observer = __webpack_require__(84);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/binding.js
var mol_util_binding = __webpack_require__(59);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/camera.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var B = input_observer["a" /* ButtonsType */];
var M = input_observer["b" /* ModifiersKeys */];
var Trigger = mol_util_binding["a" /* Binding */].Trigger;
var DefaultFocusLociBindings = {
    clickCenterFocus: Object(mol_util_binding["a" /* Binding */])([
        Trigger(1 /* Primary */, M.create()),
        Trigger(2 /* Secondary */, M.create()),
        Trigger(1 /* Primary */, M.create({ control: true }))
    ], 'Camera center and focus', 'Click element using ${triggers}'),
    clickCenterFocusSelectMode: Object(mol_util_binding["a" /* Binding */])([
        Trigger(2 /* Secondary */, M.create()),
        Trigger(1 /* Primary */, M.create({ control: true }))
    ], 'Camera center and focus', 'Click element using ${triggers}'),
};
var FocusLociParams = {
    minRadius: param_definition["ParamDefinition"].Numeric(8, { min: 1, max: 50, step: 1 }),
    extraRadius: param_definition["ParamDefinition"].Numeric(4, { min: 1, max: 50, step: 1 }, { description: 'Value added to the bounding-sphere radius of the Loci' }),
    durationMs: param_definition["ParamDefinition"].Numeric(250, { min: 0, max: 1000, step: 1 }, { description: 'Camera transition duration' }),
    bindings: param_definition["ParamDefinition"].Value(DefaultFocusLociBindings, { isHidden: true }),
};
var FocusLoci = behavior["PluginBehavior"].create({
    name: 'camera-focus-loci',
    category: 'interaction',
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        class_1.prototype.register = function () {
            var _this = this;
            this.subscribeObservable(this.ctx.behaviors.interaction.click, function (_a) {
                var current = _a.current, button = _a.button, modifiers = _a.modifiers;
                if (!_this.ctx.canvas3d)
                    return;
                var binding = _this.ctx.selectionMode
                    ? _this.params.bindings.clickCenterFocusSelectMode
                    : _this.params.bindings.clickCenterFocus;
                if (mol_util_binding["a" /* Binding */].match(binding, button, modifiers)) {
                    if (mol_model_loci["Loci"].isEmpty(current.loci)) {
                        commands["PluginCommands"].Camera.Reset(_this.ctx, {});
                        return;
                    }
                    var loci = mol_model_loci["Loci"].normalize(current.loci, _this.ctx.managers.interactivity.props.granularity);
                    _this.ctx.managers.camera.focusLoci(loci, _this.params);
                }
            });
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler)),
    params: function () { return FocusLociParams; },
    display: { name: 'Camera Focus Loci on Canvas' }
});
//# sourceMappingURL=camera.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/structure-info.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var StructureInfo = behavior["PluginBehavior"].create({
    name: 'structure-info-prop',
    category: 'custom-props',
    display: { name: 'Structure Info' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        Object.defineProperty(class_1.prototype, "maxModelIndex", {
            get: function () {
                var _a, _b;
                var maxIndex = -1;
                var cells = this.ctx.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Model));
                for (var _i = 0, cells_1 = cells; _i < cells_1.length; _i++) {
                    var c = cells_1[_i];
                    var index = ((_a = c.obj) === null || _a === void 0 ? void 0 : _a.data) && mol_model_structure["Model"].Index.get((_b = c.obj) === null || _b === void 0 ? void 0 : _b.data).value;
                    if (index !== undefined && index > maxIndex)
                        maxIndex = index;
                }
                return maxIndex;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(class_1.prototype, "maxStructureIndex", {
            get: function () {
                var _a, _b;
                var maxIndex = -1;
                var cells = this.ctx.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Structure));
                for (var _i = 0, cells_2 = cells; _i < cells_2.length; _i++) {
                    var c = cells_2[_i];
                    var index = ((_a = c.obj) === null || _a === void 0 ? void 0 : _a.data) && mol_model_structure["Structure"].Index.get((_b = c.obj) === null || _b === void 0 ? void 0 : _b.data).value;
                    if (index !== undefined && index > maxIndex)
                        maxIndex = index;
                }
                return maxIndex;
            },
            enumerable: false,
            configurable: true
        });
        Object.defineProperty(class_1.prototype, "asymIdOffset", {
            get: function () {
                var _a;
                var auth = 0;
                var label = 0;
                var cells = this.ctx.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Model));
                for (var _i = 0, cells_3 = cells; _i < cells_3.length; _i++) {
                    var c = cells_3[_i];
                    var m = (_a = c.obj) === null || _a === void 0 ? void 0 : _a.data;
                    if (m) {
                        var count = mol_model_structure["Model"].AsymIdCount.get(m);
                        var offset = mol_model_structure["Model"].AsymIdOffset.get(m).value;
                        if (count !== undefined && offset !== undefined) {
                            auth = Math.max(auth, offset.auth + count.auth);
                            label = Math.max(label, offset.label + count.label);
                        }
                    }
                }
                return { auth: auth, label: label };
            },
            enumerable: false,
            configurable: true
        });
        class_1.prototype.handleModel = function (model, oldModel) {
            if (mol_model_structure["Model"].Index.get(model).value === undefined) {
                var oldIndex = oldModel && mol_model_structure["Model"].Index.get(oldModel).value;
                var value = oldIndex !== null && oldIndex !== void 0 ? oldIndex : (this.maxModelIndex + 1);
                mol_model_structure["Model"].Index.set(model, { value: value });
            }
            if (mol_model_structure["Model"].AsymIdOffset.get(model).value === undefined) {
                var oldOffset = oldModel && mol_model_structure["Model"].AsymIdOffset.get(oldModel).value;
                var value = oldOffset !== null && oldOffset !== void 0 ? oldOffset : Object(tslib_es6["__assign"])({}, this.asymIdOffset);
                mol_model_structure["Model"].AsymIdOffset.set(model, { value: value });
            }
        };
        class_1.prototype.handleStructure = function (structure, oldStructure) {
            if (structure.parent !== undefined)
                return;
            if (mol_model_structure["Structure"].Index.get(structure).value !== undefined)
                return;
            var oldIndex = oldStructure && mol_model_structure["Structure"].Index.get(oldStructure).value;
            var value = oldIndex !== null && oldIndex !== void 0 ? oldIndex : (this.maxStructureIndex + 1);
            mol_model_structure["Structure"].Index.set(structure, { value: value });
        };
        class_1.prototype.handle = function (ref, obj, oldObj) {
            if (objects["a" /* PluginStateObject */].Molecule.Structure.is(obj)) {
                var transform = this.ctx.state.data.tree.transforms.get(ref);
                if (!transform.transformer.definition.isDecorator && obj.data.parent === undefined) {
                    this.handleStructure(obj.data, oldObj === null || oldObj === void 0 ? void 0 : oldObj.data);
                }
            }
            else if (objects["a" /* PluginStateObject */].Molecule.Model.is(obj)) {
                var transform = this.ctx.state.data.tree.transforms.get(ref);
                if (!transform.transformer.definition.isDecorator) {
                    this.handleModel(obj.data, oldObj === null || oldObj === void 0 ? void 0 : oldObj.data);
                }
            }
        };
        class_1.prototype.register = function () {
            var _this = this;
            this.ctx.customModelProperties.register(mol_model_structure["Model"].AsymIdOffset, true);
            this.ctx.customModelProperties.register(mol_model_structure["Model"].Index, true);
            this.ctx.customStructureProperties.register(mol_model_structure["Structure"].Index, true);
            this.subscribeObservable(this.ctx.state.data.events.object.created, function (o) {
                _this.handle(o.ref, o.obj);
            });
            this.subscribeObservable(this.ctx.state.data.events.object.updated, function (o) {
                _this.handle(o.ref, o.obj, o.oldObj);
            });
        };
        class_1.prototype.unregister = function () {
            this.ctx.customModelProperties.unregister(mol_model_structure["Model"].AsymIdOffset.descriptor.name);
            this.ctx.customModelProperties.unregister(mol_model_structure["Model"].Index.descriptor.name);
            this.ctx.customStructureProperties.unregister(mol_model_structure["Structure"].Index.descriptor.name);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler))
});
//# sourceMappingURL=structure-info.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/accessible-surface-area/shrake-rupley/common.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 */
/** Chothia's amino acid and nucleotide atom vdw radii */
var VdWLookup = [
    -1.0,
    1.76,
    1.87,
    1.65,
    1.50,
    1.40,
    1.85,
    1.80,
    1.60,
    1.40 // 9: P (nucleic)
]; // can still be appended on-the-fly for rare elements like selenium
/** Maximum accessible surface area observed for amino acids. Taken from: http://dx.doi.org/10.1371/journal.pone.0080635 */
var MaxAsa = {
    'ALA': 121.0,
    'ARG': 265.0,
    'ASN': 187.0,
    'ASP': 187.0,
    'CYS': 148.0,
    'GLU': 214.0,
    'GLN': 214.0,
    'GLY': 97.0,
    'HIS': 216.0,
    'ILE': 195.0,
    'LEU': 191.0,
    'LYS': 230.0,
    'MET': 203.0,
    'PHE': 228.0,
    'PRO': 154.0,
    'SER': 143.0,
    'THR': 163.0,
    'TRP': 264.0,
    'TYR': 255.0,
    'VAL': 165.0
};
var DefaultMaxAsa = 121.0;
//# sourceMappingURL=common.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/common.js
var common = __webpack_require__(109);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var model_types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic.js
var atomic = __webpack_require__(119);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js + 5 modules
var structure_structure = __webpack_require__(27);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/util.js
var util = __webpack_require__(147);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/accessible-surface-area/shrake-rupley/radii.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var radii_l = structure_structure["d" /* StructureElement */].Location.create(void 0);
function assignRadiusForHeavyAtoms(ctx) {
    var key = structure_structure["e" /* StructureProperties */].residue.key;
    var _a = structure_structure["e" /* StructureProperties */].atom, type_symbol = _a.type_symbol, label_atom_id = _a.label_atom_id, label_comp_id = _a.label_comp_id;
    var structure = ctx.structure, atomRadiusType = ctx.atomRadiusType, serialResidueIndex = ctx.serialResidueIndex;
    var prevResidueIdx = 0;
    var residueIdx = 0;
    var serialResidueIdx = -1;
    radii_l.structure = structure;
    for (var i = 0, m = 0, il = structure.units.length; i < il; ++i) {
        var unit = structure.units[i];
        var elements = unit.elements;
        radii_l.unit = unit;
        prevResidueIdx = -1;
        for (var j = 0, jl = elements.length; j < jl; ++j) {
            var eI = elements[j];
            var mj = m + j;
            radii_l.element = eI;
            residueIdx = key(radii_l);
            if (prevResidueIdx !== residueIdx)
                ++serialResidueIdx;
            prevResidueIdx = residueIdx;
            var element = type_symbol(radii_l);
            var elementIdx = Object(common["c" /* getElementIdx */])(element);
            // skip hydrogen atoms
            if (Object(common["f" /* isHydrogen */])(elementIdx)) {
                atomRadiusType[mj] = VdWLookup[0];
                serialResidueIndex[mj] = -1;
                continue;
            }
            var moleculeType = Object(util["b" /* getElementMoleculeType */])(unit, eI);
            // skip water and optionally non-polymer groups
            if (moleculeType === 2 /* Water */ || (!ctx.nonPolymer && !Object(model_types["isPolymer"])(moleculeType))) {
                atomRadiusType[mj] = VdWLookup[0];
                serialResidueIndex[mj] = -1;
                continue;
            }
            var atomId = label_atom_id(radii_l);
            var compId = label_comp_id(radii_l);
            if (Object(model_types["isNucleic"])(moleculeType)) {
                atomRadiusType[mj] = determineRadiusNucl(atomId, element, compId);
            }
            else if (moleculeType === 5 /* Protein */) {
                atomRadiusType[mj] = determineRadiusAmino(atomId, element, compId);
            }
            else {
                atomRadiusType[mj] = handleNonStandardCase(element);
            }
            serialResidueIndex[mj] = serialResidueIdx;
        }
        m += elements.length;
    }
}
/**
 * Gets the van der Waals radius of the given atom following the values defined by Chothia (1976)
 * J.Mol.Biol.105,1-14. NOTE: the vdw values defined by the paper assume no Hydrogens and thus "inflates" slightly
 * the heavy atoms to account for Hydrogens.
 */
function determineRadiusAmino(atomId, element, compId) {
    switch (element) {
        case 'O':
            return 5;
        case 'S':
            return 6;
        case 'N':
            return atomId === 'NZ' ? 4 : 3;
        case 'C':
            switch (atomId) {
                case 'C':
                case 'CE1':
                case 'CE2':
                case 'CE3':
                case 'CH2':
                case 'CZ':
                case 'CZ2':
                case 'CZ3':
                    return 1;
                case 'CA':
                case 'CB':
                case 'CE':
                case 'CG1':
                case 'CG2':
                    return 2;
                default:
                    switch (compId) {
                        case 'PHE':
                        case 'TRP':
                        case 'TYR':
                        case 'HIS':
                        case 'ASP':
                        case 'ASN':
                            return 1;
                        case 'PRO':
                        case 'LYS':
                        case 'ARG':
                        case 'MET':
                        case 'ILE':
                        case 'LEU':
                            return 2;
                        case 'GLU':
                        case 'GLN':
                            return atomId === 'CD' ? 1 : 2;
                    }
            }
    }
    return handleNonStandardCase(element);
}
function determineRadiusNucl(atomId, element, compId) {
    switch (element) {
        case 'C': return 7;
        case 'N': return 8;
        case 'P': return 9;
        case 'O': return 5;
    }
    return handleNonStandardCase(element);
}
function handleNonStandardCase(element) {
    var radius = Object(atomic["VdwRadius"])(element);
    var index = VdWLookup.indexOf(radius);
    if (index === -1) {
        // add novel value to lookup array
        index = VdWLookup.length;
        VdWLookup[index] = radius;
    }
    return index;
}
//# sourceMappingURL=radii.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/accessible-surface-area/shrake-rupley/area.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




// TODO
// - iterate over units and elements
// - avoid using serial-element index whenever possible
// - calculate atomRadiusType only for invariant units
// - factor serialResidueIndex out
var updateChunk = 5000;
function computeArea(runtime, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var atomRadius, i;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    atomRadius = ctx.atomRadiusType;
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < atomRadius.length)) return [3 /*break*/, 5];
                    if (!runtime.shouldUpdate) return [3 /*break*/, 3];
                    return [4 /*yield*/, runtime.update({ message: 'Computing per residue surface accessibility...', current: i, max: atomRadius.length })];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    computeRange(ctx, i, Math.min(i + updateChunk, atomRadius.length));
                    _a.label = 4;
                case 4:
                    i += updateChunk;
                    return [3 /*break*/, 1];
                case 5: return [2 /*return*/];
            }
        });
    });
}
var aPos = Object(linear_algebra["Vec3"])();
var bPos = Object(linear_algebra["Vec3"])();
var testPoint = Object(linear_algebra["Vec3"])();
var aLoc = structure_structure["d" /* StructureElement */].Location.create(void 0);
var bLoc = structure_structure["d" /* StructureElement */].Location.create(void 0);
function setLocation(l, structure, serialIndex) {
    l.structure = structure;
    l.unit = structure.units[structure.serialMapping.unitIndices[serialIndex]];
    l.element = structure.serialMapping.elementIndices[serialIndex];
    return l;
}
function computeRange(ctx, begin, end) {
    var structure = ctx.structure, atomRadiusType = ctx.atomRadiusType, serialResidueIndex = ctx.serialResidueIndex, area = ctx.area, spherePoints = ctx.spherePoints, scalingConstant = ctx.scalingConstant, maxLookupRadius = ctx.maxLookupRadius, probeSize = ctx.probeSize;
    var _a = structure_structure["e" /* StructureProperties */].atom, x = _a.x, y = _a.y, z = _a.z;
    var lookup3d = structure.lookup3d, serialMapping = structure.serialMapping, unitIndexMap = structure.unitIndexMap;
    var cumulativeUnitElementCount = serialMapping.cumulativeUnitElementCount;
    for (var aI = begin; aI < end; ++aI) {
        var radius1 = VdWLookup[atomRadiusType[aI]];
        if (radius1 === VdWLookup[0])
            continue;
        setLocation(aLoc, structure, aI);
        var aX = x(aLoc);
        var aY = y(aLoc);
        var aZ = z(aLoc);
        // pre-filter by lookup3d (provides >10x speed-up compared to naive evaluation)
        var _b = lookup3d.find(aX, aY, aZ, maxLookupRadius), count = _b.count, units = _b.units, indices = _b.indices, squaredDistances = _b.squaredDistances;
        // collect neighbors for each atom
        var cutoff1 = probeSize + probeSize + radius1;
        var neighbors = []; // TODO reuse
        for (var iI = 0; iI < count; ++iI) {
            var bUnit = units[iI];
            structure_structure["d" /* StructureElement */].Location.set(bLoc, ctx.structure, bUnit, bUnit.elements[indices[iI]]);
            var bI = cumulativeUnitElementCount[unitIndexMap.get(bUnit.id)] + indices[iI];
            var radius2 = VdWLookup[atomRadiusType[bI]];
            if (structure_structure["d" /* StructureElement */].Location.areEqual(aLoc, bLoc) || radius2 === VdWLookup[0])
                continue;
            var cutoff2 = (cutoff1 + radius2) * (cutoff1 + radius2);
            if (squaredDistances[iI] < cutoff2) {
                neighbors[neighbors.length] = bI;
            }
        }
        // for all neighbors: test all sphere points
        linear_algebra["Vec3"].set(aPos, aX, aY, aZ);
        var scale = probeSize + radius1;
        var accessiblePointCount = 0;
        for (var sI = 0; sI < spherePoints.length; ++sI) {
            linear_algebra["Vec3"].scaleAndAdd(testPoint, aPos, spherePoints[sI], scale);
            var accessible = true;
            for (var _nI = 0; _nI < neighbors.length; ++_nI) {
                var nI = neighbors[_nI];
                setLocation(bLoc, structure, nI);
                linear_algebra["Vec3"].set(bPos, x(bLoc), y(bLoc), z(bLoc));
                var radius3 = VdWLookup[atomRadiusType[nI]];
                var cutoff3 = (radius3 + probeSize) * (radius3 + probeSize);
                if (linear_algebra["Vec3"].squaredDistance(testPoint, bPos) < cutoff3) {
                    accessible = false;
                    break;
                }
            }
            if (accessible)
                ++accessiblePointCount;
        }
        area[serialResidueIndex[aI]] += scalingConstant * accessiblePointCount * scale * scale;
    }
}
//# sourceMappingURL=area.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/accessible-surface-area/shrake-rupley.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


// import { BitFlags } from '../../../mol-util';






var ShrakeRupleyComputationParams = {
    numberOfSpherePoints: param_definition["ParamDefinition"].Numeric(92, { min: 12, max: 360, step: 1 }, { description: 'Number of sphere points to sample per atom: 92 (original paper), 960 (BioJava), 3000 (EPPIC) - see Shrake A, Rupley JA: Environment and exposure to solvent of protein atoms. Lysozyme and insulin. J Mol Biol 1973.' }),
    probeSize: param_definition["ParamDefinition"].Numeric(1.4, { min: 0.1, max: 4, step: 0.01 }, { description: 'Corresponds to the size of a water molecule: 1.4 (original paper), 1.5 (occassionally used)' }),
    // buriedRasaThreshold: PD.Numeric(0.16, { min: 0.0, max: 1.0 }, { description: 'below this cutoff of relative accessible surface area a residue will be considered buried - see: Rost B, Sander C: Conservation and prediction of solvent accessibility in protein families. Proteins 1994.' }),
    nonPolymer: param_definition["ParamDefinition"].Boolean(false, { description: 'Include non-polymer atoms as occluders.' })
};
// TODO
// - add back buried and relative asa

var shrake_rupley_AccessibleSurfaceArea;
(function (AccessibleSurfaceArea) {
    /**
     * Adapts the BioJava implementation by Jose Duarte. That implementation is based on the publication by Shrake, A., and
     * J. A. Rupley. "Environment and Exposure to Solvent of Protein Atoms. Lysozyme and Insulin." JMB (1973).
     */
    function compute(structure, props) {
        var _this = this;
        if (props === void 0) { props = {}; }
        var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(ShrakeRupleyComputationParams)), props);
        return mol_task["b" /* Task */].create('Compute Accessible Surface Area', function (runtime) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, calculate(runtime, structure, p)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        }); });
    }
    AccessibleSurfaceArea.compute = compute;
    function calculate(runtime, structure, props) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var ctx, area, serialResidueIndex;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        ctx = initialize(structure, props);
                        assignRadiusForHeavyAtoms(ctx);
                        return [4 /*yield*/, computeArea(runtime, ctx)];
                    case 1:
                        _a.sent();
                        area = ctx.area, serialResidueIndex = ctx.serialResidueIndex;
                        return [2 /*return*/, { area: area, serialResidueIndex: serialResidueIndex }];
                }
            });
        });
    }
    function initialize(structure, props) {
        var elementCount = structure.elementCount, atomicResidueCount = structure.atomicResidueCount;
        var probeSize = props.probeSize, nonPolymer = props.nonPolymer, numberOfSpherePoints = props.numberOfSpherePoints;
        return {
            structure: structure,
            probeSize: probeSize,
            nonPolymer: nonPolymer,
            spherePoints: generateSpherePoints(numberOfSpherePoints),
            scalingConstant: 4.0 * Math.PI / numberOfSpherePoints,
            maxLookupRadius: 2 * props.probeSize + 2 * VdWLookup[2],
            atomRadiusType: new Int8Array(elementCount),
            serialResidueIndex: new Int32Array(elementCount),
            area: new Float32Array(atomicResidueCount)
        };
    }
    /** Creates a collection of points on a sphere by the Golden Section Spiral algorithm. */
    function generateSpherePoints(numberOfSpherePoints) {
        var points = [];
        var inc = Math.PI * (3.0 - Math.sqrt(5.0));
        var offset = 2.0 / numberOfSpherePoints;
        for (var k = 0; k < numberOfSpherePoints; ++k) {
            var y = k * offset - 1.0 + (offset / 2.0);
            var r = Math.sqrt(1.0 - y * y);
            var phi = k * inc;
            points[points.length] = linear_algebra["Vec3"].create(Math.cos(phi) * r, y, Math.sin(phi) * r);
        }
        return points;
    }
    /** Get relative area for a given component id */
    function normalize(compId, asa) {
        var maxAsa = MaxAsa[compId] || DefaultMaxAsa;
        return asa / maxAsa;
    }
    AccessibleSurfaceArea.normalize = normalize;
    function getValue(location, accessibleSurfaceArea) {
        var getSerialIndex = location.structure.root.serialMapping.getSerialIndex;
        var area = accessibleSurfaceArea.area, serialResidueIndex = accessibleSurfaceArea.serialResidueIndex;
        var rSI = serialResidueIndex[getSerialIndex(location.unit, location.element)];
        if (rSI === -1)
            return -1;
        return area[rSI];
    }
    AccessibleSurfaceArea.getValue = getValue;
    function getNormalizedValue(location, accessibleSurfaceArea) {
        var value = getValue(location, accessibleSurfaceArea);
        return value === -1 ? -1 : normalize(mol_model_structure["StructureProperties"].atom.label_comp_id(location), value);
    }
    AccessibleSurfaceArea.getNormalizedValue = getNormalizedValue;
    function getFlag(location, accessibleSurfaceArea) {
        var value = getNormalizedValue(location, accessibleSurfaceArea);
        return value === -1 ? 0 /* NA */ :
            value < 0.16 ? 1 /* Buried */ :
                2 /* Accessible */;
    }
    AccessibleSurfaceArea.getFlag = getFlag;
})(shrake_rupley_AccessibleSurfaceArea || (shrake_rupley_AccessibleSurfaceArea = {}));
//# sourceMappingURL=shrake-rupley.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-structure-property.js
var custom_structure_property = __webpack_require__(204);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/compiler.js + 2 modules
var compiler = __webpack_require__(163);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/symbol.js
var symbol = __webpack_require__(18);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/type.js
var language_type = __webpack_require__(15);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/accessible-surface-area.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var AccessibleSurfaceAreaParams = Object(tslib_es6["__assign"])({}, ShrakeRupleyComputationParams);
var AccessibleSurfaceAreaSymbols = {
    isBuried: compiler["QuerySymbolRuntime"].Dynamic(Object(symbol["c" /* CustomPropSymbol */])('computed', 'accessible-surface-area.is-buried', language_type["a" /* default */].Bool), function (ctx) {
        if (!mol_model_structure["Unit"].isAtomic(ctx.element.unit))
            return false;
        var accessibleSurfaceArea = AccessibleSurfaceAreaProvider.get(ctx.element.structure).value;
        if (!accessibleSurfaceArea)
            return false;
        return shrake_rupley_AccessibleSurfaceArea.getFlag(ctx.element, accessibleSurfaceArea) === 1 /* Buried */;
    }),
    isAccessible: compiler["QuerySymbolRuntime"].Dynamic(Object(symbol["c" /* CustomPropSymbol */])('computed', 'accessible-surface-area.is-accessible', language_type["a" /* default */].Bool), function (ctx) {
        if (!mol_model_structure["Unit"].isAtomic(ctx.element.unit))
            return false;
        var accessibleSurfaceArea = AccessibleSurfaceAreaProvider.get(ctx.element.structure).value;
        if (!accessibleSurfaceArea)
            return false;
        return shrake_rupley_AccessibleSurfaceArea.getFlag(ctx.element, accessibleSurfaceArea) === 2 /* Accessible */;
    }),
};
var AccessibleSurfaceAreaProvider = custom_structure_property["a" /* CustomStructureProperty */].createProvider({
    label: 'Accessible Surface Area',
    descriptor: Object(custom_property["CustomPropertyDescriptor"])({
        name: 'molstar_accessible_surface_area',
        symbols: AccessibleSurfaceAreaSymbols,
    }),
    type: 'root',
    defaultParams: AccessibleSurfaceAreaParams,
    getParams: function (data) { return AccessibleSurfaceAreaParams; },
    isApplicable: function (data) { return true; },
    obtain: function (ctx, data, props) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var p, _a;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(AccessibleSurfaceAreaParams)), props);
                    _a = {};
                    return [4 /*yield*/, shrake_rupley_AccessibleSurfaceArea.compute(data, p).runInContext(ctx.runtime)];
                case 1: return [2 /*return*/, (_a.value = _b.sent(), _a)];
            }
        });
    }); }
});
//# sourceMappingURL=accessible-surface-area.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/themes/accessible-surface-area.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Sebastian Bittrich <sebastian.bittrich@rcsb.org>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var DefaultColor = Object(mol_util_color["Color"])(0xFAFAFA);
var Description = 'Assigns a color based on the relative accessible surface area of a residue.';
var AccessibleSurfaceAreaColorThemeParams = {
    list: param_definition["ParamDefinition"].ColorList('rainbow', { presetKind: 'scale' })
};
function getAccessibleSurfaceAreaColorThemeParams(ctx) {
    return AccessibleSurfaceAreaColorThemeParams; // TODO return copy
}
function AccessibleSurfaceAreaColorTheme(ctx, props) {
    var color;
    var scale = mol_util_color["ColorScale"].create({
        listOrName: props.list.colors,
        minLabel: 'buried',
        maxLabel: 'exposed',
        domain: [0.0, 1.0]
    });
    var accessibleSurfaceArea = ctx.structure && AccessibleSurfaceAreaProvider.get(ctx.structure);
    var contextHash = accessibleSurfaceArea === null || accessibleSurfaceArea === void 0 ? void 0 : accessibleSurfaceArea.version;
    if ((accessibleSurfaceArea === null || accessibleSurfaceArea === void 0 ? void 0 : accessibleSurfaceArea.value) && ctx.structure) {
        var asa_1 = accessibleSurfaceArea.value;
        color = function (location) {
            if (mol_model_structure["StructureElement"].Location.is(location) && mol_model_structure["Unit"].isAtomic(location.unit)) {
                var value = shrake_rupley_AccessibleSurfaceArea.getNormalizedValue(location, asa_1);
                return value === -1 ? DefaultColor : scale.color(value);
            }
            return DefaultColor;
        };
    }
    else {
        color = function () { return DefaultColor; };
    }
    return {
        factory: AccessibleSurfaceAreaColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        contextHash: contextHash,
        description: Description,
        legend: scale ? scale.legend : undefined
    };
}
var AccessibleSurfaceAreaColorThemeProvider = {
    name: 'accessible-surface-area',
    label: 'Accessible Surface Area',
    category: "Residue Property" /* Residue */,
    factory: AccessibleSurfaceAreaColorTheme,
    getParams: getAccessibleSurfaceAreaColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(AccessibleSurfaceAreaColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? AccessibleSurfaceAreaProvider.attach(ctx, data.structure, void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.customPropertyDescriptors.reference(AccessibleSurfaceAreaProvider.descriptor, false); }
    }
};
//# sourceMappingURL=accessible-surface-area.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-selection-query.js
var structure_selection_query = __webpack_require__(80);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/builder.js
var builder = __webpack_require__(10);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/computed/accessible-surface-area.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var accessible_surface_area_AccessibleSurfaceArea = behavior["PluginBehavior"].create({
    name: 'computed-accessible-surface-area-prop',
    category: 'custom-props',
    display: { name: 'Accessible Surface Area' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = AccessibleSurfaceAreaProvider;
            _this.labelProvider = {
                label: function (loci) {
                    if (!_this.params.showTooltip)
                        return;
                    return accessibleSurfaceAreaLabel(loci);
                }
            };
            return _this;
        }
        class_1.prototype.update = function (p) {
            var updated = (this.params.autoAttach !== p.autoAttach ||
                this.params.showTooltip !== p.showTooltip);
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customStructureProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.register = function () {
            compiler["DefaultQueryRuntimeTable"].addCustomProp(this.provider.descriptor);
            this.ctx.customStructureProperties.register(this.provider, this.params.autoAttach);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(AccessibleSurfaceAreaColorThemeProvider);
            this.ctx.managers.lociLabels.addProvider(this.labelProvider);
            this.ctx.query.structure.registry.add(isBuried);
            this.ctx.query.structure.registry.add(isAccessible);
        };
        class_1.prototype.unregister = function () {
            compiler["DefaultQueryRuntimeTable"].removeCustomProp(this.provider.descriptor);
            this.ctx.customStructureProperties.unregister(this.provider.descriptor.name);
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(AccessibleSurfaceAreaColorThemeProvider);
            this.ctx.managers.lociLabels.removeProvider(this.labelProvider);
            this.ctx.query.structure.registry.remove(isBuried);
            this.ctx.query.structure.registry.remove(isAccessible);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler)),
    params: function () { return ({
        autoAttach: param_definition["ParamDefinition"].Boolean(false),
        showTooltip: param_definition["ParamDefinition"].Boolean(true)
    }); }
});
//
function accessibleSurfaceAreaLabel(loci) {
    if (loci.kind === 'element-loci') {
        if (loci.elements.length === 0)
            return;
        var accessibleSurfaceArea = AccessibleSurfaceAreaProvider.get(loci.structure).value;
        if (!accessibleSurfaceArea || loci.structure.customPropertyDescriptors.hasReference(AccessibleSurfaceAreaProvider.descriptor))
            return;
        var getSerialIndex_1 = loci.structure.root.serialMapping.getSerialIndex;
        var area_1 = accessibleSurfaceArea.area, serialResidueIndex_1 = accessibleSurfaceArea.serialResidueIndex;
        var seen_1 = new Set();
        var cummulativeArea_1 = 0;
        var _loop_1 = function (indices, unit) {
            var elements = unit.elements;
            mol_data_int["OrderedSet"].forEach(indices, function (idx) {
                var rSI = serialResidueIndex_1[getSerialIndex_1(unit, elements[idx])];
                if (rSI !== -1 && !seen_1.has(rSI)) {
                    cummulativeArea_1 += area_1[rSI];
                    seen_1.add(rSI);
                }
            });
        };
        for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
            var _b = _a[_i], indices = _b.indices, unit = _b.unit;
            _loop_1(indices, unit);
        }
        if (seen_1.size === 0)
            return;
        var residueCount = "<small>(" + seen_1.size + " " + (seen_1.size > 1 ? 'Residues sum' : 'Residue') + ")</small>";
        return "Accessible Surface Area " + residueCount + ": " + cummulativeArea_1.toFixed(2) + " \u212B<sup>2</sup>";
    }
    else if (loci.kind === 'structure-loci') {
        var accessibleSurfaceArea = AccessibleSurfaceAreaProvider.get(loci.structure).value;
        if (!accessibleSurfaceArea || loci.structure.customPropertyDescriptors.hasReference(AccessibleSurfaceAreaProvider.descriptor))
            return;
        return "Accessible Surface Area <small>(Whole Structure)</small>: " + Object(array["arraySum"])(accessibleSurfaceArea.area).toFixed(2) + " \u212B<sup>2</sup>";
    }
}
//
var isBuried = Object(structure_selection_query["c" /* StructureSelectionQuery */])('Buried Protein Residues', builder["MolScriptBuilder"].struct.modifier.union([
    builder["MolScriptBuilder"].struct.modifier.wholeResidues([
        builder["MolScriptBuilder"].struct.modifier.union([
            builder["MolScriptBuilder"].struct.generator.atomGroups({
                'chain-test': builder["MolScriptBuilder"].core.rel.eq([builder["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': AccessibleSurfaceAreaSymbols.isBuried.symbol(),
            })
        ])
    ])
]), {
    description: 'Select buried protein residues.',
    category: structure_selection_query["a" /* StructureSelectionCategory */].Residue,
    ensureCustomProperties: function (ctx, structure) {
        return AccessibleSurfaceAreaProvider.attach(ctx, structure);
    }
});
var isAccessible = Object(structure_selection_query["c" /* StructureSelectionQuery */])('Accessible Protein Residues', builder["MolScriptBuilder"].struct.modifier.union([
    builder["MolScriptBuilder"].struct.modifier.wholeResidues([
        builder["MolScriptBuilder"].struct.modifier.union([
            builder["MolScriptBuilder"].struct.generator.atomGroups({
                'chain-test': builder["MolScriptBuilder"].core.rel.eq([builder["MolScriptBuilder"].ammp('objectPrimitive'), 'atomistic']),
                'residue-test': AccessibleSurfaceAreaSymbols.isAccessible.symbol(),
            })
        ])
    ])
]), {
    description: 'Select accessible protein residues.',
    category: structure_selection_query["a" /* StructureSelectionCategory */].Residue,
    ensureCustomProperties: function (ctx, structure) {
        return AccessibleSurfaceAreaProvider.attach(ctx, structure);
    }
});
//# sourceMappingURL=accessible-surface-area.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions.js
var computed_interactions = __webpack_require__(108);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element.js + 3 modules
var structure_element = __webpack_require__(129);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/common.js
var interactions_common = __webpack_require__(252);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/themes/interaction-type.js
var interaction_type = __webpack_require__(330);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/representations/interactions.js + 2 modules
var representations_interactions = __webpack_require__(334);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/computed/interactions.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var Interactions = behavior["PluginBehavior"].create({
    name: 'computed-interactions-prop',
    category: 'custom-props',
    display: { name: 'Interactions' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = computed_interactions["a" /* InteractionsProvider */];
            _this.labelProvider = {
                label: function (loci) {
                    if (!_this.params.showTooltip)
                        return void 0;
                    switch (loci.kind) {
                        case 'element-loci':
                            if (loci.elements.length === 0)
                                return void 0;
                            var labels = [];
                            var structures = _this.getStructures(loci.structure);
                            for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
                                var s = structures_1[_i];
                                var interactions = _this.provider.get(s).value;
                                if (!interactions)
                                    continue;
                                var l = structure_element["a" /* default */].Loci.remap(loci, s);
                                if (l.elements.length !== 1)
                                    continue;
                                var e = l.elements[0];
                                if (mol_data_int["OrderedSet"].size(e.indices) !== 1)
                                    continue;
                                var features = interactions.unitsFeatures.get(e.unit.id);
                                if (!features)
                                    continue;
                                var typeLabels = [];
                                var groupLabels = [];
                                var label = [];
                                var idx = mol_data_int["OrderedSet"].start(e.indices);
                                var types = features.types, groups = features.groups, _a = features.elementsIndex, indices = _a.indices, offsets = _a.offsets;
                                for (var i = offsets[idx], il = offsets[idx + 1]; i < il; ++i) {
                                    var f = indices[i];
                                    var type = types[f];
                                    var group = groups[f];
                                    if (type)
                                        typeLabels.push(Object(interactions_common["d" /* featureTypeLabel */])(type));
                                    if (group)
                                        groupLabels.push(Object(interactions_common["c" /* featureGroupLabel */])(group));
                                }
                                if (typeLabels.length)
                                    label.push("<small>Types</small> " + typeLabels.join(', '));
                                if (groupLabels.length)
                                    label.push("<small>Groups</small> " + groupLabels.join(', '));
                                if (label.length)
                                    labels.push("Interaction Feature: " + label.join(' | '));
                            }
                            return labels.length ? labels.join('<br/>') : undefined;
                        default: return void 0;
                    }
                }
            };
            return _this;
        }
        class_1.prototype.getStructures = function (structure) {
            var structures = [];
            var root = this.ctx.helpers.substructureParent.get(structure);
            if (root) {
                var state = this.ctx.state.data;
                var selections = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure, root.transform.ref));
                for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
                    var s = selections_1[_i];
                    if (s.obj)
                        Object(array["arraySetAdd"])(structures, s.obj.data);
                }
            }
            return structures;
        };
        class_1.prototype.update = function (p) {
            var updated = (this.params.autoAttach !== p.autoAttach ||
                this.params.showTooltip !== p.showTooltip);
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customStructureProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.register = function () {
            this.ctx.customStructureProperties.register(this.provider, this.params.autoAttach);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(interaction_type["a" /* InteractionTypeColorThemeProvider */]);
            this.ctx.managers.lociLabels.addProvider(this.labelProvider);
            this.ctx.representation.structure.registry.add(representations_interactions["a" /* InteractionsRepresentationProvider */]);
        };
        class_1.prototype.unregister = function () {
            this.ctx.customStructureProperties.unregister(this.provider.descriptor.name);
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(interaction_type["a" /* InteractionTypeColorThemeProvider */]);
            this.ctx.managers.lociLabels.removeProvider(this.labelProvider);
            this.ctx.representation.structure.registry.remove(representations_interactions["a" /* InteractionsRepresentationProvider */]);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler)),
    params: function () { return ({
        autoAttach: param_definition["ParamDefinition"].Boolean(false),
        showTooltip: param_definition["ParamDefinition"].Boolean(true)
    }); }
});
//# sourceMappingURL=interactions.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure.js + 12 modules
var secondary_structure = __webpack_require__(152);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/computed/secondary-structure.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var SecondaryStructure = behavior["PluginBehavior"].create({
    name: 'computed-secondary-structure-prop',
    category: 'custom-props',
    display: { name: 'Secondary Structure' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = secondary_structure["a" /* SecondaryStructureProvider */];
            return _this;
        }
        class_1.prototype.update = function (p) {
            var updated = (this.params.autoAttach !== p.autoAttach);
            this.params.autoAttach = p.autoAttach;
            this.ctx.customStructureProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.register = function () {
            this.ctx.customStructureProperties.register(this.provider, this.params.autoAttach);
        };
        class_1.prototype.unregister = function () {
            this.ctx.customStructureProperties.unregister(this.provider.descriptor.name);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler)),
    params: function () { return ({
        autoAttach: param_definition["ParamDefinition"].Boolean(false)
    }); }
});
//# sourceMappingURL=secondary-structure.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/valence-model.js + 1 modules
var valence_model = __webpack_require__(228);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/geometry.js
var geometry = __webpack_require__(153);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/computed/valence-model.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var ValenceModel = behavior["PluginBehavior"].create({
    name: 'computed-valence-model-prop',
    category: 'custom-props',
    display: { name: 'Valence Model' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = valence_model["a" /* ValenceModelProvider */];
            _this.labelProvider = {
                label: function (loci) {
                    if (!_this.params.showTooltip)
                        return void 0;
                    switch (loci.kind) {
                        case 'element-loci':
                            if (loci.elements.length === 0)
                                return void 0;
                            var labels = [];
                            var structures = _this.getStructures(loci.structure);
                            for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
                                var s = structures_1[_i];
                                var valenceModel = _this.provider.get(s).value;
                                if (!valenceModel)
                                    continue;
                                var l = mol_model_structure["StructureElement"].Loci.remap(loci, s);
                                if (l.elements.length !== 1)
                                    continue;
                                var e = l.elements[0];
                                if (mol_data_int["OrderedSet"].size(e.indices) !== 1)
                                    continue;
                                var vm = valenceModel.get(e.unit.id);
                                if (!vm)
                                    continue;
                                var idx = mol_data_int["OrderedSet"].start(e.indices);
                                var charge = vm.charge[idx];
                                var idealGeometry = vm.idealGeometry[idx];
                                var implicitH = vm.implicitH[idx];
                                var totalH = vm.totalH[idx];
                                labels.push("Valence Model: <small>Charge</small> " + charge + " | <small>Ideal Geometry</small> " + Object(geometry["e" /* geometryLabel */])(idealGeometry) + " | <small>Implicit H</small> " + implicitH + " | <small>Total H</small> " + totalH);
                            }
                            return labels.length ? labels.join('<br/>') : undefined;
                        default: return void 0;
                    }
                }
            };
            return _this;
        }
        class_1.prototype.getStructures = function (structure) {
            var structures = [];
            var root = this.ctx.helpers.substructureParent.get(structure);
            if (root) {
                var state = this.ctx.state.data;
                var selections = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure, root.transform.ref));
                for (var _i = 0, selections_1 = selections; _i < selections_1.length; _i++) {
                    var s = selections_1[_i];
                    if (s.obj)
                        Object(array["arraySetAdd"])(structures, s.obj.data);
                }
            }
            return structures;
        };
        class_1.prototype.update = function (p) {
            var updated = (this.params.autoAttach !== p.autoAttach ||
                this.params.showTooltip !== p.showTooltip);
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customStructureProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.register = function () {
            this.ctx.customStructureProperties.register(this.provider, this.params.autoAttach);
            this.ctx.managers.lociLabels.addProvider(this.labelProvider);
        };
        class_1.prototype.unregister = function () {
            this.ctx.customStructureProperties.unregister(this.provider.descriptor.name);
            this.ctx.managers.lociLabels.removeProvider(this.labelProvider);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler)),
    params: function () { return ({
        autoAttach: param_definition["ParamDefinition"].Boolean(false),
        showTooltip: param_definition["ParamDefinition"].Boolean(true)
    }); }
});
//# sourceMappingURL=valence-model.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/common/property.js
var property = __webpack_require__(188);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/integrative/cross-link-restraint/format.js
/**
 * Copyright (c) 2018-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var format_ModelCrossLinkRestraint;
(function (ModelCrossLinkRestraint) {
    ModelCrossLinkRestraint.Descriptor = {
        name: 'ihm_cross_link_restraint',
    };
    ModelCrossLinkRestraint.Provider = property["a" /* FormatPropertyProvider */].create(ModelCrossLinkRestraint.Descriptor);
    function fromTable(table, model) {
        var p1 = {
            entity_id: table.entity_id_1,
            asym_id: table.asym_id_1,
            seq_id: table.seq_id_1,
            atom_id: table.atom_id_1,
        };
        var p2 = {
            entity_id: table.entity_id_2,
            asym_id: table.asym_id_2,
            seq_id: table.seq_id_2,
            atom_id: table.atom_id_2,
        };
        function _add(map, element, row) {
            var indices = map.get(element);
            if (indices)
                indices.push(row);
            else
                map.set(element, [row]);
        }
        function add(row, ps) {
            var entityId = ps.entity_id.value(row);
            var asymId = ps.asym_id.value(row);
            var seqId = ps.seq_id.value(row);
            if (table.model_granularity.value(row) === 'by-atom') {
                var atomicElement = model.atomicHierarchy.index.findAtom({
                    auth_seq_id: seqId,
                    label_asym_id: asymId,
                    label_atom_id: ps.atom_id.value(row),
                    label_entity_id: entityId,
                });
                if (atomicElement >= 0)
                    _add(atomicElementMap, atomicElement, row);
            }
            else if (model.coarseHierarchy.isDefined) {
                var sphereElement = model.coarseHierarchy.spheres.findSequenceKey(entityId, asymId, seqId);
                if (sphereElement >= 0) {
                    _add(sphereElementMap, sphereElement, row);
                }
                else {
                    var gaussianElement = model.coarseHierarchy.gaussians.findSequenceKey(entityId, asymId, seqId);
                    if (gaussianElement >= 0)
                        _add(gaussianElementMap, gaussianElement, row);
                }
            }
        }
        function getMapByKind(kind) {
            switch (kind) {
                case 0 /* Atomic */: return atomicElementMap;
                case 1 /* Spheres */: return sphereElementMap;
                case 2 /* Gaussians */: return gaussianElementMap;
            }
        }
        /** map from atomic element to cross link indices */
        var atomicElementMap = new Map();
        /** map from sphere element to cross link indices */
        var sphereElementMap = new Map();
        /** map from gaussian element to cross link indices */
        var gaussianElementMap = new Map();
        var emptyIndexArray = [];
        for (var i = 0; i < table._rowCount; ++i) {
            add(i, p1);
            add(i, p2);
        }
        return {
            getIndicesByElement: function (element, kind) {
                var map = getMapByKind(kind);
                var idx = map.get(element);
                return idx !== undefined ? idx : emptyIndexArray;
            },
            data: table
        };
    }
    ModelCrossLinkRestraint.fromTable = fromTable;
})(format_ModelCrossLinkRestraint || (format_ModelCrossLinkRestraint = {}));
//# sourceMappingURL=format.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var mol_repr_representation = __webpack_require__(40);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/location-iterator.js
var location_iterator = __webpack_require__(86);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/link.js
var util_link = __webpack_require__(63);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/complex-visual.js
var complex_visual = __webpack_require__(110);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation.js
var structure_representation = __webpack_require__(54);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/integrative/pair-restraints.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var emptyArray = [];
function getPairKey(indexA, unitA, indexB, unitB) {
    return indexA + "|" + unitA.id + "|" + indexB + "|" + unitB.id;
}
var PairRestraints = /** @class */ (function () {
    function PairRestraints(pairs) {
        this.pairs = pairs;
        var pairKeyIndices = new Map();
        this.pairs.forEach(function (p, i) {
            var key = getPairKey(p.indexA, p.unitA, p.indexB, p.unitB);
            var indices = pairKeyIndices.get(key);
            if (indices)
                indices.push(i);
            else
                pairKeyIndices.set(key, [i]);
        });
        this.count = pairs.length;
        this.pairKeyIndices = pairKeyIndices;
    }
    /** Indices into this.pairs */
    PairRestraints.prototype.getPairIndices = function (indexA, unitA, indexB, unitB) {
        var key = getPairKey(indexA, unitA, indexB, unitB);
        return this.pairKeyIndices.get(key) || emptyArray;
    };
    PairRestraints.prototype.getPairs = function (indexA, unitA, indexB, unitB) {
        var _this = this;
        var indices = this.getPairIndices(indexA, unitA, indexB, unitB);
        return indices.map(function (idx) { return _this.pairs[idx]; });
    };
    return PairRestraints;
}());

//# sourceMappingURL=pair-restraints.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/location.js
var mol_model_location = __webpack_require__(144);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/centroid-helper.js
var centroid_helper = __webpack_require__(195);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/integrative/cross-link-restraint/property.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var CrossLinkRestraintProvider = custom_structure_property["a" /* CustomStructureProperty */].createProvider({
    label: 'Cross Link Restraint',
    descriptor: Object(custom_property["CustomPropertyDescriptor"])({
        name: 'integrative-cross-link-restraint',
    }),
    type: 'local',
    defaultParams: {},
    getParams: function (data) { return ({}); },
    isApplicable: function (data) { return data.models.some(function (m) { return !!format_ModelCrossLinkRestraint.Provider.get(m); }); },
    obtain: function (ctx, data, props) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, { value: extractCrossLinkRestraints(data) }];
        });
    }); }
});

var property_CrossLinkRestraint;
(function (CrossLinkRestraint) {
    var Tag;
    (function (Tag) {
        Tag["CrossLinkRestraint"] = "cross-link-restraint";
    })(Tag = CrossLinkRestraint.Tag || (CrossLinkRestraint.Tag = {}));
    function isApplicable(structure) {
        return structure.models.some(function (m) { return !!format_ModelCrossLinkRestraint.Provider.get(m); });
    }
    CrossLinkRestraint.isApplicable = isApplicable;
    var distVecA = Object(linear_algebra["Vec3"])(), distVecB = Object(linear_algebra["Vec3"])();
    function distance(pair) {
        pair.unitA.conformation.position(pair.unitA.elements[pair.indexA], distVecA);
        pair.unitB.conformation.position(pair.unitB.elements[pair.indexB], distVecB);
        return linear_algebra["Vec3"].distance(distVecA, distVecB);
    }
    CrossLinkRestraint.distance = distance;
    function Location(crossLinkRestraints, structure, index) {
        return Object(mol_model_location["a" /* DataLocation */])('cross-link-restraints', { structure: structure, crossLinkRestraints: crossLinkRestraints }, index);
    }
    CrossLinkRestraint.Location = Location;
    function isLocation(x) {
        return !!x && x.kind === 'data-location' && x.tag === 'cross-link-restraints';
    }
    CrossLinkRestraint.isLocation = isLocation;
    function areLocationsEqual(locA, locB) {
        return (locA.data.structure === locB.data.structure &&
            locA.data.crossLinkRestraints === locB.data.crossLinkRestraints &&
            locA.element === locB.element);
    }
    CrossLinkRestraint.areLocationsEqual = areLocationsEqual;
    function _label(crossLinkRestraints, element) {
        var p = crossLinkRestraints.pairs[element];
        return "Cross Link Restraint | Type: " + p.restraintType + " | Threshold: " + p.distanceThreshold + " \u212B | Psi: " + p.psi + " | Sigma 1: " + p.sigma1 + " | Sigma 2: " + p.sigma2 + " | Distance: " + distance(p).toFixed(2) + " \u212B";
    }
    function locationLabel(location) {
        return _label(location.data.crossLinkRestraints, location.element);
    }
    CrossLinkRestraint.locationLabel = locationLabel;
    function Loci(structure, crossLinkRestraints, elements) {
        return Object(mol_model_loci["DataLoci"])('cross-link-restraints', { structure: structure, crossLinkRestraints: crossLinkRestraints }, elements, function (boundingSphere) { return getBoundingSphere(crossLinkRestraints, elements, boundingSphere); }, function () { return getLabel(structure, crossLinkRestraints, elements); });
    }
    CrossLinkRestraint.Loci = Loci;
    function isLoci(x) {
        return !!x && x.kind === 'data-loci' && x.tag === 'interactions';
    }
    CrossLinkRestraint.isLoci = isLoci;
    function getBoundingSphere(crossLinkRestraints, elements, boundingSphere) {
        return centroid_helper["a" /* CentroidHelper */].fromPairProvider(elements.length, function (i, pA, pB) {
            var p = crossLinkRestraints.pairs[elements[i]];
            p.unitA.conformation.position(p.unitA.elements[p.indexA], pA);
            p.unitB.conformation.position(p.unitB.elements[p.indexB], pB);
        }, boundingSphere);
    }
    CrossLinkRestraint.getBoundingSphere = getBoundingSphere;
    function getLabel(structure, crossLinkRestraints, elements) {
        var element = elements[0];
        if (element === undefined)
            return '';
        var p = crossLinkRestraints.pairs[element];
        return [
            _label(crossLinkRestraints, element),
            Object(mol_theme_label["bondLabel"])(mol_model_structure["Bond"].Location(structure, p.unitA, p.indexA, structure, p.unitB, p.indexB))
        ].join('</br>');
    }
    CrossLinkRestraint.getLabel = getLabel;
})(property_CrossLinkRestraint || (property_CrossLinkRestraint = {}));
//
function _addRestraints(map, unit, restraints) {
    var elements = unit.elements;
    var elementCount = elements.length;
    var kind = unit.kind;
    var _loop_1 = function (i) {
        var e = elements[i];
        restraints.getIndicesByElement(e, kind).forEach(function (ri) { return map.set(ri, i); });
    };
    for (var i = 0; i < elementCount; i++) {
        _loop_1(i);
    }
}
function extractInter(pairs, unitA, unitB) {
    if (unitA.model !== unitB.model)
        return;
    if (unitA.model.sourceData.kind !== 'mmCIF')
        return;
    var restraints = format_ModelCrossLinkRestraint.Provider.get(unitA.model);
    if (!restraints)
        return;
    var rA = new Map();
    var rB = new Map();
    _addRestraints(rA, unitA, restraints);
    _addRestraints(rB, unitB, restraints);
    rA.forEach(function (indexA, ri) {
        var indexB = rB.get(ri);
        if (indexB !== undefined) {
            pairs.push(createCrossLinkRestraint(unitA, indexA, unitB, indexB, restraints, ri), createCrossLinkRestraint(unitB, indexB, unitA, indexA, restraints, ri));
        }
    });
}
function extractIntra(pairs, unit) {
    if (unit.model.sourceData.kind !== 'mmCIF')
        return;
    var restraints = format_ModelCrossLinkRestraint.Provider.get(unit.model);
    if (!restraints)
        return;
    var elements = unit.elements;
    var elementCount = elements.length;
    var kind = unit.kind;
    var r = new Map();
    var _loop_2 = function (i) {
        var e = elements[i];
        restraints.getIndicesByElement(e, kind).forEach(function (ri) {
            var il = r.get(ri);
            if (il)
                il.push(i);
            else
                r.set(ri, [i]);
        });
    };
    for (var i = 0; i < elementCount; i++) {
        _loop_2(i);
    }
    r.forEach(function (il, ri) {
        if (il.length < 2)
            return;
        var indexA = il[0], indexB = il[1];
        pairs.push(createCrossLinkRestraint(unit, indexA, unit, indexB, restraints, ri), createCrossLinkRestraint(unit, indexB, unit, indexA, restraints, ri));
    });
}
function createCrossLinkRestraint(unitA, indexA, unitB, indexB, restraints, row) {
    return {
        unitA: unitA, indexA: indexA, unitB: unitB, indexB: indexB,
        restraintType: restraints.data.restraint_type.value(row),
        distanceThreshold: restraints.data.distance_threshold.value(row),
        psi: restraints.data.psi.value(row),
        sigma1: restraints.data.sigma_1.value(row),
        sigma2: restraints.data.sigma_2.value(row),
    };
}
function extractCrossLinkRestraints(structure) {
    var pairs = [];
    if (!structure.models.some(function (m) { return format_ModelCrossLinkRestraint.Provider.get(m); })) {
        return new PairRestraints(pairs);
    }
    var n = structure.units.length;
    for (var i = 0; i < n; ++i) {
        var unitA = structure.units[i];
        extractIntra(pairs, unitA);
        for (var j = i + 1; j < n; ++j) {
            var unitB = structure.units[j];
            if (unitA.model === unitB.model) {
                extractInter(pairs, unitA, unitB);
            }
        }
    }
    return new PairRestraints(pairs);
}
//# sourceMappingURL=property.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/integrative/cross-link-restraint/representation.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function createCrossLinkRestraintCylinderMesh(ctx, structure, theme, props, mesh) {
    var crossLinks = CrossLinkRestraintProvider.get(structure).value;
    if (!crossLinks.count)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var builderProps = {
        linkCount: crossLinks.count,
        position: function (posA, posB, edgeIndex) {
            var b = crossLinks.pairs[edgeIndex];
            var uA = b.unitA, uB = b.unitB;
            uA.conformation.position(uA.elements[b.indexA], posA);
            uB.conformation.position(uB.elements[b.indexB], posB);
        },
        radius: function (edgeIndex) {
            var b = crossLinks.pairs[edgeIndex];
            location.unit = b.unitA;
            location.element = b.unitA.elements[b.indexA];
            return theme.size.size(location) * sizeFactor;
        },
    };
    return Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
}
var CrossLinkRestraintCylinderParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["c" /* ComplexMeshParams */]), util_link["a" /* LinkCylinderParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 10, step: 0.1 }) });
function CrossLinkRestraintVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(CrossLinkRestraintCylinderParams),
        createGeometry: createCrossLinkRestraintCylinderMesh,
        createLocationIterator: createCrossLinkRestraintIterator,
        getLoci: getLinkLoci,
        eachLocation: eachCrossLink,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.linkCap !== currentProps.linkCap);
        }
    }, materialId);
}
function createCrossLinkRestraintIterator(structure) {
    var crossLinkRestraints = CrossLinkRestraintProvider.get(structure).value;
    var pairs = crossLinkRestraints.pairs;
    var groupCount = pairs.length;
    var instanceCount = 1;
    var location = property_CrossLinkRestraint.Location(crossLinkRestraints, structure);
    var getLocation = function (groupIndex) {
        location.element = groupIndex;
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
}
function getLinkLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var crossLinkRestraints = CrossLinkRestraintProvider.get(structure).value;
        var pair = crossLinkRestraints.pairs[groupId];
        if (pair) {
            return property_CrossLinkRestraint.Loci(structure, crossLinkRestraints, [groupId]);
        }
    }
    return mol_model_loci["EmptyLoci"];
}
function eachCrossLink(loci, structure, apply) {
    var changed = false;
    if (property_CrossLinkRestraint.isLoci(loci)) {
        if (!mol_model_structure["Structure"].areEquivalent(loci.data.structure, structure))
            return false;
        var crossLinkRestraints = CrossLinkRestraintProvider.get(structure).value;
        if (loci.data.crossLinkRestraints !== crossLinkRestraints)
            return false;
        for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
            var e = _a[_i];
            if (apply(mol_data_int["Interval"].ofSingleton(e)))
                changed = true;
        }
    }
    return changed;
}
//
var CrossLinkRestraintVisuals = {
    'cross-link-restraint': function (ctx, getParams) { return Object(structure_representation["a" /* ComplexRepresentation */])('Cross-link restraint', ctx, getParams, CrossLinkRestraintVisual); },
};
var CrossLinkRestraintParams = Object(tslib_es6["__assign"])({}, CrossLinkRestraintCylinderParams);
function getCrossLinkRestraintParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(CrossLinkRestraintParams);
}
function CrossLinkRestraintRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('CrossLinkRestraint', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], CrossLinkRestraintVisuals);
}
var CrossLinkRestraintRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: property_CrossLinkRestraint.Tag.CrossLinkRestraint,
    label: 'Cross Link Restraint',
    description: 'Displays cross-link restraints.',
    factory: CrossLinkRestraintRepresentation,
    getParams: getCrossLinkRestraintParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(CrossLinkRestraintParams),
    defaultColorTheme: { name: property_CrossLinkRestraint.Tag.CrossLinkRestraint },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return property_CrossLinkRestraint.isApplicable(structure); },
    ensureCustomProperties: {
        attach: function (ctx, structure) { return CrossLinkRestraintProvider.attach(ctx, structure, void 0, true); },
        detach: function (data) { return CrossLinkRestraintProvider.ref(data, false); }
    }
});
//# sourceMappingURL=representation.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/integrative/cross-link-restraint/color.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var color_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var color_Description = 'Colors cross-links by the deviation of the observed distance versus the modeled distance (e.g. modeled / `ihm_cross_link_restraint.distance_threshold`).';
var CrossLinkColorThemeParams = {
    domain: param_definition["ParamDefinition"].Interval([0.5, 1.5], { step: 0.01 }),
    list: param_definition["ParamDefinition"].ColorList('red-grey', { presetKind: 'scale' }),
};
function getCrossLinkColorThemeParams(ctx) {
    return CrossLinkColorThemeParams; // TODO return copy
}
function CrossLinkColorTheme(ctx, props) {
    var color;
    var scale = undefined;
    var crossLinkRestraints = ctx.structure && CrossLinkRestraintProvider.get(ctx.structure).value;
    if (crossLinkRestraints) {
        scale = mol_util_color["ColorScale"].create({
            domain: props.domain,
            listOrName: props.list.colors
        });
        var scaleColor_1 = scale.color;
        color = function (location) {
            if (property_CrossLinkRestraint.isLocation(location)) {
                var pair = crossLinkRestraints.pairs[location.element];
                if (pair) {
                    return scaleColor_1(property_CrossLinkRestraint.distance(pair) / pair.distanceThreshold);
                }
            }
            return color_DefaultColor;
        };
    }
    else {
        color = function () { return color_DefaultColor; };
    }
    return {
        factory: CrossLinkColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: color_Description,
        legend: scale ? scale.legend : undefined
    };
}
var CrossLinkColorThemeProvider = {
    name: 'cross-link',
    label: 'Cross Link',
    category: "Miscellaneous" /* Misc */,
    factory: CrossLinkColorTheme,
    getParams: getCrossLinkColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(CrossLinkColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure && property_CrossLinkRestraint.isApplicable(ctx.structure); },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? CrossLinkRestraintProvider.attach(ctx, data.structure, void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.customPropertyDescriptors.reference(CrossLinkRestraintProvider.descriptor, false); }
    }
};
//# sourceMappingURL=color.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props/integrative/cross-link-restraint.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var cross_link_restraint_CrossLinkRestraint = behavior["PluginBehavior"].create({
    name: 'integrative-cross-link-restraint',
    category: 'custom-props',
    display: { name: 'Cross Link Restraint' },
    ctor: /** @class */ (function (_super) {
        Object(tslib_es6["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = format_ModelCrossLinkRestraint.Provider;
            return _this;
        }
        class_1.prototype.register = function () {
            this.provider.formatRegistry.add('mmCIF', crossLinkRestraintFromMmcif);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(CrossLinkColorThemeProvider);
            this.ctx.representation.structure.registry.add(CrossLinkRestraintRepresentationProvider);
        };
        class_1.prototype.unregister = function () {
            this.provider.formatRegistry.remove('mmCIF');
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(CrossLinkColorThemeProvider);
            this.ctx.representation.structure.registry.remove(CrossLinkRestraintRepresentationProvider);
        };
        return class_1;
    }(behavior["PluginBehavior"].Handler))
});
function crossLinkRestraintFromMmcif(model) {
    if (!mmcif["MmcifFormat"].is(model.sourceData))
        return;
    var ihm_cross_link_restraint = model.sourceData.data.db.ihm_cross_link_restraint;
    if (ihm_cross_link_restraint._rowCount === 0)
        return;
    return format_ModelCrossLinkRestraint.fromTable(ihm_cross_link_restraint, model);
}
//# sourceMappingURL=cross-link-restraint.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/custom-props.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






//# sourceMappingURL=custom-props.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var BuiltInPluginBehaviors = {
    State: static_state,
    Representation: representation_namespaceObject,
    Camera: camera_namespaceObject,
    Misc: misc_namespaceObject
};
var PluginBehaviors = {
    Representation: representation,
    Camera: dynamic_camera_namespaceObject,
    CustomProps: custom_props_namespaceObject
};
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 171 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ int_adjacency_graph_IntAdjacencyGraph; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/graph/int-adjacency-graph.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var int_adjacency_graph_IntAdjacencyGraph;
(function (IntAdjacencyGraph) {
    var IntGraphImpl = /** @class */ (function () {
        function IntGraphImpl(offset, a, b, edgeCount, edgeProps) {
            this.offset = offset;
            this.a = a;
            this.b = b;
            this.edgeCount = edgeCount;
            this.vertexCount = offset.length - 1;
            this.edgeProps = (edgeProps || {});
        }
        IntGraphImpl.prototype.getEdgeIndex = function (i, j) {
            var a, b;
            if (i < j) {
                a = i;
                b = j;
            }
            else {
                a = j;
                b = i;
            }
            for (var t = this.offset[a], _t = this.offset[a + 1]; t < _t; t++) {
                if (this.b[t] === b)
                    return t;
            }
            return -1;
        };
        IntGraphImpl.prototype.getDirectedEdgeIndex = function (i, j) {
            for (var t = this.offset[i], _t = this.offset[i + 1]; t < _t; t++) {
                if (this.b[t] === j)
                    return t;
            }
            return -1;
        };
        IntGraphImpl.prototype.getVertexEdgeCount = function (i) {
            return this.offset[i + 1] - this.offset[i];
        };
        return IntGraphImpl;
    }());
    function create(offset, a, b, edgeCount, edgeProps) {
        return new IntGraphImpl(offset, a, b, edgeCount, edgeProps);
    }
    IntAdjacencyGraph.create = create;
    var EdgeBuilder = /** @class */ (function () {
        function EdgeBuilder(vertexCount, xs, ys) {
            this.vertexCount = vertexCount;
            this.xs = xs;
            this.ys = ys;
            this.current = 0;
            this.curA = 0;
            this.curB = 0;
            this.edgeCount = xs.length;
            this.offsets = new Int32Array(this.vertexCount + 1);
            this.bucketFill = new Int32Array(this.vertexCount);
            var bucketSizes = new Int32Array(this.vertexCount);
            for (var i = 0, _i = this.xs.length; i < _i; i++)
                bucketSizes[this.xs[i]]++;
            for (var i = 0, _i = this.ys.length; i < _i; i++)
                bucketSizes[this.ys[i]]++;
            var offset = 0;
            for (var i = 0; i < this.vertexCount; i++) {
                this.offsets[i] = offset;
                offset += bucketSizes[i];
            }
            this.offsets[this.vertexCount] = offset;
            this.slotCount = offset;
            this.a = new Int32Array(offset);
            this.b = new Int32Array(offset);
        }
        EdgeBuilder.prototype.createGraph = function (edgeProps) {
            return create(this.offsets, this.a, this.b, this.edgeCount, edgeProps);
        };
        /**
         * @example
         *   const property = new Int32Array(builder.slotCount);
         *   for (let i = 0; i < builder.edgeCount; i++) {
         *     builder.addNextEdge();
         *     builder.assignProperty(property, srcProp[i]);
         *   }
         *   return builder.createGraph({ property });
         */
        EdgeBuilder.prototype.addNextEdge = function () {
            var a = this.xs[this.current], b = this.ys[this.current];
            var oa = this.offsets[a] + this.bucketFill[a];
            var ob = this.offsets[b] + this.bucketFill[b];
            this.a[oa] = a;
            this.b[oa] = b;
            this.bucketFill[a]++;
            this.a[ob] = b;
            this.b[ob] = a;
            this.bucketFill[b]++;
            this.current++;
            this.curA = oa;
            this.curB = ob;
        };
        /** Builds property-less graph */
        EdgeBuilder.prototype.addAllEdges = function () {
            for (var i = 0; i < this.edgeCount; i++) {
                this.addNextEdge();
            }
        };
        EdgeBuilder.prototype.assignProperty = function (prop, value) {
            prop[this.curA] = value;
            prop[this.curB] = value;
        };
        return EdgeBuilder;
    }());
    IntAdjacencyGraph.EdgeBuilder = EdgeBuilder;
    var DirectedEdgeBuilder = /** @class */ (function () {
        function DirectedEdgeBuilder(vertexCount, xs, ys) {
            this.vertexCount = vertexCount;
            this.xs = xs;
            this.ys = ys;
            this.current = 0;
            this.curA = 0;
            this.edgeCount = xs.length;
            this.offsets = new Int32Array(this.vertexCount + 1);
            this.bucketFill = new Int32Array(this.vertexCount);
            var bucketSizes = new Int32Array(this.vertexCount);
            for (var i = 0, _i = this.xs.length; i < _i; i++)
                bucketSizes[this.xs[i]]++;
            var offset = 0;
            for (var i = 0; i < this.vertexCount; i++) {
                this.offsets[i] = offset;
                offset += bucketSizes[i];
            }
            this.offsets[this.vertexCount] = offset;
            this.slotCount = offset;
            this.a = new Int32Array(offset);
            this.b = new Int32Array(offset);
        }
        DirectedEdgeBuilder.prototype.createGraph = function (edgeProps) {
            return create(this.offsets, this.a, this.b, this.edgeCount, edgeProps);
        };
        /**
         * @example
         *   const property = new Int32Array(builder.slotCount);
         *   for (let i = 0; i < builder.edgeCount; i++) {
         *     builder.addNextEdge();
         *     builder.assignProperty(property, srcProp[i]);
         *   }
         *   return builder.createGraph({ property });
         */
        DirectedEdgeBuilder.prototype.addNextEdge = function () {
            var a = this.xs[this.current], b = this.ys[this.current];
            var oa = this.offsets[a] + this.bucketFill[a];
            this.a[oa] = a;
            this.b[oa] = b;
            this.bucketFill[a]++;
            this.current++;
            this.curA = oa;
        };
        /** Builds property-less graph */
        DirectedEdgeBuilder.prototype.addAllEdges = function () {
            for (var i = 0; i < this.edgeCount; i++) {
                this.addNextEdge();
            }
        };
        DirectedEdgeBuilder.prototype.assignProperty = function (prop, value) {
            prop[this.curA] = value;
        };
        return DirectedEdgeBuilder;
    }());
    IntAdjacencyGraph.DirectedEdgeBuilder = DirectedEdgeBuilder;
    var UniqueEdgeBuilder = /** @class */ (function () {
        function UniqueEdgeBuilder(vertexCount) {
            this.vertexCount = vertexCount;
            this.xs = [];
            this.ys = [];
            this.included = new Set();
        }
        UniqueEdgeBuilder.prototype.addEdge = function (i, j) {
            var u = i, v = j;
            if (i > j) {
                u = j;
                v = i;
            }
            var id = Object(util["f" /* cantorPairing */])(u, v);
            if (this.included.has(id))
                return false;
            this.included.add(id);
            this.xs[this.xs.length] = u;
            this.ys[this.ys.length] = v;
            return true;
        };
        UniqueEdgeBuilder.prototype.getGraph = function () {
            return fromVertexPairs(this.vertexCount, this.xs, this.ys);
        };
        // if we cant to add custom props as well
        UniqueEdgeBuilder.prototype.getEdgeBuiler = function () {
            return new EdgeBuilder(this.vertexCount, this.xs, this.ys);
        };
        return UniqueEdgeBuilder;
    }());
    IntAdjacencyGraph.UniqueEdgeBuilder = UniqueEdgeBuilder;
    function fromVertexPairs(vertexCount, xs, ys) {
        var graphBuilder = new IntAdjacencyGraph.EdgeBuilder(vertexCount, xs, ys);
        graphBuilder.addAllEdges();
        return graphBuilder.createGraph({});
    }
    IntAdjacencyGraph.fromVertexPairs = fromVertexPairs;
    function induceByVertices(graph, vertexIndices) {
        var b = graph.b, offset = graph.offset, vertexCount = graph.vertexCount, edgeProps = graph.edgeProps;
        var vertexMap = new Int32Array(vertexCount);
        for (var i = 0, _i = vertexIndices.length; i < _i; i++)
            vertexMap[vertexIndices[i]] = i + 1;
        var newEdgeCount = 0;
        for (var i = 0; i < vertexCount; i++) {
            if (vertexMap[i] === 0)
                continue;
            for (var j = offset[i], _j = offset[i + 1]; j < _j; j++) {
                if (b[j] > i && vertexMap[b[j]] !== 0)
                    newEdgeCount++;
            }
        }
        var newOffsets = new Int32Array(vertexIndices.length + 1);
        var edgeIndices = new Int32Array(2 * newEdgeCount);
        var newA = new Int32Array(2 * newEdgeCount);
        var newB = new Int32Array(2 * newEdgeCount);
        var eo = 0, vo = 0;
        for (var i = 0; i < vertexCount; i++) {
            if (vertexMap[i] === 0)
                continue;
            var aa = vertexMap[i] - 1;
            for (var j = offset[i], _j = offset[i + 1]; j < _j; j++) {
                var bb = vertexMap[b[j]];
                if (bb === 0)
                    continue;
                newA[eo] = aa;
                newB[eo] = bb - 1;
                edgeIndices[eo] = j;
                eo++;
            }
            newOffsets[++vo] = eo;
        }
        var newEdgeProps = {};
        for (var _a = 0, _b = Object.keys(edgeProps); _a < _b.length; _a++) {
            var key = _b[_a];
            newEdgeProps[key] = Object(util["d" /* arrayPickIndices */])(edgeProps[key], edgeIndices);
        }
        return create(newOffsets, newA, newB, newEdgeCount, newEdgeProps);
    }
    IntAdjacencyGraph.induceByVertices = induceByVertices;
    function connectedComponents(graph) {
        var vCount = graph.vertexCount;
        if (vCount === 0)
            return { componentCount: 0, componentIndex: new Int32Array(0) };
        if (graph.edgeCount === 0) {
            var componentIndex_1 = new Int32Array(vCount);
            for (var i = 0, _i = vCount; i < _i; i++) {
                componentIndex_1[i] = i;
            }
            return { componentCount: vCount, componentIndex: componentIndex_1 };
        }
        var componentIndex = new Int32Array(vCount);
        for (var i = 0, _i = vCount; i < _i; i++)
            componentIndex[i] = -1;
        var currentComponent = 0;
        componentIndex[0] = currentComponent;
        var offset = graph.offset, neighbor = graph.b;
        var stack = [0];
        var list = Object(mol_data_int["LinkedIndex"])(vCount);
        list.remove(0);
        while (stack.length > 0) {
            var v = stack.pop();
            var cIdx = componentIndex[v];
            for (var eI = offset[v], _eI = offset[v + 1]; eI < _eI; eI++) {
                var n = neighbor[eI];
                if (!list.has(n))
                    continue;
                list.remove(n);
                stack.push(n);
                componentIndex[n] = cIdx;
            }
            // check if we visited all vertices.
            // If not, create a new component and continue.
            if (stack.length === 0 && list.head >= 0) {
                stack.push(list.head);
                componentIndex[list.head] = ++currentComponent;
                list.remove(list.head);
            }
        }
        return { componentCount: vCount, componentIndex: componentIndex };
    }
    IntAdjacencyGraph.connectedComponents = connectedComponents;
    /**
     * Check if any vertex in `verticesA` is connected to any vertex in `verticesB`
     * via at most `maxDistance` edges.
     *
     * Returns true if verticesA and verticesB are intersecting.
     */
    function areVertexSetsConnected(graph, verticesA, verticesB, maxDistance) {
        // check if A and B are intersecting, this handles maxDistance = 0
        if (mol_data_int["SortedArray"].areIntersecting(verticesA, verticesB))
            return true;
        if (maxDistance < 1)
            return false;
        var visited = new Set();
        for (var i = 0, il = verticesA.length; i < il; ++i) {
            visited.add(verticesA[i]);
        }
        return areVertexSetsConnectedImpl(graph, verticesA, verticesB, maxDistance, visited);
    }
    IntAdjacencyGraph.areVertexSetsConnected = areVertexSetsConnected;
})(int_adjacency_graph_IntAdjacencyGraph || (int_adjacency_graph_IntAdjacencyGraph = {}));
function areVertexSetsConnectedImpl(graph, frontier, target, distance, visited) {
    var neighbor = graph.b, offset = graph.offset;
    var newFrontier = [];
    for (var i = 0, il = frontier.length; i < il; ++i) {
        var src = frontier[i];
        for (var j = offset[src], jl = offset[src + 1]; j < jl; ++j) {
            var other = neighbor[j];
            if (visited.has(other))
                continue;
            if (mol_data_int["SortedArray"].has(target, other))
                return true;
            visited.add(other);
            newFrontier[newFrontier.length] = other;
        }
    }
    return distance > 1 ? areVertexSetsConnectedImpl(graph, newFrontier, target, distance - 1, visited) : false;
}
//# sourceMappingURL=int-adjacency-graph.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/graph.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

//# sourceMappingURL=graph.js.map

/***/ }),
/* 172 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LinesBuilder; });
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9);
/* harmony import */ var _lines__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(74);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var tmpVecA = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
var tmpVecB = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
var tmpDir = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"])();
var LinesBuilder;
(function (LinesBuilder) {
    function create(initialCount, chunkSize, lines) {
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        var mappings = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Float32Array, 2, chunkSize, lines ? lines.mappingBuffer.ref.value : initialCount);
        var groups = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Float32Array, 1, chunkSize, lines ? lines.groupBuffer.ref.value : initialCount);
        var indices = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Uint32Array, 3, chunkSize * 3, lines ? lines.indexBuffer.ref.value : initialCount * 3);
        var starts = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Float32Array, 3, chunkSize, lines ? lines.startBuffer.ref.value : initialCount);
        var ends = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].create(Float32Array, 3, chunkSize, lines ? lines.endBuffer.ref.value : initialCount);
        var add = function (startX, startY, startZ, endX, endY, endZ, group) {
            var offset = mappings.elementCount;
            for (var i = 0; i < 4; ++i) {
                _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add3(starts, startX, startY, startZ);
                _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add3(ends, endX, endY, endZ);
                _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add(groups, group);
            }
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add2(mappings, -1, 1);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add2(mappings, -1, -1);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add2(mappings, 1, 1);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add2(mappings, 1, -1);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add3(indices, offset, offset + 1, offset + 2);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].add3(indices, offset + 1, offset + 3, offset + 2);
        };
        var addFixedCountDashes = function (start, end, segmentCount, group) {
            var d = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].distance(start, end);
            var s = Math.floor(segmentCount / 2);
            var step = 1 / segmentCount;
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].sub(tmpDir, end, start);
            for (var j = 0; j < s; ++j) {
                var f = step * (j * 2 + 1);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].setMagnitude(tmpDir, tmpDir, d * f);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(tmpVecA, start, tmpDir);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].setMagnitude(tmpDir, tmpDir, d * step * ((j + 1) * 2));
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].add(tmpVecB, start, tmpDir);
                add(tmpVecA[0], tmpVecA[1], tmpVecA[2], tmpVecB[0], tmpVecB[1], tmpVecB[2], group);
            }
        };
        return {
            add: add,
            addFixedCountDashes: addFixedCountDashes,
            addFixedLengthDashes: function (start, end, segmentLength, group) {
                var d = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].distance(start, end);
                addFixedCountDashes(start, end, d / segmentLength, group);
            },
            addCage: function (t, cage, group) {
                var vertices = cage.vertices, edges = cage.edges;
                for (var i = 0, il = edges.length; i < il; i += 2) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(tmpVecA, vertices, edges[i] * 3);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].fromArray(tmpVecB, vertices, edges[i + 1] * 3);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].transformMat4(tmpVecA, tmpVecA, t);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].transformMat4(tmpVecB, tmpVecB, t);
                    add(tmpVecA[0], tmpVecA[1], tmpVecA[2], tmpVecB[0], tmpVecB[1], tmpVecB[2], group);
                }
            },
            getLines: function () {
                var mb = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(mappings, true);
                var ib = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(indices, true);
                var gb = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(groups, true);
                var sb = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(starts, true);
                var eb = _mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* ChunkedArray */ "a"].compact(ends, true);
                return _lines__WEBPACK_IMPORTED_MODULE_1__[/* Lines */ "a"].create(mb, ib, gb, sb, eb, indices.elementCount / 2, lines);
            }
        };
    }
    LinesBuilder.create = create;
})(LinesBuilder || (LinesBuilder = {}));
//# sourceMappingURL=lines-builder.js.map

/***/ }),
/* 173 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IndexPairBonds; });
/* harmony import */ var _mol_math_graph__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(171);
/* harmony import */ var _common_property__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(188);
/**
 * Copyright (c) 2019-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function getGraph(indexA, indexB, props, count) {
    var builder = new _mol_math_graph__WEBPACK_IMPORTED_MODULE_0__[/* IntAdjacencyGraph */ "a"].EdgeBuilder(count, indexA, indexB);
    var order = new Int8Array(builder.slotCount);
    var symmetryA = new Array(builder.slotCount);
    var symmetryB = new Array(builder.slotCount);
    for (var i = 0, _i = builder.edgeCount; i < _i; i++) {
        builder.addNextEdge();
        builder.assignProperty(order, props.order ? props.order[i] : 1);
        builder.assignProperty(symmetryA, props.symmetryA ? props.symmetryA[i] : '');
        builder.assignProperty(symmetryB, props.symmetryB ? props.symmetryB[i] : '');
    }
    return builder.createGraph({ order: order, symmetryA: symmetryA, symmetryB: symmetryB });
}
var IndexPairBonds;
(function (IndexPairBonds) {
    IndexPairBonds.Descriptor = {
        name: 'index_pair_bonds',
    };
    IndexPairBonds.Provider = _common_property__WEBPACK_IMPORTED_MODULE_1__[/* FormatPropertyProvider */ "a"].create(IndexPairBonds.Descriptor);
    function fromData(data) {
        var pairs = data.pairs, count = data.count;
        var indexA = pairs.indexA.toArray();
        var indexB = pairs.indexB.toArray();
        var order = pairs.order && pairs.order.toArray();
        var symmetryA = pairs.symmetryA && pairs.symmetryA.toArray();
        var symmetryB = pairs.symmetryB && pairs.symmetryB.toArray();
        return getGraph(indexA, indexB, { order: order, symmetryA: symmetryA, symmetryB: symmetryB }, count);
    }
    IndexPairBonds.fromData = fromData;
})(IndexPairBonds || (IndexPairBonds = {}));
//# sourceMappingURL=index-pair.js.map

/***/ }),
/* 174 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getMantissaMultiplier */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return integerDigitCount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getArrayDigitCount; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isInteger; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getPrecision; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return toPrecision; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * Determine the number of digits in a floating point number
 * Find a number M such that round(M * v) - M * v <= delta.
 * If no such M exists, return -1.
 */
function getMantissaMultiplier(v, maxDigits, delta) {
    var m = 1, i;
    for (i = 0; i < maxDigits; i++) {
        var mv = m * v;
        if (Math.abs(Math.round(mv) - mv) <= delta)
            return i;
        m *= 10;
    }
    return -1;
}
function integerDigitCount(v, delta) {
    var f = Math.abs(v);
    if (f < delta)
        return 0;
    return Math.floor(Math.log10(Math.abs(v))) + 1;
}
/**
 * Determine the maximum number of digits in a floating point array.
 * Find a number M such that round(M * v) - M * v <= delta.
 * If no such M exists, return -1.
 */
function getArrayDigitCount(xs, maxDigits, delta) {
    var mantissaDigits = 1;
    var integerDigits = 0;
    for (var i = 0, _i = xs.length; i < _i; i++) {
        if (mantissaDigits >= 0) {
            var t = getMantissaMultiplier(xs[i], maxDigits, delta);
            if (t < 0)
                mantissaDigits = -1;
            else if (t > mantissaDigits)
                mantissaDigits = t;
        }
        var abs = Math.abs(xs[i]);
        if (abs > delta) {
            var d = Math.floor(Math.log10(Math.abs(abs))) + 1;
            if (d > integerDigits)
                integerDigits = d;
        }
    }
    return { mantissaDigits: mantissaDigits, integerDigits: integerDigits };
}
function isInteger(s) {
    s = s.trim();
    var n = parseInt(s, 10);
    return isNaN(n) ? false : n.toString() === s;
}
function getPrecision(v) {
    if (!isFinite(v))
        return 0;
    var e = 1;
    var p = 0;
    while (Math.round(v * e) / e !== v) {
        e *= 10;
        ++p;
    }
    return p;
}
function toPrecision(v, precision) {
    return parseFloat(v.toPrecision(precision));
}
//# sourceMappingURL=number.js.map

/***/ }),
/* 175 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return config; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var _enable_super_gross_mode_that_will_cause_bad_things = false;
var config = {
    Promise: undefined,
    set useDeprecatedSynchronousErrorHandling(value) {
        if (value) {
            var error = /*@__PURE__*/ new Error();
            /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack);
        }
        else if (_enable_super_gross_mode_that_will_cause_bad_things) {
            /*@__PURE__*/ console.log('RxJS: Back to a better error behavior. Thank you. <3');
        }
        _enable_super_gross_mode_that_will_cause_bad_things = value;
    },
    get useDeprecatedSynchronousErrorHandling() {
        return _enable_super_gross_mode_that_will_cause_bad_things;
    },
};
//# sourceMappingURL=config.js.map


/***/ }),
/* 176 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Viewport; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return cameraProject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return cameraUnproject; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function Viewport() {
    return Viewport.zero();
}
(function (Viewport) {
    function zero() {
        return { x: 0, y: 0, width: 0, height: 0 };
    }
    Viewport.zero = zero;
    function create(x, y, width, height) {
        return { x: x, y: y, width: width, height: height };
    }
    Viewport.create = create;
    function clone(viewport) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, viewport);
    }
    Viewport.clone = clone;
    function copy(target, source) {
        return Object.assign(target, source);
    }
    Viewport.copy = copy;
    function set(viewport, x, y, width, height) {
        viewport.x = x;
        viewport.y = y;
        viewport.width = width;
        viewport.height = height;
        return viewport;
    }
    Viewport.set = set;
    function toVec4(v4, viewport) {
        v4[0] = viewport.x;
        v4[1] = viewport.y;
        v4[2] = viewport.width;
        v4[3] = viewport.height;
        return v4;
    }
    Viewport.toVec4 = toVec4;
    function equals(a, b) {
        return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
    }
    Viewport.equals = equals;
})(Viewport || (Viewport = {}));
//
var NEAR_RANGE = 0;
var FAR_RANGE = 1;
var tmpVec4 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec4"])();
/** Transform point into 2D window coordinates. */
function cameraProject(out, point, viewport, projectionView) {
    var vX = viewport.x, vY = viewport.y, vWidth = viewport.width, vHeight = viewport.height;
    // clip space -> NDC -> window coordinates, implicit 1.0 for w component
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec4"].set(tmpVec4, point[0], point[1], point[2], 1.0);
    // transform into clip space
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec4"].transformMat4(tmpVec4, tmpVec4, projectionView);
    // transform into NDC
    var w = tmpVec4[3];
    if (w !== 0) {
        tmpVec4[0] /= w;
        tmpVec4[1] /= w;
        tmpVec4[2] /= w;
    }
    // transform into window coordinates, set fourth component is (1/clip.w) as in gl_FragCoord.w
    out[0] = vX + vWidth / 2 * tmpVec4[0] + (0 + vWidth / 2);
    out[1] = vY + vHeight / 2 * tmpVec4[1] + (0 + vHeight / 2);
    out[2] = (FAR_RANGE - NEAR_RANGE) / 2 * tmpVec4[2] + (FAR_RANGE + NEAR_RANGE) / 2;
    out[3] = w === 0 ? 0 : 1 / w;
    return out;
}
/**
 * Transform point from screen space to 3D coordinates.
 * The point must have x and y set to 2D window coordinates and z between 0 (near) and 1 (far).
 */
function cameraUnproject(out, point, viewport, inverseProjectionView) {
    var vX = viewport.x, vY = viewport.y, vWidth = viewport.width, vHeight = viewport.height;
    var x = point[0] - vX;
    var y = (vHeight - point[1] - 1) - vY;
    var z = point[2];
    out[0] = (2 * x) / vWidth - 1;
    out[1] = (2 * y) / vHeight - 1;
    out[2] = 2 * z - 1;
    return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4(out, out, inverseProjectionView);
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 177 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export DataCompressionMethod */
/* unused harmony export readStringFromFile */
/* unused harmony export readUint8ArrayFromFile */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return readFromFile; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ajaxGet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ajaxGetMany; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _zip_zip__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(317);
/* harmony import */ var _mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(157);
/* harmony import */ var _assets__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(114);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * Adapted from LiteMol
 */





// polyfill XMLHttpRequest in node.js
var XHR = typeof document === 'undefined' ? __webpack_require__(431) : XMLHttpRequest;
var DataCompressionMethod;
(function (DataCompressionMethod) {
    DataCompressionMethod[DataCompressionMethod["None"] = 0] = "None";
    DataCompressionMethod[DataCompressionMethod["Gzip"] = 1] = "Gzip";
    DataCompressionMethod[DataCompressionMethod["Zip"] = 2] = "Zip";
})(DataCompressionMethod || (DataCompressionMethod = {}));
function readStringFromFile(file) {
    return readFromFileInternal(file, 'string');
}
function readUint8ArrayFromFile(file) {
    return readFromFileInternal(file, 'binary');
}
function readFromFile(file, type) {
    return readFromFileInternal(file, type);
}
function ajaxGet(params) {
    if (typeof params === 'string')
        return ajaxGetInternal(params, params, 'string');
    return ajaxGetInternal(params.title, params.url, params.type || 'string', params.body, params.headers);
}
function isDone(data) {
    if (data instanceof FileReader) {
        return data.readyState === FileReader.DONE;
    }
    else if (data instanceof XMLHttpRequest) {
        return data.readyState === XMLHttpRequest.DONE;
    }
    throw new Error('unknown data type');
}
function genericError(isDownload) {
    if (isDownload)
        return 'Failed to download data. Possible reasons: Resource is not available, or CORS is not allowed on the server.';
    return 'Failed to open file.';
}
function readData(ctx, action, data) {
    return new Promise(function (resolve, reject) {
        // first check if data reading is already done
        if (isDone(data)) {
            var error = data.error;
            if (error !== null && error !== undefined) {
                reject(error !== null && error !== void 0 ? error : genericError(data instanceof XMLHttpRequest));
            }
            else {
                resolve(data);
            }
            return;
        }
        var hasError = false;
        data.onerror = function (e) {
            if (hasError)
                return;
            var error = e.target.error;
            reject(error !== null && error !== void 0 ? error : genericError(data instanceof XMLHttpRequest));
        };
        data.onprogress = function (e) {
            if (!ctx.shouldUpdate || hasError)
                return;
            try {
                if (e.lengthComputable) {
                    ctx.update({ message: action, isIndeterminate: false, current: e.loaded, max: e.total });
                }
                else {
                    ctx.update({ message: action + " " + (e.loaded / 1024 / 1024).toFixed(2) + " MB", isIndeterminate: true });
                }
            }
            catch (e) {
                hasError = true;
                reject(e);
            }
        };
        data.onload = function (e) {
            resolve(data);
        };
    });
}
function getCompression(name) {
    return /\.gz$/i.test(name) ? DataCompressionMethod.Gzip :
        /\.zip$/i.test(name) ? DataCompressionMethod.Zip :
            DataCompressionMethod.None;
}
function decompress(ctx, data, compression) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var _a, parsed, names;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _a = compression;
                    switch (_a) {
                        case DataCompressionMethod.None: return [3 /*break*/, 1];
                        case DataCompressionMethod.Gzip: return [3 /*break*/, 2];
                        case DataCompressionMethod.Zip: return [3 /*break*/, 3];
                    }
                    return [3 /*break*/, 5];
                case 1: return [2 /*return*/, data];
                case 2: return [2 /*return*/, Object(_zip_zip__WEBPACK_IMPORTED_MODULE_2__[/* ungzip */ "a"])(ctx, data)];
                case 3: return [4 /*yield*/, Object(_zip_zip__WEBPACK_IMPORTED_MODULE_2__[/* unzip */ "b"])(ctx, data.buffer)];
                case 4:
                    parsed = _b.sent();
                    names = Object.keys(parsed);
                    if (names.length !== 1)
                        throw new Error('can only decompress zip files with a single entry');
                    return [2 /*return*/, parsed[names[0]]];
                case 5: return [2 /*return*/];
            }
        });
    });
}
function processFile(ctx, reader, type, compression) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var result, data, decompressed, parser;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    result = reader.result;
                    data = result instanceof ArrayBuffer ? new Uint8Array(result) : result;
                    if (data === null)
                        throw new Error('no data given');
                    if (!(compression !== DataCompressionMethod.None)) return [3 /*break*/, 4];
                    if (!(data instanceof Uint8Array))
                        throw new Error('need Uint8Array for decompression');
                    return [4 /*yield*/, decompress(ctx, data, compression)];
                case 1:
                    decompressed = _a.sent();
                    if (!(type === 'string')) return [3 /*break*/, 3];
                    return [4 /*yield*/, ctx.update({ message: 'Decoding text...' })];
                case 2:
                    _a.sent();
                    data = Object(_mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__[/* utf8Read */ "b"])(decompressed, 0, decompressed.length);
                    return [3 /*break*/, 4];
                case 3:
                    data = decompressed;
                    _a.label = 4;
                case 4:
                    if (!(type === 'binary' && data instanceof Uint8Array)) return [3 /*break*/, 5];
                    return [2 /*return*/, data];
                case 5:
                    if (!(type === 'zip' && data instanceof Uint8Array)) return [3 /*break*/, 7];
                    return [4 /*yield*/, Object(_zip_zip__WEBPACK_IMPORTED_MODULE_2__[/* unzip */ "b"])(ctx, data.buffer)];
                case 6: return [2 /*return*/, _a.sent()];
                case 7:
                    if (type === 'string' && typeof data === 'string') {
                        return [2 /*return*/, data];
                    }
                    else if (type === 'xml' && typeof data === 'string') {
                        parser = new DOMParser();
                        return [2 /*return*/, parser.parseFromString(data, 'application/xml')];
                    }
                    else if (type === 'json' && typeof data === 'string') {
                        return [2 /*return*/, JSON.parse(data)];
                    }
                    _a.label = 8;
                case 8: throw new Error("could not get requested response data '" + type + "'");
            }
        });
    });
}
function readFromFileInternal(file, type) {
    var _this = this;
    var reader = void 0;
    return _mol_task__WEBPACK_IMPORTED_MODULE_1__[/* Task */ "b"].create('Read File', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var compression, fileReader;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, , 5, 6]);
                    reader = new FileReader();
                    compression = type === 'zip' ? DataCompressionMethod.None : getCompression(file.name);
                    if (type === 'binary' || type === 'zip' || compression !== DataCompressionMethod.None) {
                        reader.readAsArrayBuffer(file);
                    }
                    else {
                        reader.readAsText(file);
                    }
                    return [4 /*yield*/, ctx.update({ message: 'Opening file...', canAbort: true })];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, readData(ctx, 'Reading...', reader)];
                case 2:
                    fileReader = _a.sent();
                    return [4 /*yield*/, ctx.update({ message: 'Processing file...', canAbort: false })];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, processFile(ctx, fileReader, type, compression)];
                case 4: return [2 /*return*/, _a.sent()];
                case 5:
                    reader = void 0;
                    return [7 /*endfinally*/];
                case 6: return [2 /*return*/];
            }
        });
    }); }, function () {
        if (reader)
            reader.abort();
    });
}
var RequestPool = /** @class */ (function () {
    function RequestPool() {
    }
    RequestPool.get = function () {
        if (this.pool.length) {
            return this.pool.pop();
        }
        return new XHR();
    };
    RequestPool.emptyFunc = function () { };
    RequestPool.deposit = function (req) {
        if (this.pool.length < this.poolSize) {
            req.onabort = RequestPool.emptyFunc;
            req.onerror = RequestPool.emptyFunc;
            req.onload = RequestPool.emptyFunc;
            req.onprogress = RequestPool.emptyFunc;
            this.pool.push(req);
        }
    };
    RequestPool.pool = [];
    RequestPool.poolSize = 15;
    return RequestPool;
}());
function processAjax(req, type) {
    if (req.status >= 200 && req.status < 400) {
        var response = req.response;
        RequestPool.deposit(req);
        if ((type === 'binary' || type === 'zip') && response instanceof ArrayBuffer) {
            return new Uint8Array(response);
        }
        else if (type === 'string' && typeof response === 'string') {
            return response;
        }
        else if (type === 'xml' && response instanceof XMLDocument) {
            return response;
        }
        else if (type === 'json' && typeof response === 'object') {
            return response;
        }
        throw new Error("could not get requested response data '" + type + "'");
    }
    else {
        RequestPool.deposit(req);
        throw new Error("Download failed with status code " + req.status);
    }
}
function getRequestResponseType(type) {
    switch (type) {
        case 'json': return 'json';
        case 'xml': return 'document';
        case 'string': return 'text';
        case 'binary': return 'arraybuffer';
        case 'zip': return 'arraybuffer';
    }
}
function ajaxGetInternal(title, url, type, body, headers) {
    var _this = this;
    var xhttp = void 0;
    return _mol_task__WEBPACK_IMPORTED_MODULE_1__[/* Task */ "b"].create(title ? title : 'Download', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var _a, headers_1, _b, name_1, value, req, result;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    xhttp = RequestPool.get();
                    xhttp.open(body ? 'post' : 'get', url, true);
                    if (headers) {
                        for (_a = 0, headers_1 = headers; _a < headers_1.length; _a++) {
                            _b = headers_1[_a], name_1 = _b[0], value = _b[1];
                            xhttp.setRequestHeader(name_1, value);
                        }
                    }
                    xhttp.responseType = getRequestResponseType(type);
                    xhttp.send(body);
                    return [4 /*yield*/, ctx.update({ message: 'Waiting for server...', canAbort: true })];
                case 1:
                    _c.sent();
                    return [4 /*yield*/, readData(ctx, 'Downloading...', xhttp)];
                case 2:
                    req = _c.sent();
                    xhttp = void 0; // guard against reuse, help garbage collector
                    return [4 /*yield*/, ctx.update({ message: 'Parsing response...', canAbort: false })];
                case 3:
                    _c.sent();
                    result = processAjax(req, type);
                    return [2 /*return*/, result];
            }
        });
    }); }, function () {
        if (xhttp) {
            xhttp.abort();
            xhttp = void 0; // guard against reuse, help garbage collector
        }
    });
}
function ajaxGetMany(ctx, assetManager, sources, maxConcurrency) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var len, slots, promises, promiseKeys, currentSrc, _i, current, done, r, src, idx, current, asset;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    len = sources.length;
                    slots = new Array(sources.length);
                    return [4 /*yield*/, ctx.update({ message: 'Downloading...', current: 0, max: len })];
                case 1:
                    _a.sent();
                    promises = [], promiseKeys = [];
                    currentSrc = 0;
                    for (_i = Math.min(len, maxConcurrency); currentSrc < _i; currentSrc++) {
                        current = sources[currentSrc];
                        promises.push(wrapPromise(currentSrc, current.id, assetManager.resolve(_assets__WEBPACK_IMPORTED_MODULE_4__["Asset"].getUrlAsset(assetManager, current.url), current.isBinary ? 'binary' : 'string').runAsChild(ctx)));
                        promiseKeys.push(currentSrc);
                    }
                    done = 0;
                    _a.label = 2;
                case 2:
                    if (!(promises.length > 0)) return [3 /*break*/, 6];
                    return [4 /*yield*/, Promise.race(promises)];
                case 3:
                    r = _a.sent();
                    src = sources[r.index];
                    idx = promiseKeys.indexOf(r.index);
                    done++;
                    if (r.kind === 'error' && !src.canFail) {
                        // TODO: cancel other downloads
                        throw new Error(src.url + ": " + r.error);
                    }
                    if (!ctx.shouldUpdate) return [3 /*break*/, 5];
                    return [4 /*yield*/, ctx.update({ message: 'Downloading...', current: done, max: len })];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    slots[r.index] = r;
                    promises = promises.filter(_filterRemoveIndex, idx);
                    promiseKeys = promiseKeys.filter(_filterRemoveIndex, idx);
                    if (currentSrc < len) {
                        current = sources[currentSrc];
                        asset = assetManager.resolve(_assets__WEBPACK_IMPORTED_MODULE_4__["Asset"].getUrlAsset(assetManager, current.url), current.isBinary ? 'binary' : 'string').runAsChild(ctx);
                        promises.push(wrapPromise(currentSrc, current.id, asset));
                        promiseKeys.push(currentSrc);
                        currentSrc++;
                    }
                    return [3 /*break*/, 2];
                case 6: return [2 /*return*/, slots];
            }
        });
    });
}
function _filterRemoveIndex(_, i) {
    return this !== i;
}
function wrapPromise(index, id, p) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var result, error_1;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    return [4 /*yield*/, p];
                case 1:
                    result = _a.sent();
                    return [2 /*return*/, { kind: 'ok', result: result, index: index, id: id }];
                case 2:
                    error_1 = _a.sent();
                    return [2 /*return*/, { kind: 'error', error: error_1, index: index, id: id }];
                case 3: return [2 /*return*/];
            }
        });
    });
}
//# sourceMappingURL=data-source.js.map

/***/ }),
/* 178 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return SaccharideColors; });
/* unused harmony export getSaccharideName */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return getSaccharideShape; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return UnknownSaccharideComponent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return SaccharidesSnfgMap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MonosaccharidesColorTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return SaccharideCompIdMap; });
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var _a, _b;

var SaccharideColors = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["ColorMap"])({
    Blue: 0x0090bc,
    Green: 0x00a651,
    Yellow: 0xffd400,
    Orange: 0xf47920,
    Pink: 0xf69ea1,
    Purple: 0xa54399,
    LightBlue: 0x8fcce9,
    Brown: 0xa17a4d,
    Red: 0xed1c24,
    Secondary: 0xf1ece1
});
var SaccharideTypeNameMap = (_a = {},
    _a[0 /* Hexose */] = 'Hexose',
    _a[1 /* HexNAc */] = 'HexNAc',
    _a[2 /* Hexosamine */] = 'Hexosamine',
    _a[3 /* Hexuronate */] = 'Hexuronate',
    _a[4 /* Deoxyhexose */] = 'Deoxyhexose',
    _a[5 /* DeoxyhexNAc */] = 'DeoxyhexNAc',
    _a[6 /* DiDeoxyhexose */] = 'Di-deoxyhexose',
    _a[7 /* Pentose */] = 'Pentose',
    _a[8 /* Deoxynonulosonate */] = 'Deoxynonulosonate',
    _a[9 /* DiDeoxynonulosonate */] = 'Di-deoxynonulosonate',
    _a[10 /* Unknown */] = 'Unknown',
    _a[11 /* Assigned */] = 'Assigned',
    _a);
function getSaccharideName(type) {
    return SaccharideTypeNameMap[type];
}
var SaccharideTypeShapeMap = (_b = {},
    _b[0 /* Hexose */] = 0 /* FilledSphere */,
    _b[1 /* HexNAc */] = 1 /* FilledCube */,
    _b[2 /* Hexosamine */] = 2 /* CrossedCube */,
    _b[3 /* Hexuronate */] = 3 /* DividedDiamond */,
    _b[4 /* Deoxyhexose */] = 4 /* FilledCone */,
    _b[5 /* DeoxyhexNAc */] = 5 /* DevidedCone */,
    _b[6 /* DiDeoxyhexose */] = 6 /* FlatBox */,
    _b[7 /* Pentose */] = 7 /* FilledStar */,
    _b[8 /* Deoxynonulosonate */] = 8 /* FilledDiamond */,
    _b[9 /* DiDeoxynonulosonate */] = 9 /* FlatDiamond */,
    _b[10 /* Unknown */] = 10 /* FlatHexagon */,
    _b[11 /* Assigned */] = 11 /* Pentagon */,
    _b);
function getSaccharideShape(type, ringMemberCount) {
    if (type === 10 /* Unknown */) {
        if (ringMemberCount === 4)
            return 12 /* DiamondPrism */;
        else if (ringMemberCount === 5)
            return 13 /* PentagonalPrism */;
        else if (ringMemberCount === 6)
            return 14 /* HexagonalPrism */;
        else if (ringMemberCount === 7)
            return 15 /* HeptagonalPrism */;
        else
            return 10 /* FlatHexagon */;
    }
    else {
        return SaccharideTypeShapeMap[type];
    }
}
var UnknownSaccharideComponent = {
    abbr: 'Unk',
    name: 'Unknown',
    color: SaccharideColors.Secondary,
    type: 10 /* Unknown */
};
var Monosaccharides = [
    { abbr: 'Glc', name: 'Glucose', color: SaccharideColors.Blue, type: 0 /* Hexose */ },
    { abbr: 'Man', name: 'Mannose', color: SaccharideColors.Green, type: 0 /* Hexose */ },
    { abbr: 'Gal', name: 'Galactose', color: SaccharideColors.Yellow, type: 0 /* Hexose */ },
    { abbr: 'Gul', name: 'Gulose', color: SaccharideColors.Orange, type: 0 /* Hexose */ },
    { abbr: 'Alt', name: 'Altrose', color: SaccharideColors.Pink, type: 0 /* Hexose */ },
    { abbr: 'All', name: 'Allose', color: SaccharideColors.Purple, type: 0 /* Hexose */ },
    { abbr: 'Tal', name: 'Talose', color: SaccharideColors.LightBlue, type: 0 /* Hexose */ },
    { abbr: 'Ido', name: 'Idose', color: SaccharideColors.Brown, type: 0 /* Hexose */ },
    { abbr: 'GlcNAc', name: 'N-Acetyl Glucosamine', color: SaccharideColors.Blue, type: 1 /* HexNAc */ },
    { abbr: 'ManNAc', name: 'N-Acetyl Mannosamine', color: SaccharideColors.Green, type: 1 /* HexNAc */ },
    { abbr: 'GalNAc', name: 'N-Acetyl Galactosamine', color: SaccharideColors.Yellow, type: 1 /* HexNAc */ },
    { abbr: 'GulNAc', name: 'N-Acetyl Gulosamine', color: SaccharideColors.Orange, type: 1 /* HexNAc */ },
    { abbr: 'AltNAc', name: 'N-Acetyl Altrosamine', color: SaccharideColors.Pink, type: 1 /* HexNAc */ },
    { abbr: 'AllNAc', name: 'N-Acetyl Allosamine', color: SaccharideColors.Purple, type: 1 /* HexNAc */ },
    { abbr: 'TalNAc', name: 'N-Acetyl Talosamine', color: SaccharideColors.LightBlue, type: 1 /* HexNAc */ },
    { abbr: 'IdoNAc', name: 'N-Acetyl Idosamine', color: SaccharideColors.Brown, type: 1 /* HexNAc */ },
    { abbr: 'GlcN', name: 'Glucosamine', color: SaccharideColors.Blue, type: 2 /* Hexosamine */ },
    { abbr: 'ManN', name: 'Mannosamine', color: SaccharideColors.Green, type: 2 /* Hexosamine */ },
    { abbr: 'GalN', name: 'Galactosamine', color: SaccharideColors.Yellow, type: 2 /* Hexosamine */ },
    { abbr: 'GulN', name: 'Gulosamine', color: SaccharideColors.Orange, type: 2 /* Hexosamine */ },
    { abbr: 'AltN', name: 'Altrosamine', color: SaccharideColors.Pink, type: 2 /* Hexosamine */ },
    { abbr: 'AllN', name: 'Allosamine', color: SaccharideColors.Purple, type: 2 /* Hexosamine */ },
    { abbr: 'TalN', name: 'Talosamine', color: SaccharideColors.LightBlue, type: 2 /* Hexosamine */ },
    { abbr: 'IdoN', name: 'Idosamine', color: SaccharideColors.Brown, type: 2 /* Hexosamine */ },
    { abbr: 'GlcA', name: 'Glucuronic Acid', color: SaccharideColors.Blue, type: 3 /* Hexuronate */ },
    { abbr: 'ManA', name: 'Mannuronic Acid', color: SaccharideColors.Green, type: 3 /* Hexuronate */ },
    { abbr: 'GalA', name: 'Galacturonic Acid', color: SaccharideColors.Yellow, type: 3 /* Hexuronate */ },
    { abbr: 'GulA', name: 'Guluronic Acid', color: SaccharideColors.Orange, type: 3 /* Hexuronate */ },
    { abbr: 'AltA', name: 'Altruronic Acid', color: SaccharideColors.Pink, type: 3 /* Hexuronate */ },
    { abbr: 'AllA', name: 'Alluronic Acid', color: SaccharideColors.Purple, type: 3 /* Hexuronate */ },
    { abbr: 'TalA', name: 'Taluronic Acid', color: SaccharideColors.LightBlue, type: 3 /* Hexuronate */ },
    { abbr: 'IdoA', name: 'Iduronic Acid', color: SaccharideColors.Brown, type: 3 /* Hexuronate */ },
    { abbr: 'Qui', name: 'Quinovose', color: SaccharideColors.Blue, type: 4 /* Deoxyhexose */ },
    { abbr: 'Rha', name: 'Rhamnose', color: SaccharideColors.Green, type: 4 /* Deoxyhexose */ },
    { abbr: '6dGul', name: '6-Deoxy Gulose', color: SaccharideColors.Orange, type: 4 /* Deoxyhexose */ },
    { abbr: '6dAlt', name: '6-Deoxy Altrose', color: SaccharideColors.Pink, type: 4 /* Deoxyhexose */ },
    { abbr: '6dTal', name: '6-Deoxy Talose', color: SaccharideColors.LightBlue, type: 4 /* Deoxyhexose */ },
    { abbr: 'Fuc', name: 'Fucose', color: SaccharideColors.Red, type: 4 /* Deoxyhexose */ },
    { abbr: 'QuiNAc', name: 'N-Acetyl Quinovosamine', color: SaccharideColors.Blue, type: 5 /* DeoxyhexNAc */ },
    { abbr: 'RhaNAc', name: 'N-Acetyl Rhamnosamine', color: SaccharideColors.Green, type: 5 /* DeoxyhexNAc */ },
    { abbr: '6dAltNAc', name: 'N-Acetyl 6-Deoxy Altrosamine', color: SaccharideColors.Pink, type: 5 /* DeoxyhexNAc */ },
    { abbr: '6dTalNAc', name: 'N-Acetyl 6-Deoxy Talosamine', color: SaccharideColors.LightBlue, type: 5 /* DeoxyhexNAc */ },
    { abbr: 'FucNAc', name: 'N-Acetyl Fucosamine', color: SaccharideColors.Red, type: 5 /* DeoxyhexNAc */ },
    { abbr: 'Oli', name: 'Olivose', color: SaccharideColors.Blue, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Tyv', name: 'Tyvelose', color: SaccharideColors.Green, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Abe', name: 'Abequose', color: SaccharideColors.Orange, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Par', name: 'Paratose', color: SaccharideColors.Pink, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Dig', name: 'Digitoxose', color: SaccharideColors.Purple, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Col', name: 'Colitose', color: SaccharideColors.LightBlue, type: 6 /* DiDeoxyhexose */ },
    { abbr: 'Ara', name: 'Arabinose', color: SaccharideColors.Green, type: 7 /* Pentose */ },
    { abbr: 'Lyx', name: 'Lyxose', color: SaccharideColors.Yellow, type: 7 /* Pentose */ },
    { abbr: 'Xyl', name: 'Xylose', color: SaccharideColors.Orange, type: 7 /* Pentose */ },
    { abbr: 'Rib', name: 'Ribose', color: SaccharideColors.Pink, type: 7 /* Pentose */ },
    { abbr: 'Kdn', name: 'Keto-Deoxy Nonulonic Acid', color: SaccharideColors.Green, type: 8 /* Deoxynonulosonate */ },
    { abbr: 'Neu5Ac', name: 'N-Acetyl Neuraminic Acid', color: SaccharideColors.Purple, type: 8 /* Deoxynonulosonate */ },
    { abbr: 'Neu5Gc', name: 'N-Glycolyl Neuraminic Acid', color: SaccharideColors.LightBlue, type: 8 /* Deoxynonulosonate */ },
    { abbr: 'Neu', name: 'Neuraminic Acid', color: SaccharideColors.Brown, type: 8 /* Deoxynonulosonate */ },
    { abbr: 'Sia', name: 'Sialic acid', color: SaccharideColors.Red, type: 8 /* Deoxynonulosonate */ },
    { abbr: 'Pse', name: 'Pseudaminic Acid', color: SaccharideColors.Green, type: 9 /* DiDeoxynonulosonate */ },
    { abbr: 'Leg', name: 'Legionaminic Acid', color: SaccharideColors.Yellow, type: 9 /* DiDeoxynonulosonate */ },
    { abbr: 'Aci', name: 'Acinetaminic Acid', color: SaccharideColors.Pink, type: 9 /* DiDeoxynonulosonate */ },
    { abbr: '4eLeg', name: '4-Epilegionaminic Acid', color: SaccharideColors.LightBlue, type: 9 /* DiDeoxynonulosonate */ },
    { abbr: 'Bac', name: 'Bacillosamine', color: SaccharideColors.Blue, type: 10 /* Unknown */ },
    { abbr: 'LDmanHep', name: 'L-Glycero-D-Manno Heptose', color: SaccharideColors.Green, type: 10 /* Unknown */ },
    { abbr: 'Kdo', name: 'Keto-Deoxy Octulonic Acid', color: SaccharideColors.Yellow, type: 10 /* Unknown */ },
    { abbr: 'Dha', name: '3-Deoxy Lyxo-Heptulosaric Acid', color: SaccharideColors.Orange, type: 10 /* Unknown */ },
    { abbr: 'DDmanHep', name: 'D-Glycero-D-Manno-Heptose', color: SaccharideColors.Pink, type: 10 /* Unknown */ },
    { abbr: 'MurNAc', name: 'N-Acetyl Muramic Acid', color: SaccharideColors.Purple, type: 10 /* Unknown */ },
    { abbr: 'MurNGc', name: 'N-Glycolyl Muramic Acid', color: SaccharideColors.LightBlue, type: 10 /* Unknown */ },
    { abbr: 'Mur', name: 'Muramic Acid', color: SaccharideColors.Brown, type: 10 /* Unknown */ },
    { abbr: 'Api', name: 'Apicose', color: SaccharideColors.Green, type: 11 /* Assigned */ },
    { abbr: 'Fru', name: 'Fructose', color: SaccharideColors.Green, type: 11 /* Assigned */ },
    { abbr: 'Tag', name: 'Tagatose', color: SaccharideColors.Yellow, type: 11 /* Assigned */ },
    { abbr: 'Sor', name: 'Sorbose', color: SaccharideColors.Orange, type: 11 /* Assigned */ },
    { abbr: 'Psi', name: 'Psicose', color: SaccharideColors.Pink, type: 11 /* Assigned */ },
];
var SaccharidesSnfgMap = (function () {
    var map = new Map();
    for (var i = 0, il = Monosaccharides.length; i < il; ++i) {
        var saccharide = Monosaccharides[i];
        map.set(saccharide.abbr, saccharide);
    }
    return map;
})();
var MonosaccharidesColorTable = [
    ['Glc-family', SaccharideColors.Blue],
    ['Man-family', SaccharideColors.Green],
    ['Gal-family', SaccharideColors.Yellow],
    ['Gul-family', SaccharideColors.Orange],
    ['Alt-family', SaccharideColors.Pink],
    ['All-family', SaccharideColors.Purple],
    ['Tal-family', SaccharideColors.LightBlue],
    ['Ido-family', SaccharideColors.Brown],
    ['Fuc-family', SaccharideColors.Red],
    ['Generic/Unknown/Secondary', SaccharideColors.Secondary],
];
var CommonSaccharideNames = {
    // Hexose
    Glc: [
        'GLC', 'BGC', 'Z8T',
        'TRE',
        'MLR',
    ],
    Man: ['MAN', 'BMA'],
    Gal: ['GLA', 'GAL', 'GZL', 'GXL', 'GIV'],
    Gul: ['4GL', 'GL0', 'GUP', 'Z8H'],
    Alt: ['Z6H', '3MK', 'SHD'],
    All: ['AFD', 'ALL', 'WOO', 'Z2D'],
    Tal: ['ZEE', 'A5C', 'SDY'],
    Ido: ['ZCD', 'Z0F', '4N2'],
    // HexNAc
    GlcNAc: ['NDG', 'NAG', 'NGZ'],
    ManNAc: ['BM3', 'BM7'],
    GalNAc: ['A2G', 'NGA', 'YYQ'],
    GulNAc: ['LXB'],
    AltNAc: [],
    AllNAc: ['NAA'],
    TalNAc: [],
    IdoNAc: ['LXZ', 'HSQ'],
    // Hexosamine
    GlcN: ['PA1', 'GCS'],
    ManN: ['95Z'],
    GalN: ['X6X', '1GN'],
    GulN: [],
    AltN: [],
    AllN: [],
    TalN: [],
    IdoN: [],
    // Hexuronate
    GlcA: ['GCU', 'BDP'],
    ManA: ['MAV', 'BEM'],
    GalA: ['ADA', 'GTR', 'GTK'],
    GulA: ['LGU'],
    AltA: [],
    AllA: [],
    TalA: ['X1X', 'X0X'],
    IdoA: ['IDR'],
    // Deoxyhexose
    Qui: ['G6D', 'YYK'],
    Rha: ['RAM', 'RM4', 'XXR'],
    '6dGul': ['66O'],
    '6dAlt': [],
    '6dTal': [],
    Fuc: ['FUC', 'FUL', 'FCA', 'FCB', 'GYE'],
    // DeoxyhexNAc
    QuiNAc: ['Z9W'],
    RhaNAc: [],
    '6dAltNAc': [],
    '6dTalNAc': [],
    FucNAc: ['49T'],
    // Di-deoxyhexose
    Oli: ['DDA', 'RAE', 'Z5J'],
    Tyv: ['TYV'],
    Abe: ['ABE'],
    Par: ['PZU'],
    Dig: ['Z3U'],
    Col: [],
    // Pentose
    Ara: ['64K', 'ARA', 'ARB', 'AHR', 'FUB', 'BXY', 'BXX', 'SEJ'],
    Lyx: ['LDY', 'Z4W'],
    Xyl: ['XYS', 'XYP', 'XYZ', 'HSY', 'LXC'],
    Rib: ['YYM', 'RIP', 'RIB', 'BDR', '0MK', 'Z6J', '32O'],
    // Deoxynonulosonate
    Kdn: ['KDM', 'KDN'],
    Neu5Ac: ['SIA', 'SLB'],
    Neu5Gc: ['NGC', 'NGE'],
    Neu: [],
    Sia: [],
    // Di-deoxynonulosonate
    Pse: [],
    Leg: [],
    Aci: [],
    '4eLeg': [],
    // Unknown
    Bac: [],
    LDmanHep: ['GMH'],
    Kdo: ['KDO'],
    Dha: [],
    DDmanHep: ['289'],
    MurNAc: ['MUB', 'AMU'],
    MurNGc: [],
    Mur: ['1S4', 'MUR'],
    // Assigned
    Api: ['XXM'],
    Fru: ['BDF', 'Z9N', 'FRU', 'LFR'],
    Tag: ['T6T'],
    Sor: ['SOE', 'UEA'],
    Psi: ['PSV', 'SF6', 'SF9', 'TTV'],
};
var UnknownSaccharideNames = [
    'NGZ',
    'LAT',
    'PUF', 'GDA', '9WJ',
];
var SaccharideCompIdMap = (function () {
    var map = new Map();
    for (var i = 0, il = Monosaccharides.length; i < il; ++i) {
        var saccharide = Monosaccharides[i];
        var names = CommonSaccharideNames[saccharide.abbr];
        if (names) {
            for (var j = 0, jl = names.length; j < jl; ++j) {
                map.set(names[j], saccharide);
            }
        }
    }
    for (var i = 0, il = UnknownSaccharideNames.length; i < il; ++i) {
        map.set(UnknownSaccharideNames[i], UnknownSaccharideComponent);
    }
    return map;
})();
//# sourceMappingURL=constants.js.map

/***/ }),
/* 179 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DataFormatProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return guessCifVariant; });
/* harmony import */ var _mol_io_common_msgpack_decode__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(357);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function DataFormatProvider(provider) { return provider; }
function guessCifVariant(info, data) {
    if (info.ext === 'bcif') {
        try {
            // TODO: find a way to run msgpackDecode only once
            //      now it is run twice, here and during file parsing
            if (Object(_mol_io_common_msgpack_decode__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"])(data).encoder.startsWith('VolumeServer'))
                return 'dscif';
        }
        catch (_a) { }
    }
    else if (info.ext === 'cif') {
        var str = data;
        if (str.startsWith('data_SERVER\n#\n_density_server_result'))
            return 'dscif';
        if (str.includes('atom_site_fract_x') || str.includes('atom_site.fract_x'))
            return 'coreCif';
    }
    return -1;
}
//# sourceMappingURL=provider.js.map

/***/ }),
/* 180 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RxEventHelper", function() { return RxEventHelper; });
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(60);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(279);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var RxEventHelper;
(function (RxEventHelper) {
    function create() {
        var helper = new _RxEventHelper();
        var ret = (function () { return helper.create(); });
        ret.dispose = function () { return helper.dispose(); };
        ret.behavior = function (v) { return helper.behavior(v); };
        return ret;
    }
    RxEventHelper.create = create;
})(RxEventHelper || (RxEventHelper = {}));
var _RxEventHelper = /** @class */ (function () {
    function _RxEventHelper() {
        this._eventList = [];
        this._disposed = false;
    }
    _RxEventHelper.prototype.create = function () {
        var s = new rxjs__WEBPACK_IMPORTED_MODULE_0__[/* Subject */ "a"]();
        this._eventList.push(s);
        return s;
    };
    _RxEventHelper.prototype.behavior = function (v) {
        var s = new rxjs__WEBPACK_IMPORTED_MODULE_1__[/* BehaviorSubject */ "a"](v);
        this._eventList.push(s);
        return s;
    };
    _RxEventHelper.prototype.dispose = function () {
        if (this._disposed)
            return;
        for (var _i = 0, _a = this._eventList; _i < _a.length; _i++) {
            var e = _a[_i];
            e.complete();
        }
        this._disposed = true;
    };
    return _RxEventHelper;
}());
//# sourceMappingURL=rx-event-helper.js.map

/***/ }),
/* 181 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return identity; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function identity(x) {
    return x;
}
//# sourceMappingURL=identity.js.map


/***/ }),
/* 182 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createTransform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createIdentityTransform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return fillIdentityTransform; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return updateTransformData; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(29);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function createTransform(transformArray, instanceCount, transformData) {
    if (transformData) {
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.matrix, transformData.matrix.ref.value);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.transform, transformArray);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.uInstanceCount, instanceCount);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.instanceCount, instanceCount);
        var aTransform = transformData.aTransform.ref.value.length >= instanceCount * 16 ? transformData.aTransform.ref.value : new Float32Array(instanceCount * 16);
        aTransform.set(transformArray);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.aTransform, aTransform);
        // Note that this sets `extraTransform` to identity transforms
        var extraTransform = transformData.extraTransform.ref.value.length >= instanceCount * 16 ? transformData.extraTransform.ref.value : new Float32Array(instanceCount * 16);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.extraTransform, fillIdentityTransform(extraTransform, instanceCount));
        var aInstance = transformData.aInstance.ref.value.length >= instanceCount ? transformData.aInstance.ref.value : new Float32Array(instanceCount);
        _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.aInstance, Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_2__["fillSerial"])(aInstance, instanceCount));
        updateTransformData(transformData);
        return transformData;
    }
    else {
        return {
            aTransform: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(new Float32Array(transformArray)),
            matrix: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].identity()),
            transform: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(transformArray),
            extraTransform: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(fillIdentityTransform(new Float32Array(instanceCount * 16), instanceCount)),
            uInstanceCount: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(instanceCount),
            instanceCount: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(instanceCount),
            aInstance: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].create(Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_2__["fillSerial"])(new Float32Array(instanceCount)))
        };
    }
}
var identityTransform = new Float32Array(16);
_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].toArray(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].identity(), identityTransform, 0);
function createIdentityTransform(transformData) {
    return createTransform(new Float32Array(identityTransform), 1, transformData);
}
function fillIdentityTransform(transform, count) {
    for (var i = 0; i < count; i++) {
        transform.set(identityTransform, i * 16);
    }
    return transform;
}
/**
 * updates per-instance transform calculated for instance `i` as
 * `aTransform[i] = matrix * transform[i] * extraTransform[i]`
 */
function updateTransformData(transformData) {
    var aTransform = transformData.aTransform.ref.value;
    var instanceCount = transformData.instanceCount.ref.value;
    var matrix = transformData.matrix.ref.value;
    var transform = transformData.transform.ref.value;
    var extraTransform = transformData.extraTransform.ref.value;
    for (var i = 0; i < instanceCount; i++) {
        var i16 = i * 16;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mulOffset(aTransform, extraTransform, transform, i16, i16, i16);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mulOffset(aTransform, matrix, aTransform, i16, 0, i16);
    }
    _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* ValueCell */ "e"].update(transformData.aTransform, aTransform);
}
//# sourceMappingURL=transform-data.js.map

/***/ }),
/* 183 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "UpdateTransformControl", function() { return UpdateTransformControl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "TransformUpdaterControl", function() { return TransformUpdaterControl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_memoize__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(155);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(287);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(32);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var UpdateTransformControl = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(UpdateTransformControl, _super);
    function UpdateTransformControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._getInfo = Object(_mol_util_memoize__WEBPACK_IMPORTED_MODULE_1__[/* memoizeLatest */ "b"])(function (t) { return _common__WEBPACK_IMPORTED_MODULE_2__[/* StateTransformParameters */ "a"].infoFromTransform(_this.plugin, _this.props.state, t); });
        _this.state = { error: void 0, isInitial: true, params: _this.getInfo().initialValues, busy: false, isCollapsed: _this.props.initiallyCollapsed };
        return _this;
    }
    UpdateTransformControl.prototype.applyAction = function () {
        if (this.props.customUpdate)
            return this.props.customUpdate(this.state.params);
        return this.plugin.state.updateTransform(this.props.state, this.props.transform.ref, this.state.params);
    };
    UpdateTransformControl.prototype.getInfo = function () { return this._getInfo(this.props.transform); };
    UpdateTransformControl.prototype.getTransformerId = function () { return this.props.transform.transformer.id; };
    UpdateTransformControl.prototype.getHeader = function () { return this.props.customHeader || this.props.transform.transformer.definition.display; };
    UpdateTransformControl.prototype.canApply = function () {
        var state = this.props.state;
        var cell = state.cells.get(this.props.transform.ref);
        if (!cell)
            return false;
        if (cell.status === 'error') {
            var parent_1 = state.cells.get(this.props.transform.parent);
            if (!parent_1)
                return false;
            return parent_1.status === 'ok';
        }
        return !this.state.error && !this.state.busy && !this.state.isInitial;
    };
    UpdateTransformControl.prototype.applyText = function () { return this.canApply() ? 'Update' : 'Nothing to Update'; };
    UpdateTransformControl.prototype.isUpdate = function () { return true; };
    UpdateTransformControl.prototype.getSourceAndTarget = function () {
        var bCell = this.props.state.cells.get(this.props.transform.ref);
        return {
            a: this.props.state.cells.get(this.props.transform.parent).obj,
            b: bCell === null || bCell === void 0 ? void 0 : bCell.obj,
            bCell: bCell
        };
    };
    UpdateTransformControl.prototype.canAutoApply = function (newParams) {
        var autoUpdate = this.props.transform.transformer.definition.canAutoUpdate;
        if (!autoUpdate)
            return false;
        var state = this.props.state;
        var cell = state.cells.get(this.props.transform.ref);
        if (!cell || !cell.sourceRef || cell.status !== 'ok')
            return false;
        var parentCell = state.cells.get(cell.sourceRef);
        return autoUpdate({ a: parentCell.obj, b: cell.obj, oldParams: this.getInfo().initialValues, newParams: newParams }, this.plugin);
    };
    UpdateTransformControl.prototype.componentDidMount = function () {
        var _this = this;
        _super.prototype.componentDidMount.call(this);
        if (this.props.toggleCollapsed)
            this.subscribe(this.props.toggleCollapsed, function () { return _this.setState({ isCollapsed: !_this.state.isCollapsed }); });
        this.subscribe(this.plugin.state.events.object.updated, function (_a) {
            var ref = _a.ref, state = _a.state;
            if (_this.props.transform.ref !== ref || _this.props.state !== state)
                return;
            if (_this.state.params !== _this.props.transform.params) {
                _this._getInfo = Object(_mol_util_memoize__WEBPACK_IMPORTED_MODULE_1__[/* memoizeLatest */ "b"])(function (t) { return _common__WEBPACK_IMPORTED_MODULE_2__[/* StateTransformParameters */ "a"].infoFromTransform(_this.plugin, _this.props.state, t); });
                _this.setState({ params: _this.props.transform.params, isInitial: true });
            }
        });
    };
    UpdateTransformControl.prototype.componentDidUpdate = function (prevProps) {
        var _a;
        if (this.props.transform !== prevProps.transform) {
            var cell = this.props.state.cells.get(this.props.transform.ref);
            this.setState({
                params: ((_a = cell.params) === null || _a === void 0 ? void 0 : _a.values) || {},
                isInitial: true,
                error: void 0,
                simpleOnly: this.state.simpleOnly
            });
        }
    };
    return UpdateTransformControl;
}(_common__WEBPACK_IMPORTED_MODULE_2__[/* TransformControlBase */ "b"]));
var TransformUpdaterControl = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TransformUpdaterControl, _super);
    function TransformUpdaterControl() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    TransformUpdaterControl.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.object.updated, function (_a) {
            var ref = _a.ref, state = _a.state;
            if (_this.props.nodeRef !== ref || _this.plugin.state.data !== state)
                return;
            _this.forceUpdate();
        });
    };
    TransformUpdaterControl.prototype.render = function () {
        var state = this.plugin.state.data;
        var ref = this.props.nodeRef;
        var cell = state.cells.get(ref);
        if (!cell || (cell.status !== 'ok' && cell.status !== 'error'))
            return null;
        var transform = cell.transform;
        return react__WEBPACK_IMPORTED_MODULE_3__["createElement"](UpdateTransformControl, { state: state, transform: transform, initiallyCollapsed: this.props.initiallyCollapsed, customHeader: this.props.header });
    };
    return TransformUpdaterControl;
}(_base__WEBPACK_IMPORTED_MODULE_4__["PluginUIComponent"]));
//# sourceMappingURL=update-transform.js.map

/***/ }),
/* 184 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createCage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cloneCage; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return transformCage; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function createCage(vertices, edges) {
    return { vertices: vertices, edges: edges };
}
function cloneCage(cage) {
    return {
        vertices: new Float32Array(cage.vertices),
        edges: new Uint32Array(cage.edges)
    };
}
var tmpV = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
/** Transform primitive in-place */
function transformCage(cage, t) {
    var vertices = cage.vertices;
    for (var i = 0, il = vertices.length; i < il; i += 3) {
        // position
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpV, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].fromArray(tmpV, vertices, i), t);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].toArray(tmpV, vertices, i);
    }
    return cage;
}
//# sourceMappingURL=cage.js.map

/***/ }),
/* 185 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getBoundary; });
/* harmony import */ var _linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _boundary_helper__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(126);
/* harmony import */ var _geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var boundaryHelperCoarse = new _boundary_helper__WEBPACK_IMPORTED_MODULE_2__[/* BoundaryHelper */ "a"]('14');
var boundaryHelperFine = new _boundary_helper__WEBPACK_IMPORTED_MODULE_2__[/* BoundaryHelper */ "a"]('98');
function getBoundaryHelper(count) {
    return count > 10000 ? boundaryHelperCoarse : boundaryHelperFine;
}
function getBoundary(data) {
    var x = data.x, y = data.y, z = data.z, radius = data.radius, indices = data.indices;
    var p = Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    var n = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices);
    var boundaryHelper = getBoundaryHelper(n);
    boundaryHelper.reset();
    for (var t = 0; t < n; t++) {
        var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, t);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(p, x[i], y[i], z[i]);
        boundaryHelper.includePositionRadius(p, (radius && radius[i]) || 0);
    }
    boundaryHelper.finishedIncludeStep();
    for (var t = 0; t < n; t++) {
        var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, t);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(p, x[i], y[i], z[i]);
        boundaryHelper.radiusPositionRadius(p, (radius && radius[i]) || 0);
    }
    var sphere = boundaryHelper.getSphere();
    if (!radius && _geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].hasExtrema(sphere) && n <= sphere.extrema.length) {
        var extrema = [];
        for (var t = 0; t < n; t++) {
            var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, t);
            extrema.push(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].create(x[i], y[i], z[i]));
        }
        _geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].setExtrema(sphere, extrema);
    }
    return { box: boundaryHelper.getBox(), sphere: sphere };
}
//# sourceMappingURL=boundary.js.map

/***/ }),
/* 186 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getArrayBounds", function() { return getArrayBounds; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createArray", function() { return createArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fillArrayValues", function() { return fillArrayValues; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "createAndFillArray", function() { return createAndFillArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isTypedArray", function() { return isTypedArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "typedArrayWindow", function() { return typedArrayWindow; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function getArrayBounds(rowCount, params) {
    var start = params && typeof params.start !== 'undefined' ? Math.max(Math.min(params.start, rowCount - 1), 0) : 0;
    var end = params && typeof params.end !== 'undefined' ? Math.min(params.end, rowCount) : rowCount;
    return { start: start, end: end };
}
function createArray(rowCount, params) {
    var c = params && typeof params.array !== 'undefined' ? params.array : Array;
    var _a = getArrayBounds(rowCount, params), start = _a.start, end = _a.end;
    return { array: new c(end - start), start: start, end: end };
}
function fillArrayValues(value, target, start) {
    for (var i = 0, _e = target.length; i < _e; i++)
        target[i] = value(start + i);
    return target;
}
function createAndFillArray(rowCount, value, params) {
    var _a = createArray(rowCount, params), array = _a.array, start = _a.start;
    return fillArrayValues(value, array, start);
}
function isTypedArray(data) {
    return !!data.buffer && typeof data.byteLength === 'number' && typeof data.BYTES_PER_ELEMENT === 'number';
}
function typedArrayWindow(data, params) {
    var constructor = data.constructor, buffer = data.buffer, length = data.length, byteOffset = data.byteOffset, BYTES_PER_ELEMENT = data.BYTES_PER_ELEMENT;
    var _a = getArrayBounds(length, params), start = _a.start, end = _a.end;
    if (start === 0 && end === length)
        return data;
    return new constructor(buffer, byteOffset + BYTES_PER_ELEMENT * start, Math.min(length, end - start));
}
//# sourceMappingURL=column-helpers.js.map

/***/ }),
/* 187 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export Index */
/* unused harmony export IndexPair */
/* unused harmony export EdgesXY */
/* unused harmony export EdgesXZ */
/* unused harmony export EdgesYZ */
/* unused harmony export CubeVertices */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CubeEdges; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return EdgeIdInfo; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return EdgeTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return TriTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AllowedContours; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 */
function Index(i, j, k) { return { i: i, j: j, k: k }; }
function IndexPair(a, b) { return { a: a, b: b }; }
var EdgesXY = [
    [],
    [0, 3],
    [0, 1],
    [1, 3],
    [1, 2],
    [0, 1, 1, 2, 2, 3, 0, 3],
    [0, 2],
    [2, 3],
    [2, 3],
    [0, 2],
    [0, 1, 1, 2, 2, 3, 0, 3],
    [1, 2],
    [1, 3],
    [0, 1],
    [0, 3],
    []
];
var EdgesXZ = [
    [],
    [0, 8],
    [0, 9],
    [9, 8],
    [9, 4],
    [0, 9, 9, 4, 4, 8, 0, 8],
    [0, 4],
    [4, 8],
    [4, 8],
    [0, 4],
    [0, 9, 9, 4, 4, 8, 0, 8],
    [9, 4],
    [9, 8],
    [0, 9],
    [0, 8],
    []
];
var EdgesYZ = [
    [],
    [3, 8],
    [3, 11],
    [11, 8],
    [11, 7],
    [3, 11, 11, 7, 7, 8, 3, 8],
    [3, 7],
    [7, 8],
    [7, 8],
    [3, 7],
    [3, 11, 11, 7, 7, 8, 3, 8],
    [11, 7],
    [11, 8],
    [3, 11],
    [3, 8],
    []
];
var CubeVertices = [
    Index(0, 0, 0),
    Index(1, 0, 0),
    Index(1, 1, 0),
    Index(0, 1, 0),
    Index(0, 0, 1),
    Index(1, 0, 1),
    Index(1, 1, 1),
    Index(0, 1, 1),
];
var CubeEdges = [
    IndexPair(CubeVertices[0], CubeVertices[1]),
    IndexPair(CubeVertices[1], CubeVertices[2]),
    IndexPair(CubeVertices[2], CubeVertices[3]),
    IndexPair(CubeVertices[3], CubeVertices[0]),
    IndexPair(CubeVertices[4], CubeVertices[5]),
    IndexPair(CubeVertices[5], CubeVertices[6]),
    IndexPair(CubeVertices[6], CubeVertices[7]),
    IndexPair(CubeVertices[7], CubeVertices[4]),
    IndexPair(CubeVertices[0], CubeVertices[4]),
    IndexPair(CubeVertices[1], CubeVertices[5]),
    IndexPair(CubeVertices[2], CubeVertices[6]),
    IndexPair(CubeVertices[3], CubeVertices[7]),
];
var EdgeIdInfo = [
    { i: 0, j: 0, k: 0, e: 0 },
    { i: 1, j: 0, k: 0, e: 1 },
    { i: 0, j: 1, k: 0, e: 0 },
    { i: 0, j: 0, k: 0, e: 1 },
    { i: 0, j: 0, k: 1, e: 0 },
    { i: 1, j: 0, k: 1, e: 1 },
    { i: 0, j: 1, k: 1, e: 0 },
    { i: 0, j: 0, k: 1, e: 1 },
    { i: 0, j: 0, k: 0, e: 2 },
    { i: 1, j: 0, k: 0, e: 2 },
    { i: 1, j: 1, k: 0, e: 2 },
    { i: 0, j: 1, k: 0, e: 2 }
];
// Tables EdgeTable and TriTable taken from http://paulbourke.net/geometry/polygonise/
var EdgeTable = [
    0x0, 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
    0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd03, 0xe09, 0xf00,
    0x190, 0x99, 0x393, 0x29a, 0x596, 0x49f, 0x795, 0x69c,
    0x99c, 0x895, 0xb9f, 0xa96, 0xd9a, 0xc93, 0xf99, 0xe90,
    0x230, 0x339, 0x33, 0x13a, 0x636, 0x73f, 0x435, 0x53c,
    0xa3c, 0xb35, 0x83f, 0x936, 0xe3a, 0xf33, 0xc39, 0xd30,
    0x3a0, 0x2a9, 0x1a3, 0xaa, 0x7a6, 0x6af, 0x5a5, 0x4ac,
    0xbac, 0xaa5, 0x9af, 0x8a6, 0xfaa, 0xea3, 0xda9, 0xca0,
    0x460, 0x569, 0x663, 0x76a, 0x66, 0x16f, 0x265, 0x36c,
    0xc6c, 0xd65, 0xe6f, 0xf66, 0x86a, 0x963, 0xa69, 0xb60,
    0x5f0, 0x4f9, 0x7f3, 0x6fa, 0x1f6, 0xff, 0x3f5, 0x2fc,
    0xdfc, 0xcf5, 0xfff, 0xef6, 0x9fa, 0x8f3, 0xbf9, 0xaf0,
    0x650, 0x759, 0x453, 0x55a, 0x256, 0x35f, 0x55, 0x15c,
    0xe5c, 0xf55, 0xc5f, 0xd56, 0xa5a, 0xb53, 0x859, 0x950,
    0x7c0, 0x6c9, 0x5c3, 0x4ca, 0x3c6, 0x2cf, 0x1c5, 0xcc,
    0xfcc, 0xec5, 0xdcf, 0xcc6, 0xbca, 0xac3, 0x9c9, 0x8c0,
    0x8c0, 0x9c9, 0xac3, 0xbca, 0xcc6, 0xdcf, 0xec5, 0xfcc,
    0xcc, 0x1c5, 0x2cf, 0x3c6, 0x4ca, 0x5c3, 0x6c9, 0x7c0,
    0x950, 0x859, 0xb53, 0xa5a, 0xd56, 0xc5f, 0xf55, 0xe5c,
    0x15c, 0x55, 0x35f, 0x256, 0x55a, 0x453, 0x759, 0x650,
    0xaf0, 0xbf9, 0x8f3, 0x9fa, 0xef6, 0xfff, 0xcf5, 0xdfc,
    0x2fc, 0x3f5, 0xff, 0x1f6, 0x6fa, 0x7f3, 0x4f9, 0x5f0,
    0xb60, 0xa69, 0x963, 0x86a, 0xf66, 0xe6f, 0xd65, 0xc6c,
    0x36c, 0x265, 0x16f, 0x66, 0x76a, 0x663, 0x569, 0x460,
    0xca0, 0xda9, 0xea3, 0xfaa, 0x8a6, 0x9af, 0xaa5, 0xbac,
    0x4ac, 0x5a5, 0x6af, 0x7a6, 0xaa, 0x1a3, 0x2a9, 0x3a0,
    0xd30, 0xc39, 0xf33, 0xe3a, 0x936, 0x83f, 0xb35, 0xa3c,
    0x53c, 0x435, 0x73f, 0x636, 0x13a, 0x33, 0x339, 0x230,
    0xe90, 0xf99, 0xc93, 0xd9a, 0xa96, 0xb9f, 0x895, 0x99c,
    0x69c, 0x795, 0x49f, 0x596, 0x29a, 0x393, 0x99, 0x190,
    0xf00, 0xe09, 0xd03, 0xc0a, 0xb06, 0xa0f, 0x905, 0x80c,
    0x70c, 0x605, 0x50f, 0x406, 0x30a, 0x203, 0x109, 0x0
];
var TriTable = [
    [],
    [0, 8, 3],
    [0, 1, 9],
    [1, 8, 3, 9, 8, 1],
    [1, 2, 10],
    [0, 8, 3, 1, 2, 10],
    [9, 2, 10, 0, 2, 9],
    [2, 8, 3, 2, 10, 8, 10, 9, 8],
    [3, 11, 2],
    [0, 11, 2, 8, 11, 0],
    [1, 9, 0, 2, 3, 11],
    [1, 11, 2, 1, 9, 11, 9, 8, 11],
    [3, 10, 1, 11, 10, 3],
    [0, 10, 1, 0, 8, 10, 8, 11, 10],
    [3, 9, 0, 3, 11, 9, 11, 10, 9],
    [9, 8, 10, 10, 8, 11],
    [4, 7, 8],
    [4, 3, 0, 7, 3, 4],
    [0, 1, 9, 8, 4, 7],
    [4, 1, 9, 4, 7, 1, 7, 3, 1],
    [1, 2, 10, 8, 4, 7],
    [3, 4, 7, 3, 0, 4, 1, 2, 10],
    [9, 2, 10, 9, 0, 2, 8, 4, 7],
    [2, 10, 9, 2, 9, 7, 2, 7, 3, 7, 9, 4],
    [8, 4, 7, 3, 11, 2],
    [11, 4, 7, 11, 2, 4, 2, 0, 4],
    [9, 0, 1, 8, 4, 7, 2, 3, 11],
    [4, 7, 11, 9, 4, 11, 9, 11, 2, 9, 2, 1],
    [3, 10, 1, 3, 11, 10, 7, 8, 4],
    [1, 11, 10, 1, 4, 11, 1, 0, 4, 7, 11, 4],
    [4, 7, 8, 9, 0, 11, 9, 11, 10, 11, 0, 3],
    [4, 7, 11, 4, 11, 9, 9, 11, 10],
    [9, 5, 4],
    [9, 5, 4, 0, 8, 3],
    [0, 5, 4, 1, 5, 0],
    [8, 5, 4, 8, 3, 5, 3, 1, 5],
    [1, 2, 10, 9, 5, 4],
    [3, 0, 8, 1, 2, 10, 4, 9, 5],
    [5, 2, 10, 5, 4, 2, 4, 0, 2],
    [2, 10, 5, 3, 2, 5, 3, 5, 4, 3, 4, 8],
    [9, 5, 4, 2, 3, 11],
    [0, 11, 2, 0, 8, 11, 4, 9, 5],
    [0, 5, 4, 0, 1, 5, 2, 3, 11],
    [2, 1, 5, 2, 5, 8, 2, 8, 11, 4, 8, 5],
    [10, 3, 11, 10, 1, 3, 9, 5, 4],
    [4, 9, 5, 0, 8, 1, 8, 10, 1, 8, 11, 10],
    [5, 4, 0, 5, 0, 11, 5, 11, 10, 11, 0, 3],
    [5, 4, 8, 5, 8, 10, 10, 8, 11],
    [9, 7, 8, 5, 7, 9],
    [9, 3, 0, 9, 5, 3, 5, 7, 3],
    [0, 7, 8, 0, 1, 7, 1, 5, 7],
    [1, 5, 3, 3, 5, 7],
    [9, 7, 8, 9, 5, 7, 10, 1, 2],
    [10, 1, 2, 9, 5, 0, 5, 3, 0, 5, 7, 3],
    [8, 0, 2, 8, 2, 5, 8, 5, 7, 10, 5, 2],
    [2, 10, 5, 2, 5, 3, 3, 5, 7],
    [7, 9, 5, 7, 8, 9, 3, 11, 2],
    [9, 5, 7, 9, 7, 2, 9, 2, 0, 2, 7, 11],
    [2, 3, 11, 0, 1, 8, 1, 7, 8, 1, 5, 7],
    [11, 2, 1, 11, 1, 7, 7, 1, 5],
    [9, 5, 8, 8, 5, 7, 10, 1, 3, 10, 3, 11],
    [5, 7, 0, 5, 0, 9, 7, 11, 0, 1, 0, 10, 11, 10, 0],
    [11, 10, 0, 11, 0, 3, 10, 5, 0, 8, 0, 7, 5, 7, 0],
    [11, 10, 5, 7, 11, 5],
    [10, 6, 5],
    [0, 8, 3, 5, 10, 6],
    [9, 0, 1, 5, 10, 6],
    [1, 8, 3, 1, 9, 8, 5, 10, 6],
    [1, 6, 5, 2, 6, 1],
    [1, 6, 5, 1, 2, 6, 3, 0, 8],
    [9, 6, 5, 9, 0, 6, 0, 2, 6],
    [5, 9, 8, 5, 8, 2, 5, 2, 6, 3, 2, 8],
    [2, 3, 11, 10, 6, 5],
    [11, 0, 8, 11, 2, 0, 10, 6, 5],
    [0, 1, 9, 2, 3, 11, 5, 10, 6],
    [5, 10, 6, 1, 9, 2, 9, 11, 2, 9, 8, 11],
    [6, 3, 11, 6, 5, 3, 5, 1, 3],
    [0, 8, 11, 0, 11, 5, 0, 5, 1, 5, 11, 6],
    [3, 11, 6, 0, 3, 6, 0, 6, 5, 0, 5, 9],
    [6, 5, 9, 6, 9, 11, 11, 9, 8],
    [5, 10, 6, 4, 7, 8],
    [4, 3, 0, 4, 7, 3, 6, 5, 10],
    [1, 9, 0, 5, 10, 6, 8, 4, 7],
    [10, 6, 5, 1, 9, 7, 1, 7, 3, 7, 9, 4],
    [6, 1, 2, 6, 5, 1, 4, 7, 8],
    [1, 2, 5, 5, 2, 6, 3, 0, 4, 3, 4, 7],
    [8, 4, 7, 9, 0, 5, 0, 6, 5, 0, 2, 6],
    [7, 3, 9, 7, 9, 4, 3, 2, 9, 5, 9, 6, 2, 6, 9],
    [3, 11, 2, 7, 8, 4, 10, 6, 5],
    [5, 10, 6, 4, 7, 2, 4, 2, 0, 2, 7, 11],
    [0, 1, 9, 4, 7, 8, 2, 3, 11, 5, 10, 6],
    [9, 2, 1, 9, 11, 2, 9, 4, 11, 7, 11, 4, 5, 10, 6],
    [8, 4, 7, 3, 11, 5, 3, 5, 1, 5, 11, 6],
    [5, 1, 11, 5, 11, 6, 1, 0, 11, 7, 11, 4, 0, 4, 11],
    [0, 5, 9, 0, 6, 5, 0, 3, 6, 11, 6, 3, 8, 4, 7],
    [6, 5, 9, 6, 9, 11, 4, 7, 9, 7, 11, 9],
    [10, 4, 9, 6, 4, 10],
    [4, 10, 6, 4, 9, 10, 0, 8, 3],
    [10, 0, 1, 10, 6, 0, 6, 4, 0],
    [8, 3, 1, 8, 1, 6, 8, 6, 4, 6, 1, 10],
    [1, 4, 9, 1, 2, 4, 2, 6, 4],
    [3, 0, 8, 1, 2, 9, 2, 4, 9, 2, 6, 4],
    [0, 2, 4, 4, 2, 6],
    [8, 3, 2, 8, 2, 4, 4, 2, 6],
    [10, 4, 9, 10, 6, 4, 11, 2, 3],
    [0, 8, 2, 2, 8, 11, 4, 9, 10, 4, 10, 6],
    [3, 11, 2, 0, 1, 6, 0, 6, 4, 6, 1, 10],
    [6, 4, 1, 6, 1, 10, 4, 8, 1, 2, 1, 11, 8, 11, 1],
    [9, 6, 4, 9, 3, 6, 9, 1, 3, 11, 6, 3],
    [8, 11, 1, 8, 1, 0, 11, 6, 1, 9, 1, 4, 6, 4, 1],
    [3, 11, 6, 3, 6, 0, 0, 6, 4],
    [6, 4, 8, 11, 6, 8],
    [7, 10, 6, 7, 8, 10, 8, 9, 10],
    [0, 7, 3, 0, 10, 7, 0, 9, 10, 6, 7, 10],
    [10, 6, 7, 1, 10, 7, 1, 7, 8, 1, 8, 0],
    [10, 6, 7, 10, 7, 1, 1, 7, 3],
    [1, 2, 6, 1, 6, 8, 1, 8, 9, 8, 6, 7],
    [2, 6, 9, 2, 9, 1, 6, 7, 9, 0, 9, 3, 7, 3, 9],
    [7, 8, 0, 7, 0, 6, 6, 0, 2],
    [7, 3, 2, 6, 7, 2],
    [2, 3, 11, 10, 6, 8, 10, 8, 9, 8, 6, 7],
    [2, 0, 7, 2, 7, 11, 0, 9, 7, 6, 7, 10, 9, 10, 7],
    [1, 8, 0, 1, 7, 8, 1, 10, 7, 6, 7, 10, 2, 3, 11],
    [11, 2, 1, 11, 1, 7, 10, 6, 1, 6, 7, 1],
    [8, 9, 6, 8, 6, 7, 9, 1, 6, 11, 6, 3, 1, 3, 6],
    [0, 9, 1, 11, 6, 7],
    [7, 8, 0, 7, 0, 6, 3, 11, 0, 11, 6, 0],
    [7, 11, 6],
    [7, 6, 11],
    [3, 0, 8, 11, 7, 6],
    [0, 1, 9, 11, 7, 6],
    [8, 1, 9, 8, 3, 1, 11, 7, 6],
    [10, 1, 2, 6, 11, 7],
    [1, 2, 10, 3, 0, 8, 6, 11, 7],
    [2, 9, 0, 2, 10, 9, 6, 11, 7],
    [6, 11, 7, 2, 10, 3, 10, 8, 3, 10, 9, 8],
    [7, 2, 3, 6, 2, 7],
    [7, 0, 8, 7, 6, 0, 6, 2, 0],
    [2, 7, 6, 2, 3, 7, 0, 1, 9],
    [1, 6, 2, 1, 8, 6, 1, 9, 8, 8, 7, 6],
    [10, 7, 6, 10, 1, 7, 1, 3, 7],
    [10, 7, 6, 1, 7, 10, 1, 8, 7, 1, 0, 8],
    [0, 3, 7, 0, 7, 10, 0, 10, 9, 6, 10, 7],
    [7, 6, 10, 7, 10, 8, 8, 10, 9],
    [6, 8, 4, 11, 8, 6],
    [3, 6, 11, 3, 0, 6, 0, 4, 6],
    [8, 6, 11, 8, 4, 6, 9, 0, 1],
    [9, 4, 6, 9, 6, 3, 9, 3, 1, 11, 3, 6],
    [6, 8, 4, 6, 11, 8, 2, 10, 1],
    [1, 2, 10, 3, 0, 11, 0, 6, 11, 0, 4, 6],
    [4, 11, 8, 4, 6, 11, 0, 2, 9, 2, 10, 9],
    [10, 9, 3, 10, 3, 2, 9, 4, 3, 11, 3, 6, 4, 6, 3],
    [8, 2, 3, 8, 4, 2, 4, 6, 2],
    [0, 4, 2, 4, 6, 2],
    [1, 9, 0, 2, 3, 4, 2, 4, 6, 4, 3, 8],
    [1, 9, 4, 1, 4, 2, 2, 4, 6],
    [8, 1, 3, 8, 6, 1, 8, 4, 6, 6, 10, 1],
    [10, 1, 0, 10, 0, 6, 6, 0, 4],
    [4, 6, 3, 4, 3, 8, 6, 10, 3, 0, 3, 9, 10, 9, 3],
    [10, 9, 4, 6, 10, 4],
    [4, 9, 5, 7, 6, 11],
    [0, 8, 3, 4, 9, 5, 11, 7, 6],
    [5, 0, 1, 5, 4, 0, 7, 6, 11],
    [11, 7, 6, 8, 3, 4, 3, 5, 4, 3, 1, 5],
    [9, 5, 4, 10, 1, 2, 7, 6, 11],
    [6, 11, 7, 1, 2, 10, 0, 8, 3, 4, 9, 5],
    [7, 6, 11, 5, 4, 10, 4, 2, 10, 4, 0, 2],
    [3, 4, 8, 3, 5, 4, 3, 2, 5, 10, 5, 2, 11, 7, 6],
    [7, 2, 3, 7, 6, 2, 5, 4, 9],
    [9, 5, 4, 0, 8, 6, 0, 6, 2, 6, 8, 7],
    [3, 6, 2, 3, 7, 6, 1, 5, 0, 5, 4, 0],
    [6, 2, 8, 6, 8, 7, 2, 1, 8, 4, 8, 5, 1, 5, 8],
    [9, 5, 4, 10, 1, 6, 1, 7, 6, 1, 3, 7],
    [1, 6, 10, 1, 7, 6, 1, 0, 7, 8, 7, 0, 9, 5, 4],
    [4, 0, 10, 4, 10, 5, 0, 3, 10, 6, 10, 7, 3, 7, 10],
    [7, 6, 10, 7, 10, 8, 5, 4, 10, 4, 8, 10],
    [6, 9, 5, 6, 11, 9, 11, 8, 9],
    [3, 6, 11, 0, 6, 3, 0, 5, 6, 0, 9, 5],
    [0, 11, 8, 0, 5, 11, 0, 1, 5, 5, 6, 11],
    [6, 11, 3, 6, 3, 5, 5, 3, 1],
    [1, 2, 10, 9, 5, 11, 9, 11, 8, 11, 5, 6],
    [0, 11, 3, 0, 6, 11, 0, 9, 6, 5, 6, 9, 1, 2, 10],
    [11, 8, 5, 11, 5, 6, 8, 0, 5, 10, 5, 2, 0, 2, 5],
    [6, 11, 3, 6, 3, 5, 2, 10, 3, 10, 5, 3],
    [5, 8, 9, 5, 2, 8, 5, 6, 2, 3, 8, 2],
    [9, 5, 6, 9, 6, 0, 0, 6, 2],
    [1, 5, 8, 1, 8, 0, 5, 6, 8, 3, 8, 2, 6, 2, 8],
    [1, 5, 6, 2, 1, 6],
    [1, 3, 6, 1, 6, 10, 3, 8, 6, 5, 6, 9, 8, 9, 6],
    [10, 1, 0, 10, 0, 6, 9, 5, 0, 5, 6, 0],
    [0, 3, 8, 5, 6, 10],
    [10, 5, 6],
    [11, 5, 10, 7, 5, 11],
    [11, 5, 10, 11, 7, 5, 8, 3, 0],
    [5, 11, 7, 5, 10, 11, 1, 9, 0],
    [10, 7, 5, 10, 11, 7, 9, 8, 1, 8, 3, 1],
    [11, 1, 2, 11, 7, 1, 7, 5, 1],
    [0, 8, 3, 1, 2, 7, 1, 7, 5, 7, 2, 11],
    [9, 7, 5, 9, 2, 7, 9, 0, 2, 2, 11, 7],
    [7, 5, 2, 7, 2, 11, 5, 9, 2, 3, 2, 8, 9, 8, 2],
    [2, 5, 10, 2, 3, 5, 3, 7, 5],
    [8, 2, 0, 8, 5, 2, 8, 7, 5, 10, 2, 5],
    [9, 0, 1, 5, 10, 3, 5, 3, 7, 3, 10, 2],
    [9, 8, 2, 9, 2, 1, 8, 7, 2, 10, 2, 5, 7, 5, 2],
    [1, 3, 5, 3, 7, 5],
    [0, 8, 7, 0, 7, 1, 1, 7, 5],
    [9, 0, 3, 9, 3, 5, 5, 3, 7],
    [9, 8, 7, 5, 9, 7],
    [5, 8, 4, 5, 10, 8, 10, 11, 8],
    [5, 0, 4, 5, 11, 0, 5, 10, 11, 11, 3, 0],
    [0, 1, 9, 8, 4, 10, 8, 10, 11, 10, 4, 5],
    [10, 11, 4, 10, 4, 5, 11, 3, 4, 9, 4, 1, 3, 1, 4],
    [2, 5, 1, 2, 8, 5, 2, 11, 8, 4, 5, 8],
    [0, 4, 11, 0, 11, 3, 4, 5, 11, 2, 11, 1, 5, 1, 11],
    [0, 2, 5, 0, 5, 9, 2, 11, 5, 4, 5, 8, 11, 8, 5],
    [9, 4, 5, 2, 11, 3],
    [2, 5, 10, 3, 5, 2, 3, 4, 5, 3, 8, 4],
    [5, 10, 2, 5, 2, 4, 4, 2, 0],
    [3, 10, 2, 3, 5, 10, 3, 8, 5, 4, 5, 8, 0, 1, 9],
    [5, 10, 2, 5, 2, 4, 1, 9, 2, 9, 4, 2],
    [8, 4, 5, 8, 5, 3, 3, 5, 1],
    [0, 4, 5, 1, 0, 5],
    [8, 4, 5, 8, 5, 3, 9, 0, 5, 0, 3, 5],
    [9, 4, 5],
    [4, 11, 7, 4, 9, 11, 9, 10, 11],
    [0, 8, 3, 4, 9, 7, 9, 11, 7, 9, 10, 11],
    [1, 10, 11, 1, 11, 4, 1, 4, 0, 7, 4, 11],
    [3, 1, 4, 3, 4, 8, 1, 10, 4, 7, 4, 11, 10, 11, 4],
    [4, 11, 7, 9, 11, 4, 9, 2, 11, 9, 1, 2],
    [9, 7, 4, 9, 11, 7, 9, 1, 11, 2, 11, 1, 0, 8, 3],
    [11, 7, 4, 11, 4, 2, 2, 4, 0],
    [11, 7, 4, 11, 4, 2, 8, 3, 4, 3, 2, 4],
    [2, 9, 10, 2, 7, 9, 2, 3, 7, 7, 4, 9],
    [9, 10, 7, 9, 7, 4, 10, 2, 7, 8, 7, 0, 2, 0, 7],
    [3, 7, 10, 3, 10, 2, 7, 4, 10, 1, 10, 0, 4, 0, 10],
    [1, 10, 2, 8, 7, 4],
    [4, 9, 1, 4, 1, 7, 7, 1, 3],
    [4, 9, 1, 4, 1, 7, 0, 8, 1, 8, 7, 1],
    [4, 0, 3, 7, 4, 3],
    [4, 8, 7],
    [9, 10, 8, 10, 11, 8],
    [3, 0, 9, 3, 9, 11, 11, 9, 10],
    [0, 1, 10, 0, 10, 8, 8, 10, 11],
    [3, 1, 10, 11, 3, 10],
    [1, 2, 11, 1, 11, 9, 9, 11, 8],
    [3, 0, 9, 3, 9, 11, 1, 2, 9, 2, 11, 9],
    [0, 2, 11, 8, 0, 11],
    [3, 2, 11],
    [2, 3, 8, 2, 8, 10, 10, 8, 9],
    [9, 10, 2, 0, 9, 2],
    [2, 3, 8, 2, 8, 10, 0, 1, 8, 1, 10, 8],
    [1, 10, 2],
    [1, 3, 8, 9, 1, 8],
    [0, 9, 1],
    [0, 3, 8],
    []
];
/**
 * Triangles are constructed between points on cube edges.
 * AllowedContours[edge1][edge1] indicates which lines from a given
 * triangle should be shown in line mode.
 *
 * Values are bitmasks:
 * In loop over cubes we keep another bitmask indicating whether our current
 * cell is the first x-value (1),
 * first y-value (2) or first z-value (4) of the current loop.
 * We draw all lines on leading faces but only draw trailing face lines the first
 * time through the loop
 * A value of 8 below means the edge is always drawn (leading face)
 *
 * E.g. the first row, lines between edge0 and other edges in the bottom
 * x-y plane are only drawn for the first value of z, edges in the
 * x-z plane are only drawn for the first value of y. No other lines
 * are drawn as they're redundant
 * The line between edge 1 and 5 is always drawn as it's on the leading edge
 */
var AllowedContours = [
    [0, 4, 4, 4, 2, 0, 0, 0, 2, 2, 0, 0],
    [4, 0, 4, 4, 0, 8, 0, 0, 0, 8, 8, 0],
    [4, 4, 0, 4, 0, 0, 8, 0, 0, 0, 8, 8],
    [4, 4, 4, 0, 0, 0, 0, 1, 1, 0, 0, 1],
    [2, 0, 0, 0, 0, 8, 8, 8, 2, 2, 0, 0],
    [0, 8, 0, 0, 8, 0, 8, 8, 0, 8, 8, 0],
    [0, 0, 8, 0, 8, 8, 0, 8, 0, 0, 8, 8],
    [0, 0, 0, 1, 8, 8, 8, 0, 1, 0, 0, 1],
    [2, 0, 0, 1, 2, 0, 0, 1, 0, 2, 0, 1],
    [2, 8, 0, 0, 2, 8, 0, 0, 2, 0, 8, 0],
    [0, 8, 8, 0, 0, 8, 8, 0, 0, 8, 0, 8],
    [0, 0, 8, 1, 0, 0, 8, 1, 1, 0, 8, 0]
];
//# sourceMappingURL=tables.js.map

/***/ }),
/* 188 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FormatPropertyProvider; });
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var FormatRegistry = /** @class */ (function () {
    function FormatRegistry() {
        this.map = new Map();
        this.applicable = new Map();
    }
    FormatRegistry.prototype.add = function (kind, obtain, applicable) {
        this.map.set(kind, obtain);
        if (applicable)
            this.applicable.set(kind, applicable);
    };
    FormatRegistry.prototype.remove = function (kind) {
        this.map.delete(kind);
        this.applicable.delete(kind);
    };
    FormatRegistry.prototype.get = function (kind) {
        return this.map.get(kind);
    };
    FormatRegistry.prototype.isApplicable = function (model) {
        var isApplicable = this.applicable.get(model.sourceData.kind);
        return isApplicable ? isApplicable(model) : true;
    };
    return FormatRegistry;
}());

var FormatPropertyProvider;
(function (FormatPropertyProvider) {
    function create(descriptor) {
        var name = descriptor.name;
        var formatRegistry = new FormatRegistry();
        return {
            descriptor: descriptor,
            formatRegistry: formatRegistry,
            isApplicable: function (model) {
                return formatRegistry.isApplicable(model);
            },
            get: function (model) {
                if (model._staticPropertyData[name])
                    return model._staticPropertyData[name];
                if (model.customProperties.has(descriptor))
                    return;
                var obtain = formatRegistry.get(model.sourceData.kind);
                if (!obtain)
                    return;
                model._staticPropertyData[name] = obtain(model);
                model.customProperties.add(descriptor);
                return model._staticPropertyData[name];
            },
            set: function (model, value) {
                model._staticPropertyData[name] = value;
            }
        };
    }
    FormatPropertyProvider.create = create;
})(FormatPropertyProvider || (FormatPropertyProvider = {}));
//# sourceMappingURL=property.js.map

/***/ }),
/* 189 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BindingsHelp", function() { return BindingsHelp; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelpText", function() { return HelpText; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelpGroup", function() { return HelpGroup; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ViewportHelpContent", function() { return ViewportHelpContent; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HelpContent", function() { return HelpContent; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mol_util_binding__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(59);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(32);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(13);
/* harmony import */ var _mol_plugin_behavior_dynamic_representation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(223);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(14);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(19);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









function getBindingsList(bindings) {
    return Object.keys(bindings).map(function (k) { return [k, bindings[k]]; });
}
var BindingsHelp = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BindingsHelp, _super);
    function BindingsHelp() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    BindingsHelp.prototype.getBindingComponents = function () {
        var bindingsList = getBindingsList(this.props.bindings);
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null, bindingsList.map(function (value) {
            var name = value[0], binding = value[1];
            return !_mol_util_binding__WEBPACK_IMPORTED_MODULE_2__[/* Binding */ "a"].isEmpty(binding)
                ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { key: name, style: { marginBottom: '6px' } },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null, binding.action),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("br", null),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { dangerouslySetInnerHTML: { __html: _mol_util_binding__WEBPACK_IMPORTED_MODULE_2__[/* Binding */ "a"].format(binding, name) } }))
                : null;
        }));
    };
    BindingsHelp.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null, this.getBindingComponents());
    };
    return BindingsHelp;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var HelpText = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HelpText, _super);
    function HelpText() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    HelpText.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-help-text' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null, this.props.children));
    };
    return HelpText;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

var HelpGroup = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HelpGroup, _super);
    function HelpGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            header: _this.props.header,
            isExpanded: !!_this.props.initiallyExpanded
        };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        return _this;
    }
    HelpGroup.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-wrapper' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-group-header' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["Button"], { onClick: this.toggleExpanded },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_6__["Icon"], { svg: this.state.isExpanded ? _controls_icons__WEBPACK_IMPORTED_MODULE_6__["ArrowDropDownSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_6__["ArrowRightSvg"] }),
                    this.props.header)),
            this.state.isExpanded && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-offset', style: { display: this.state.isExpanded ? 'block' : 'none' } }, this.props.children));
    };
    return HelpGroup;
}(react__WEBPACK_IMPORTED_MODULE_1__["PureComponent"]));

function HelpSection(props) {
    return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-simple-help-section' }, props.header);
}
var ViewportHelpContent = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ViewportHelpContent, _super);
    function ViewportHelpContent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ViewportHelpContent.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
    };
    ViewportHelpContent.prototype.render = function () {
        var interactionBindings = {};
        this.plugin.spec.behaviors.forEach(function (b) {
            var bindings = b.defaultParams.bindings;
            if (bindings)
                Object.assign(interactionBindings, bindings);
        });
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            (!this.props.selectOnly && this.plugin.canvas3d) && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { key: 'trackball', header: 'Moving in 3D' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](BindingsHelp, { bindings: this.plugin.canvas3d.props.trackball.bindings })),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { key: 'interactions', header: 'Mouse Controls' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](BindingsHelp, { bindings: interactionBindings })));
    };
    return ViewportHelpContent;
}(_base__WEBPACK_IMPORTED_MODULE_3__["PluginUIComponent"]));

var HelpContent = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HelpContent, _super);
    function HelpContent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    HelpContent.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
    };
    HelpContent.prototype.formatTriggers = function (binding) {
        return binding.triggers.map(function (t) { return _mol_util_binding__WEBPACK_IMPORTED_MODULE_2__[/* Binding */ "a"].Trigger.format(t); }).join(' or ');
    };
    HelpContent.prototype.getTriggerFor = function (transformer, name) {
        var state = this.plugin.state.behaviors;
        var selections = state.select(_mol_state__WEBPACK_IMPORTED_MODULE_4__["StateSelection"].Generators.ofTransformer(transformer));
        var params = selections.length === 1 ? selections[0].params : undefined;
        var bindings = params ? params.values.bindings : {};
        var binding = name in bindings ? bindings[name] : _mol_util_binding__WEBPACK_IMPORTED_MODULE_2__[/* Binding */ "a"].Empty;
        return this.formatTriggers(binding);
    };
    HelpContent.prototype.render = function () {
        var selectToggleTriggers = this.getTriggerFor(_mol_plugin_behavior_dynamic_representation__WEBPACK_IMPORTED_MODULE_5__["SelectLoci"], 'clickSelectToggle');
        var focusTriggers = this.getTriggerFor(_mol_plugin_behavior_dynamic_representation__WEBPACK_IMPORTED_MODULE_5__["FocusLoci"], 'clickFocus');
        // TODO: interactive help, for example for density
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpSection, { header: 'Interface Controls' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Inline Help' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null, "Many user interface elements show a little questionmark icon when hovered over. Clicking the icon toggles the display of an inline help text."),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null, "Tooltips may provide additional information on a user interface element and are shown when hovering over it with the mouse.")),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Selections' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null,
                    "The viewer allows changing colors and representations for selections of atoms, residues or chains. Selections can be created by",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("ul", { style: { paddingLeft: '20px' } },
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("li", null,
                            "picking elements on the 3D canvas or the sequence view using the mouse, e.g. toggle selection using ",
                            selectToggleTriggers,
                            " (for more see help section on ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Mouse Controls"),
                            ")"),
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("li", null,
                            "using the ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Add"),
                            ", ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Remove"),
                            " and ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Only"),
                            " dropdown buttons in the ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Manage Selection"),
                            " panel which allow modifing the current selection by predefined sets")))),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Coloring' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null,
                    "There are two ways to color structures. Every representation (e.g. cartoon or spacefill) has a color theme which can be changed using the dropdown for each representation in the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Structure Settings"),
                    " panel. Additionally any selection atoms, residues or chains can by given a custom color. For that, first select the parts of the structure to be colored (see help section on ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Selections"),
                    ") and, second, choose a color from the color dropdown botton in the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Selection"),
                    " row of the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Change Representation"),
                    " panel. The theme color can be seen as a base color that is overpainted by the custom color. Custom colors can be removed for a selection with the 'Clear' option in the color dropdown.")),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Representations' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null,
                    "Structures can be shown with many different representations (e.g. cartoon or spacefill). The ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Change Representation"),
                    " panel offers a collection of predefined styles which can be applied using the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Preset"),
                    " dropdown button. Additionally any selection atoms, residues or chains can by shown with a custom representation. For that, first select the parts of the structure to be mofified (see help section on ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Selections"),
                    ") and, second, choose a representation to hide or show from the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Show"),
                    " and ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Hide"),
                    " dropdown bottons in the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Selection"),
                    " row of the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Change Representation"),
                    " panel. The ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Everything"),
                    " row applies the action to the whole structure instead of the current selection.")),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Surroundings' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null,
                    "To show the surroundings of a residue or ligand, click it in the 3D scene or in the sequence widget using ",
                    focusTriggers,
                    ".")),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpSection, { header: 'How-to Guides' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpGroup, { header: 'Create an Image' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpText, null,
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", null,
                        "Use the ",
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_6__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_6__["CameraSvg"] }),
                        " icon in the viewport to bring up the screenshot controls."),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", null,
                        "To adjust the size of the image, use the ",
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("i", null, "Resolution"),
                        " dropdown."))),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](HelpSection, { header: 'Mouse Controls' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ViewportHelpContent, null));
    };
    return HelpContent;
}(_base__WEBPACK_IMPORTED_MODULE_3__["PluginUIComponent"]));

//# sourceMappingURL=help.js.map

/***/ }),
/* 190 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return NotificationKind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Notification; });
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(133);
/* harmony import */ var _observable_of__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(254);
/* harmony import */ var _observable_throwError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(295);
/** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */



var NotificationKind;
/*@__PURE__*/ (function (NotificationKind) {
    NotificationKind["NEXT"] = "N";
    NotificationKind["ERROR"] = "E";
    NotificationKind["COMPLETE"] = "C";
})(NotificationKind || (NotificationKind = {}));
var Notification = /*@__PURE__*/ (function () {
    function Notification(kind, value, error) {
        this.kind = kind;
        this.value = value;
        this.error = error;
        this.hasValue = kind === 'N';
    }
    Notification.prototype.observe = function (observer) {
        switch (this.kind) {
            case 'N':
                return observer.next && observer.next(this.value);
            case 'E':
                return observer.error && observer.error(this.error);
            case 'C':
                return observer.complete && observer.complete();
        }
    };
    Notification.prototype.do = function (next, error, complete) {
        var kind = this.kind;
        switch (kind) {
            case 'N':
                return next && next(this.value);
            case 'E':
                return error && error(this.error);
            case 'C':
                return complete && complete();
        }
    };
    Notification.prototype.accept = function (nextOrObserver, error, complete) {
        if (nextOrObserver && typeof nextOrObserver.next === 'function') {
            return this.observe(nextOrObserver);
        }
        else {
            return this.do(nextOrObserver, error, complete);
        }
    };
    Notification.prototype.toObservable = function () {
        var kind = this.kind;
        switch (kind) {
            case 'N':
                return Object(_observable_of__WEBPACK_IMPORTED_MODULE_1__[/* of */ "a"])(this.value);
            case 'E':
                return Object(_observable_throwError__WEBPACK_IMPORTED_MODULE_2__[/* throwError */ "a"])(this.error);
            case 'C':
                return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_0__[/* empty */ "b"])();
        }
        throw new Error('unexpected notification kind value');
    };
    Notification.createNext = function (value) {
        if (typeof value !== 'undefined') {
            return new Notification('N', value);
        }
        return Notification.undefinedValueNotification;
    };
    Notification.createError = function (err) {
        return new Notification('E', undefined, err);
    };
    Notification.createComplete = function () {
        return Notification.completeNotification;
    };
    Notification.completeNotification = new Notification('C');
    Notification.undefinedValueNotification = new Notification('N', undefined);
    return Notification;
}());

//# sourceMappingURL=Notification.js.map


/***/ }),
/* 191 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Transformer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _transform__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(76);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _action__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(340);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var Transformer;
(function (Transformer) {
    function getParamDefinition(t, a, globalCtx) {
        return t.definition.params ? t.definition.params(a, globalCtx) : {};
    }
    Transformer.getParamDefinition = getParamDefinition;
    function is(obj) {
        return !!obj && typeof obj.toAction === 'function' && typeof obj.apply === 'function';
    }
    Transformer.is = is;
    var UpdateResult;
    (function (UpdateResult) {
        UpdateResult[UpdateResult["Unchanged"] = 0] = "Unchanged";
        UpdateResult[UpdateResult["Updated"] = 1] = "Updated";
        UpdateResult[UpdateResult["Recreate"] = 2] = "Recreate";
        UpdateResult[UpdateResult["Null"] = 3] = "Null";
    })(UpdateResult = Transformer.UpdateResult || (Transformer.UpdateResult = {}));
    var registry = new Map();
    var fromTypeIndex = new Map();
    function _index(tr) {
        for (var _i = 0, _a = tr.definition.from; _i < _a.length; _i++) {
            var t = _a[_i];
            if (fromTypeIndex.has(t.type)) {
                fromTypeIndex.get(t.type).push(tr);
            }
            else {
                fromTypeIndex.set(t.type, [tr]);
            }
        }
    }
    function getAll() {
        return Array.from(registry.values());
    }
    Transformer.getAll = getAll;
    function get(id) {
        var t = registry.get(id);
        if (!t) {
            throw new Error("A transformer with signature '" + id + "' is not registered.");
        }
        return t;
    }
    Transformer.get = get;
    function fromType(type) {
        return fromTypeIndex.get(type) || [];
    }
    Transformer.fromType = fromType;
    function create(namespace, definition) {
        var name = definition.name;
        var id = namespace + "." + name;
        if (registry.has(id)) {
            throw new Error("A transform with id '" + name + "' is already registered. Please pick a unique identifier for your transforms and/or register them only once. This is to ensure that transforms can be serialized and replayed.");
        }
        var t = {
            apply: function (parent, params, props) { return _transform__WEBPACK_IMPORTED_MODULE_1__[/* StateTransform */ "a"].create(parent, t, params, props); },
            toAction: function () { return _action__WEBPACK_IMPORTED_MODULE_3__[/* StateAction */ "a"].fromTransformer(t); },
            namespace: namespace,
            id: id,
            definition: definition,
            createDefaultParams: function (a, globalCtx) { return definition.params ? _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(definition.params(a, globalCtx)) : {}; }
        };
        registry.set(id, t);
        _index(t);
        return t;
    }
    Transformer.create = create;
    function factory(namespace) {
        return function (definition) { return create(namespace, definition); };
    }
    Transformer.factory = factory;
    function builderFactory(namespace) {
        return Builder.build(namespace);
    }
    Transformer.builderFactory = builderFactory;
    var Builder;
    (function (Builder) {
        function root(namespace, info) {
            return function (def) { return create(namespace, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ name: info.name, from: info.from instanceof Array ? info.from : [info.from], to: info.to instanceof Array ? info.to : [info.to], display: typeof info.display === 'string'
                    ? { name: info.display }
                    : !!info.display
                        ? info.display
                        : { name: Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* capitalize */ "b"])(info.name.replace(/[-]/g, ' ')) }, params: typeof info.params === 'object'
                    ? function () { return info.params; }
                    : !!info.params
                        ? info.params
                        : void 0, isDecorator: info.isDecorator }, def)); };
        }
        function build(namespace) {
            return function (info) { return root(namespace, info); };
        }
        Builder.build = build;
    })(Builder = Transformer.Builder || (Transformer.Builder = {}));
    function build(namespace) {
        return Builder.build(namespace);
    }
    Transformer.build = build;
    Transformer.ROOT = create('build-in', {
        name: 'root',
        from: [],
        to: [],
        display: { name: 'Root', description: 'For internal use.' },
        apply: function () { throw new Error('should never be applied'); },
        update: function () { return UpdateResult.Unchanged; }
    });
})(Transformer || (Transformer = {}));
//# sourceMappingURL=transformer.js.map

/***/ }),
/* 192 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SimpleBuffer; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var SimpleBuffer;
(function (SimpleBuffer) {
    function fromUint8Array(array) {
        var dv = new DataView(array.buffer);
        return Object.assign(array.subarray(0), {
            readInt8: function (offset) { return dv.getInt8(offset); },
            readUInt8: function (offset) { return dv.getUint8(offset); },
            writeInt8: function (value, offset) { return dv.setInt8(offset, value); },
            writeUInt8: function (value, offset) { return dv.setUint8(offset, value); },
            readInt16LE: function (offset) { return dv.getInt16(offset, true); },
            readInt32LE: function (offset) { return dv.getInt32(offset, true); },
            readUInt16LE: function (offset) { return dv.getUint16(offset, true); },
            readUInt32LE: function (offset) { return dv.getUint32(offset, true); },
            readFloatLE: function (offset) { return dv.getFloat32(offset, true); },
            readDoubleLE: function (offset) { return dv.getFloat64(offset, true); },
            writeInt16LE: function (value, offset) { return dv.setInt16(offset, value, true); },
            writeInt32LE: function (value, offset) { return dv.setInt32(offset, value, true); },
            writeUInt16LE: function (value, offset) { return dv.setUint16(offset, value, true); },
            writeUInt32LE: function (value, offset) { return dv.setUint32(offset, value, true); },
            writeFloatLE: function (value, offset) { return dv.setFloat32(offset, value, true); },
            writeDoubleLE: function (value, offset) { return dv.setFloat64(offset, value, true); },
            readInt16BE: function (offset) { return dv.getInt16(offset, false); },
            readInt32BE: function (offset) { return dv.getInt32(offset, false); },
            readUInt16BE: function (offset) { return dv.getUint16(offset, false); },
            readUInt32BE: function (offset) { return dv.getUint32(offset, false); },
            readFloatBE: function (offset) { return dv.getFloat32(offset, false); },
            readDoubleBE: function (offset) { return dv.getFloat64(offset, false); },
            writeInt16BE: function (value, offset) { return dv.setInt16(offset, value, false); },
            writeInt32BE: function (value, offset) { return dv.setInt32(offset, value, false); },
            writeUInt16BE: function (value, offset) { return dv.setUint16(offset, value, false); },
            writeUInt32BE: function (value, offset) { return dv.setUint32(offset, value, false); },
            writeFloatBE: function (value, offset) { return dv.setFloat32(offset, value, false); },
            writeDoubleBE: function (value, offset) { return dv.setFloat64(offset, value, false); },
            copy: function (targetBuffer, targetStart, sourceStart, sourceEnd) {
                targetStart = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(targetStart, 0);
                sourceStart = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(sourceStart, 0);
                sourceEnd = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(sourceEnd, array.length);
                targetBuffer.set(array.subarray(sourceStart, sourceEnd), targetStart);
                return sourceEnd - sourceStart;
            }
        });
    }
    SimpleBuffer.fromUint8Array = fromUint8Array;
    function fromArrayBuffer(arrayBuffer) {
        return fromUint8Array(new Uint8Array(arrayBuffer));
    }
    SimpleBuffer.fromArrayBuffer = fromArrayBuffer;
    function fromBuffer(buffer) {
        return buffer;
    }
    SimpleBuffer.fromBuffer = fromBuffer;
    SimpleBuffer.IsNativeEndianLittle = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412;
    /** source and target can't be the same */
    function flipByteOrder(source, target, byteCount, elementByteSize, offset) {
        for (var i = 0, n = byteCount; i < n; i += elementByteSize) {
            for (var j = 0; j < elementByteSize; j++) {
                target[offset + i + elementByteSize - j - 1] = source[offset + i + j];
            }
        }
    }
    SimpleBuffer.flipByteOrder = flipByteOrder;
    function flipByteOrderInPlace2(buffer, byteOffset, length) {
        if (byteOffset === void 0) { byteOffset = 0; }
        var intView = new Int16Array(buffer, byteOffset, length);
        for (var i = 0, n = intView.length; i < n; ++i) {
            var val = intView[i];
            intView[i] = ((val & 0xff) << 8) | ((val >> 8) & 0xff);
        }
    }
    SimpleBuffer.flipByteOrderInPlace2 = flipByteOrderInPlace2;
    function ensureLittleEndian(source, target, byteCount, elementByteSize, offset) {
        if (SimpleBuffer.IsNativeEndianLittle)
            return;
        if (!byteCount || elementByteSize <= 1)
            return;
        flipByteOrder(source, target, byteCount, elementByteSize, offset);
    }
    SimpleBuffer.ensureLittleEndian = ensureLittleEndian;
})(SimpleBuffer || (SimpleBuffer = {}));
//# sourceMappingURL=simple-buffer.js.map

/***/ }),
/* 193 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TypedArrayValueType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getElementByteSize; });
/* unused harmony export makeTypedArray */
/* unused harmony export createTypedArray */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createTypedArrayBufferContext; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return readTypedArray; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(192);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Taken/adapted from DensityServer (https://github.com/dsehnal/DensityServer)
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var TypedArrayValueType;
(function (TypedArrayValueType) {
    TypedArrayValueType.Float32 = 'float32';
    TypedArrayValueType.Int8 = 'int8';
    TypedArrayValueType.Int16 = 'int16';
    TypedArrayValueType.Uint16 = 'uint16';
})(TypedArrayValueType || (TypedArrayValueType = {}));
function getElementByteSize(type) {
    if (type === TypedArrayValueType.Float32)
        return 4;
    if (type === TypedArrayValueType.Int16)
        return 2;
    if (type === TypedArrayValueType.Uint16)
        return 2;
    return 1;
}
function makeTypedArray(type, buffer, byteOffset, length) {
    if (byteOffset === void 0) { byteOffset = 0; }
    if (type === TypedArrayValueType.Float32)
        return new Float32Array(buffer, byteOffset, length);
    if (type === TypedArrayValueType.Int16)
        return new Int16Array(buffer, byteOffset, length);
    if (type === TypedArrayValueType.Uint16)
        return new Uint16Array(buffer, byteOffset, length);
    return new Int8Array(buffer, byteOffset, length);
}
function createTypedArray(type, size) {
    switch (type) {
        case TypedArrayValueType.Float32: return new Float32Array(new ArrayBuffer(4 * size));
        case TypedArrayValueType.Int8: return new Int8Array(new ArrayBuffer(1 * size));
        case TypedArrayValueType.Int16: return new Int16Array(new ArrayBuffer(2 * size));
        case TypedArrayValueType.Uint16: return new Uint16Array(new ArrayBuffer(2 * size));
    }
    throw Error(type + " is not a supported value format.");
}
function createTypedArrayBufferContext(size, type) {
    var elementByteSize = getElementByteSize(type);
    var arrayBuffer = new ArrayBuffer(elementByteSize * size);
    var readBuffer = _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].fromArrayBuffer(arrayBuffer);
    var valuesBuffer = _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].IsNativeEndianLittle ? arrayBuffer : new ArrayBuffer(elementByteSize * size);
    return {
        type: type,
        elementByteSize: elementByteSize,
        readBuffer: readBuffer,
        valuesBuffer: new Uint8Array(valuesBuffer),
        values: makeTypedArray(type, valuesBuffer)
    };
}
function readTypedArray(ctx, file, position, byteCount, valueByteOffset, littleEndian) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, file.readBuffer(position, ctx.readBuffer, byteCount, valueByteOffset)];
                case 1:
                    _a.sent();
                    if (ctx.elementByteSize > 1 && ((littleEndian !== void 0 && littleEndian !== _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].IsNativeEndianLittle) || !_mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].IsNativeEndianLittle)) {
                        // fix the endian
                        _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].flipByteOrder(ctx.readBuffer, ctx.valuesBuffer, byteCount, ctx.elementByteSize, valueByteOffset);
                    }
                    return [2 /*return*/, ctx.values];
            }
        });
    });
}
//# sourceMappingURL=typed-array.js.map

/***/ }),
/* 194 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {/* harmony import */ var _mol_util_now__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(83);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var UUID;
(function (UUID) {
    var _btoa = typeof btoa !== 'undefined' ? btoa : function (s) { return Buffer.from(s).toString('base64'); };
    var chars = [];
    /** Creates a 22 characters 'base64' encoded UUID */
    function create22() {
        var d = (+new Date()) + Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_0__[/* now */ "b"])();
        for (var i = 0; i < 16; i++) {
            chars[i] = String.fromCharCode((d + Math.random() * 0xff) % 0xff | 0);
            d = Math.floor(d / 0xff);
        }
        return _btoa(chars.join('')).replace(/\+/g, '-').replace(/\//g, '_').substr(0, 22);
    }
    UUID.create22 = create22;
    function createv4() {
        var d = (+new Date()) + Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_0__[/* now */ "b"])();
        var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (d + Math.random() * 16) % 16 | 0;
            d = Math.floor(d / 16);
            return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
        });
        return uuid;
    }
    UUID.createv4 = createv4;
    function is(x) {
        return typeof x === 'string';
    }
    UUID.is = is;
})(UUID || (UUID = {}));
/* harmony default export */ __webpack_exports__["a"] = (UUID);
//# sourceMappingURL=uuid.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(426).Buffer))

/***/ }),
/* 195 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CentroidHelper; });
/* harmony import */ var _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(25);
/* harmony import */ var _primitives_sphere3d__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(274);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var CentroidHelper = /** @class */ (function () {
    function CentroidHelper() {
        this.count = 0;
        this.center = Object(_mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"])();
        this.radiusSq = 0;
    }
    CentroidHelper.prototype.reset = function () {
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].set(this.center, 0, 0, 0);
        this.radiusSq = 0;
        this.count = 0;
    };
    CentroidHelper.prototype.includeStep = function (p) {
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].add(this.center, this.center, p);
        this.count++;
    };
    CentroidHelper.prototype.finishedIncludeStep = function () {
        if (this.count === 0)
            return;
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].scale(this.center, this.center, 1 / this.count);
    };
    CentroidHelper.prototype.radiusStep = function (p) {
        var d = _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].squaredDistance(p, this.center);
        if (d > this.radiusSq)
            this.radiusSq = d;
    };
    CentroidHelper.prototype.radiusSphereStep = function (center, radius) {
        var _d = _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].distance(center, this.center) + radius;
        var d = _d * _d;
        if (d > this.radiusSq)
            this.radiusSq = d;
    };
    CentroidHelper.prototype.getSphere = function (sphere) {
        if (!sphere)
            sphere = Object(_primitives_sphere3d__WEBPACK_IMPORTED_MODULE_1__[/* Sphere3D */ "a"])();
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].copy(sphere.center, this.center);
        sphere.radius = Math.sqrt(this.radiusSq);
        return sphere;
    };
    CentroidHelper.prototype.getCount = function () {
        return this.count;
    };
    return CentroidHelper;
}());
(function (CentroidHelper) {
    var helper = new CentroidHelper();
    var posA = Object(_mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"])();
    var posB = Object(_mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"])();
    function fromArrays(_a, to) {
        var x = _a.x, y = _a.y, z = _a.z;
        helper.reset();
        var n = x.length;
        for (var i = 0; i < n; i++) {
            _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].set(posA, x[i], y[i], z[i]);
            helper.includeStep(posA);
        }
        helper.finishedIncludeStep();
        for (var i = 0; i < n; i++) {
            _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].set(posA, x[i], y[i], z[i]);
            helper.radiusStep(posA);
        }
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].copy(to.center, helper.center);
        to.radius = Math.sqrt(helper.radiusSq);
        return to;
    }
    CentroidHelper.fromArrays = fromArrays;
    function fromProvider(count, getter, to) {
        helper.reset();
        for (var i = 0; i < count; i++) {
            getter(i, posA);
            helper.includeStep(posA);
        }
        helper.finishedIncludeStep();
        for (var i = 0; i < count; i++) {
            getter(i, posA);
            helper.radiusStep(posA);
        }
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].copy(to.center, helper.center);
        to.radius = Math.sqrt(helper.radiusSq);
        return to;
    }
    CentroidHelper.fromProvider = fromProvider;
    function fromPairProvider(count, getter, to) {
        helper.reset();
        for (var i = 0; i < count; i++) {
            getter(i, posA, posB);
            helper.includeStep(posA);
            helper.includeStep(posB);
        }
        helper.finishedIncludeStep();
        for (var i = 0; i < count; i++) {
            getter(i, posA, posB);
            helper.radiusStep(posA);
            helper.radiusStep(posB);
        }
        _mol_math_linear_algebra_3d__WEBPACK_IMPORTED_MODULE_0__[/* Vec3 */ "f"].copy(to.center, helper.center);
        to.radius = Math.sqrt(helper.radiusSq);
        return to;
    }
    CentroidHelper.fromPairProvider = fromPairProvider;
})(CentroidHelper || (CentroidHelper = {}));
//# sourceMappingURL=centroid-helper.js.map

/***/ }),
/* 196 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ color_ColorTheme; });

// UNUSED EXPORTS: ColorThemeProvider

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/constants.js
var constants = __webpack_require__(178);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/legend.js
var mol_util_legend = __webpack_require__(141);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/carbohydrate-symbol.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var Description = 'Assigns colors according to the Symbol Nomenclature for Glycans (SNFG).';
var CarbohydrateSymbolColorThemeParams = {};
function getCarbohydrateSymbolColorThemeParams(ctx) {
    return CarbohydrateSymbolColorThemeParams; // TODO return copy
}
function CarbohydrateSymbolColorTheme(ctx, props) {
    var color;
    if (ctx.structure) {
        var _a = ctx.structure.carbohydrates, elements_1 = _a.elements, getElementIndices_1 = _a.getElementIndices;
        var getColor_1 = function (unit, index) {
            if (!mol_model_structure["Unit"].isAtomic(unit))
                return DefaultColor;
            var carbs = getElementIndices_1(unit, index);
            return carbs.length > 0 ? elements_1[carbs[0]].component.color : DefaultColor;
        };
        color = function (location, isSecondary) {
            if (isSecondary) {
                return constants["b" /* SaccharideColors */].Secondary;
            }
            else {
                if (mol_model_structure["StructureElement"].Location.is(location)) {
                    return getColor_1(location.unit, location.element);
                }
                else if (mol_model_structure["Bond"].isLocation(location)) {
                    return getColor_1(location.aUnit, location.aUnit.elements[location.aIndex]);
                }
            }
            return DefaultColor;
        };
    }
    else {
        color = function () { return DefaultColor; };
    }
    return {
        factory: CarbohydrateSymbolColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: Description,
        legend: Object(mol_util_legend["b" /* TableLegend */])(constants["a" /* MonosaccharidesColorTable */])
    };
}
var CarbohydrateSymbolColorThemeProvider = {
    name: 'carbohydrate-symbol',
    label: 'Carbohydrate Symbol',
    category: "Residue Property" /* Residue */,
    factory: CarbohydrateSymbolColorTheme,
    getParams: getCarbohydrateSymbolColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(CarbohydrateSymbolColorThemeParams),
    isApplicable: function (ctx) {
        return !!ctx.structure && ctx.structure.models.some(function (m) { return mol_model_structure["Model"].hasCarbohydrate(m); });
    }
};
//# sourceMappingURL=carbohydrate-symbol.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color/uniform.js
var uniform = __webpack_require__(355);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/theme.js
var theme = __webpack_require__(89);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color/chain-id.js
var chain_id = __webpack_require__(327);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/palette.js + 1 modules
var color_palette = __webpack_require__(111);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/element-index.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var element_index_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var element_index_Description = 'Gives every element (atom or coarse sphere/gaussian) a unique color based on the position (index) of the element in the list of elements in the structure.';
var ElementIndexColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: 'red-yellow-blue' }));
function getElementIndexColorThemeParams(ctx) {
    return ElementIndexColorThemeParams; // TODO return copy
}
function ElementIndexColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var units_1 = ctx.structure.root.units;
        var unitCount = units_1.length;
        var cummulativeElementCount_1 = new Map();
        var unitIdIndex_1 = new Map();
        var elementCount = 0;
        for (var i = 0; i < unitCount; ++i) {
            cummulativeElementCount_1.set(i, elementCount);
            elementCount += units_1[i].elements.length;
            unitIdIndex_1.set(units_1[i].id, i);
        }
        var palette_1 = Object(color_palette["a" /* getPalette */])(elementCount, props);
        legend = palette_1.legend;
        color = function (location) {
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                var unitIndex = unitIdIndex_1.get(location.unit.id);
                var unitElementIndex = mol_data_int["OrderedSet"].findPredecessorIndex(units_1[unitIndex].elements, location.element);
                return palette_1.color(cummulativeElementCount_1.get(unitIndex) + unitElementIndex);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                var unitIndex = unitIdIndex_1.get(location.aUnit.id);
                var unitElementIndex = mol_data_int["OrderedSet"].findPredecessorIndex(units_1[unitIndex].elements, location.aUnit.elements[location.aIndex]);
                return palette_1.color(cummulativeElementCount_1.get(unitIndex) + unitElementIndex);
            }
            return element_index_DefaultColor;
        };
    }
    else {
        color = function () { return element_index_DefaultColor; };
    }
    return {
        factory: ElementIndexColorTheme,
        granularity: 'groupInstance',
        color: color,
        props: props,
        description: element_index_Description,
        legend: legend
    };
}
var ElementIndexColorThemeProvider = {
    name: 'element-index',
    label: 'Element Index',
    category: "Atom Property" /* Atom */,
    factory: ElementIndexColorTheme,
    getParams: getElementIndexColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(ElementIndexColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=element-index.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color/element-symbol.js
var element_symbol = __webpack_require__(307);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/util.js
var util = __webpack_require__(147);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/color.js
var color_color = __webpack_require__(43);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/molecule-type.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var MoleculeTypeColors = Object(mol_util_color["ColorMap"])({
    water: 0x386cb0,
    ion: 0xf0027f,
    protein: 0xbeaed4,
    RNA: 0xfdc086,
    DNA: 0xbf5b17,
    PNA: 0x42A49A,
    saccharide: 0x7fc97f,
});
var DefaultMoleculeTypeColor = Object(mol_util_color["Color"])(0xffff99);
var molecule_type_Description = 'Assigns a color based on the molecule type of a residue.';
var MoleculeTypeColorThemeParams = {
    saturation: param_definition["ParamDefinition"].Numeric(0, { min: -6, max: 6, step: 0.1 }),
    lightness: param_definition["ParamDefinition"].Numeric(0, { min: -6, max: 6, step: 0.1 })
};
function getMoleculeTypeColorThemeParams(ctx) {
    return MoleculeTypeColorThemeParams; // TODO return copy
}
function moleculeTypeColor(colorMap, unit, element) {
    var moleculeType = Object(util["b" /* getElementMoleculeType */])(unit, element);
    switch (moleculeType) {
        case 2 /* Water */: return colorMap.water;
        case 3 /* Ion */: return colorMap.ion;
        case 5 /* Protein */: return colorMap.protein;
        case 6 /* RNA */: return colorMap.RNA;
        case 7 /* DNA */: return colorMap.DNA;
        case 8 /* PNA */: return colorMap.PNA;
        case 9 /* Saccharide */: return colorMap.saccharide;
    }
    return DefaultMoleculeTypeColor;
}
function MoleculeTypeColorTheme(ctx, props) {
    var colorMap = Object(color_color["getAdjustedColorMap"])(MoleculeTypeColors, props.saturation, props.lightness);
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            return moleculeTypeColor(colorMap, location.unit, location.element);
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            return moleculeTypeColor(colorMap, location.aUnit, location.aUnit.elements[location.aIndex]);
        }
        return DefaultMoleculeTypeColor;
    }
    return {
        factory: MoleculeTypeColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: molecule_type_Description,
        legend: Object(mol_util_legend["b" /* TableLegend */])(Object.keys(MoleculeTypeColors).map(function (name) {
            return [name, MoleculeTypeColors[name]];
        }).concat([['Other/unknown', DefaultMoleculeTypeColor]]))
    };
}
var MoleculeTypeColorThemeProvider = {
    name: 'molecule-type',
    label: 'Molecule Type',
    category: "Residue Property" /* Residue */,
    factory: MoleculeTypeColorTheme,
    getParams: getMoleculeTypeColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(MoleculeTypeColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=molecule-type.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/lists.js
var lists = __webpack_require__(88);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/polymer-id.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var DefaultList = 'dark-2';
var polymer_id_DefaultColor = Object(mol_util_color["Color"])(0xFAFAFA);
var polymer_id_Description = 'Gives every polymer chain a color based on its `asym_id` value.';
var PolymerIdColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: DefaultList }));
function getPolymerIdColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(PolymerIdColorThemeParams);
    if (ctx.structure) {
        if (getPolymerAsymIdSerialMap(ctx.structure.root).size > lists["ColorLists"][DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(DefaultList).list } });
        }
    }
    return params;
}
function getAsymId(unit) {
    switch (unit.kind) {
        case 0 /* Atomic */:
            return mol_model_structure["StructureProperties"].chain.label_asym_id;
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            return mol_model_structure["StructureProperties"].coarse.asym_id;
    }
}
function getPolymerAsymIdSerialMap(structure) {
    var map = new Map();
    for (var i = 0, il = structure.unitSymmetryGroups.length; i < il; ++i) {
        var unit = structure.unitSymmetryGroups[i].units[0];
        var model = unit.model;
        if (mol_model_structure["Unit"].isAtomic(unit)) {
            var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, chains = _a.chains;
            var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, unit.elements);
            while (chainIt.hasNext) {
                var chainIndex = chainIt.move().index;
                var entityId = chains.label_entity_id.value(chainIndex);
                var eI = model.entities.getEntityIndex(entityId);
                if (model.entities.data.type.value(eI) === 'polymer') {
                    var asymId = chains.label_asym_id.value(chainIndex);
                    if (!map.has(asymId))
                        map.set(asymId, map.size);
                }
            }
        }
        else if (mol_model_structure["Unit"].isCoarse(unit)) {
            var _b = mol_model_structure["Unit"].isSpheres(unit)
                ? model.coarseHierarchy.spheres
                : model.coarseHierarchy.gaussians, chainElementSegments = _b.chainElementSegments, asym_id = _b.asym_id, entity_id = _b.entity_id;
            var chainIt = mol_data_int["Segmentation"].transientSegments(chainElementSegments, unit.elements);
            while (chainIt.hasNext) {
                var chainIndex = chainIt.move().index;
                var elementIndex = chainElementSegments.offsets[chainIndex];
                var entityId = entity_id.value(elementIndex);
                var eI = model.entities.getEntityIndex(entityId);
                if (model.entities.data.type.value(eI) === 'polymer') {
                    var asymId = asym_id.value(elementIndex);
                    if (!map.has(asymId))
                        map.set(asymId, map.size);
                }
            }
        }
    }
    return map;
}
function PolymerIdColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var l_1 = mol_model_structure["StructureElement"].Location.create(ctx.structure);
        var polymerAsymIdSerialMap_1 = getPolymerAsymIdSerialMap(ctx.structure.root);
        var labelTable_1 = Array.from(polymerAsymIdSerialMap_1.keys());
        props.palette.params.valueLabel = function (i) { return labelTable_1[i]; };
        var palette_1 = Object(color_palette["a" /* getPalette */])(polymerAsymIdSerialMap_1.size, props);
        legend = palette_1.legend;
        color = function (location) {
            var serial = undefined;
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                var asym_id = getAsymId(location.unit);
                serial = polymerAsymIdSerialMap_1.get(asym_id(location));
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                var asym_id = getAsymId(location.aUnit);
                l_1.unit = location.aUnit;
                l_1.element = location.aUnit.elements[location.aIndex];
                serial = polymerAsymIdSerialMap_1.get(asym_id(l_1));
            }
            return serial === undefined ? polymer_id_DefaultColor : palette_1.color(serial);
        };
    }
    else {
        color = function () { return polymer_id_DefaultColor; };
    }
    return {
        factory: PolymerIdColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: polymer_id_Description,
        legend: legend
    };
}
var PolymerIdColorThemeProvider = {
    name: 'polymer-id',
    label: 'Polymer Chain Id',
    category: "Chain Property" /* Chain */,
    factory: PolymerIdColorTheme,
    getParams: getPolymerIdColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(PolymerIdColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=polymer-id.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/polymer-index.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var polymer_index_DefaultList = 'dark-2';
var polymer_index_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var polymer_index_Description = 'Gives every polymer chain instance a unique color based on the position (index) of the polymer in the list of polymers in the structure.';
var PolymerIndexColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: polymer_index_DefaultList }));
function getPolymerIndexColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(PolymerIndexColorThemeParams);
    if (ctx.structure) {
        if (getPolymerChainCount(ctx.structure.root) > lists["ColorLists"][polymer_index_DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(polymer_index_DefaultList).list } });
        }
    }
    return params;
}
function getPolymerChainCount(structure) {
    var polymerChainCount = 0;
    var units = structure.units;
    for (var i = 0, il = units.length; i < il; ++i) {
        if (units[i].polymerElements.length > 0)
            ++polymerChainCount;
    }
    return polymerChainCount;
}
function PolymerIndexColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var palette = Object(color_palette["a" /* getPalette */])(getPolymerChainCount(ctx.structure.root), props);
        legend = palette.legend;
        var units = ctx.structure.root.units;
        var unitIdColor_1 = new Map();
        for (var i = 0, j = 0, il = units.length; i < il; ++i) {
            if (units[i].polymerElements.length > 0) {
                unitIdColor_1.set(units[i].id, palette.color(j));
                ++j;
            }
        }
        color = function (location) {
            var color;
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                color = unitIdColor_1.get(location.unit.id);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                color = unitIdColor_1.get(location.aUnit.id);
            }
            return color !== undefined ? color : polymer_index_DefaultColor;
        };
    }
    else {
        color = function () { return polymer_index_DefaultColor; };
    }
    return {
        factory: PolymerIndexColorTheme,
        granularity: 'instance',
        color: color,
        props: props,
        description: polymer_index_Description,
        legend: legend
    };
}
var PolymerIndexColorThemeProvider = {
    name: 'polymer-index',
    label: 'Polymer Chain Instance',
    category: "Chain Property" /* Chain */,
    factory: PolymerIndexColorTheme,
    getParams: getPolymerIndexColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(PolymerIndexColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=polymer-index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/residue-name.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





// protein colors from Jmol http://jmol.sourceforge.net/jscolors/
var ResidueNameColors = Object(mol_util_color["ColorMap"])({
    // standard amino acids
    'ALA': 0x8CFF8C,
    'ARG': 0x00007C,
    'ASN': 0xFF7C70,
    'ASP': 0xA00042,
    'CYS': 0xFFFF70,
    'GLN': 0xFF4C4C,
    'GLU': 0x660000,
    'GLY': 0xEEEEEE,
    'HIS': 0x7070FF,
    'ILE': 0x004C00,
    'LEU': 0x455E45,
    'LYS': 0x4747B8,
    'MET': 0xB8A042,
    'PHE': 0x534C52,
    'PRO': 0x525252,
    'SER': 0xFF7042,
    'THR': 0xB84C00,
    'TRP': 0x4F4600,
    'TYR': 0x8C704C,
    'VAL': 0xFF8CFF,
    // rna bases
    'A': 0xDC143C,
    'G': 0x32CD32,
    'I': 0x9ACD32,
    'C': 0xFFD700,
    'T': 0x4169E1,
    'U': 0x40E0D0,
    // dna bases
    'DA': 0xDC143C,
    'DG': 0x32CD32,
    'DI': 0x9ACD32,
    'DC': 0xFFD700,
    'DT': 0x4169E1,
    'DU': 0x40E0D0,
    // peptide bases
    'APN': 0xDC143C,
    'GPN': 0x32CD32,
    'CPN': 0xFFD700,
    'TPN': 0x4169E1,
});
var DefaultResidueNameColor = Object(mol_util_color["Color"])(0xFF00FF);
var residue_name_Description = 'Assigns a color to every residue according to its name.';
var ResidueNameColorThemeParams = {
    saturation: param_definition["ParamDefinition"].Numeric(0, { min: -6, max: 6, step: 0.1 }),
    lightness: param_definition["ParamDefinition"].Numeric(1, { min: -6, max: 6, step: 0.1 })
};
function getResidueNameColorThemeParams(ctx) {
    return ResidueNameColorThemeParams; // TODO return copy
}
function getAtomicCompId(unit, element) {
    return unit.model.atomicHierarchy.atoms.label_comp_id.value(unit.residueIndex[element]);
}
function getCoarseCompId(unit, element) {
    var seqIdBegin = unit.coarseElements.seq_id_begin.value(element);
    var seqIdEnd = unit.coarseElements.seq_id_end.value(element);
    if (seqIdBegin === seqIdEnd) {
        var entityKey = unit.coarseElements.entityKey[element];
        var seq = unit.model.sequence.byEntityKey[entityKey].sequence;
        return seq.compId.value(seqIdBegin - 1); // 1-indexed
    }
}
function residueNameColor(colorMap, residueName) {
    var c = colorMap[residueName];
    return c === undefined ? DefaultResidueNameColor : c;
}
function ResidueNameColorTheme(ctx, props) {
    var colorMap = Object(color_color["getAdjustedColorMap"])(ResidueNameColors, props.saturation, props.lightness);
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.unit)) {
                var compId = getAtomicCompId(location.unit, location.element);
                return residueNameColor(colorMap, compId);
            }
            else {
                var compId = getCoarseCompId(location.unit, location.element);
                if (compId)
                    return residueNameColor(colorMap, compId);
            }
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.aUnit)) {
                var compId = getAtomicCompId(location.aUnit, location.aUnit.elements[location.aIndex]);
                return residueNameColor(colorMap, compId);
            }
            else {
                var compId = getCoarseCompId(location.aUnit, location.aUnit.elements[location.aIndex]);
                if (compId)
                    return residueNameColor(colorMap, compId);
            }
        }
        return DefaultResidueNameColor;
    }
    return {
        factory: ResidueNameColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: residue_name_Description,
        legend: Object(mol_util_legend["b" /* TableLegend */])(Object.keys(ResidueNameColors).map(function (name) {
            return [name, ResidueNameColors[name]];
        }).concat([['Unknown', DefaultResidueNameColor]]))
    };
}
var ResidueNameColorThemeProvider = {
    name: 'residue-name',
    label: 'Residue Name',
    category: "Residue Property" /* Residue */,
    factory: ResidueNameColorTheme,
    getParams: getResidueNameColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(ResidueNameColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=residue-name.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure.js + 12 modules
var secondary_structure = __webpack_require__(152);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/secondary-structure.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








// from Jmol http://jmol.sourceforge.net/jscolors/ (shapely)
var SecondaryStructureColors = Object(mol_util_color["ColorMap"])({
    'alphaHelix': 0xFF0080,
    'threeTenHelix': 0xA00080,
    'piHelix': 0x600080,
    'betaTurn': 0x6080FF,
    'betaStrand': 0xFFC800,
    'coil': 0xFFFFFF,
    'bend': 0x66D8C9 /* biting original color used 0x00FF00 */,
    'turn': 0x00B266,
    'dna': 0xAE00FE,
    'rna': 0xFD0162,
    'carbohydrate': 0xA6A6FA
});
var DefaultSecondaryStructureColor = Object(mol_util_color["Color"])(0x808080);
var secondary_structure_Description = 'Assigns a color based on the type of secondary structure and basic molecule type.';
var SecondaryStructureColorThemeParams = {
    saturation: param_definition["ParamDefinition"].Numeric(-1, { min: -6, max: 6, step: 0.1 }),
    lightness: param_definition["ParamDefinition"].Numeric(0, { min: -6, max: 6, step: 0.1 })
};
function getSecondaryStructureColorThemeParams(ctx) {
    return SecondaryStructureColorThemeParams; // TODO return copy
}
function secondaryStructureColor(colorMap, unit, element, computedSecondaryStructure) {
    var secStrucType = types["SecondaryStructureType"].create(0 /* None */);
    if (computedSecondaryStructure && mol_model_structure["Unit"].isAtomic(unit)) {
        var secondaryStructure = computedSecondaryStructure.get(unit.invariantId);
        if (secondaryStructure)
            secStrucType = secondaryStructure.type[secondaryStructure.getIndex(unit.residueIndex[element])];
    }
    if (types["SecondaryStructureType"].is(secStrucType, 2 /* Helix */)) {
        if (types["SecondaryStructureType"].is(secStrucType, 2048 /* Helix3Ten */)) {
            return colorMap.threeTenHelix;
        }
        else if (types["SecondaryStructureType"].is(secStrucType, 32768 /* HelixPi */)) {
            return colorMap.piHelix;
        }
        return colorMap.alphaHelix;
    }
    else if (types["SecondaryStructureType"].is(secStrucType, 4 /* Beta */)) {
        return colorMap.betaStrand;
    }
    else if (types["SecondaryStructureType"].is(secStrucType, 8 /* Bend */)) {
        return colorMap.bend;
    }
    else if (types["SecondaryStructureType"].is(secStrucType, 16 /* Turn */)) {
        return colorMap.turn;
    }
    else {
        var moleculeType = Object(util["b" /* getElementMoleculeType */])(unit, element);
        if (moleculeType === 7 /* DNA */) {
            return colorMap.dna;
        }
        else if (moleculeType === 6 /* RNA */) {
            return colorMap.rna;
        }
        else if (moleculeType === 9 /* Saccharide */) {
            return colorMap.carbohydrate;
        }
        else if (moleculeType === 5 /* Protein */) {
            return colorMap.coil;
        }
    }
    return DefaultSecondaryStructureColor;
}
function SecondaryStructureColorTheme(ctx, props) {
    var computedSecondaryStructure = ctx.structure && secondary_structure["a" /* SecondaryStructureProvider */].get(ctx.structure);
    var contextHash = computedSecondaryStructure && computedSecondaryStructure.version;
    var colorMap = Object(color_color["getAdjustedColorMap"])(SecondaryStructureColors, props.saturation, props.lightness);
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            return secondaryStructureColor(colorMap, location.unit, location.element, computedSecondaryStructure === null || computedSecondaryStructure === void 0 ? void 0 : computedSecondaryStructure.value);
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            return secondaryStructureColor(colorMap, location.aUnit, location.aUnit.elements[location.aIndex], computedSecondaryStructure === null || computedSecondaryStructure === void 0 ? void 0 : computedSecondaryStructure.value);
        }
        return DefaultSecondaryStructureColor;
    }
    return {
        factory: SecondaryStructureColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        contextHash: contextHash,
        description: secondary_structure_Description,
        legend: Object(mol_util_legend["b" /* TableLegend */])(Object.keys(SecondaryStructureColors).map(function (name) {
            return [name, SecondaryStructureColors[name]];
        }).concat([['Other', DefaultSecondaryStructureColor]]))
    };
}
var SecondaryStructureColorThemeProvider = {
    name: 'secondary-structure',
    label: 'Secondary Structure',
    category: "Residue Property" /* Residue */,
    factory: SecondaryStructureColorTheme,
    getParams: getSecondaryStructureColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(SecondaryStructureColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? secondary_structure["a" /* SecondaryStructureProvider */].attach(ctx, data.structure, void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.customPropertyDescriptors.reference(secondary_structure["a" /* SecondaryStructureProvider */].descriptor, false); }
    }
};
//# sourceMappingURL=secondary-structure.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/sequence-id.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var sequence_id_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var sequence_id_Description = 'Gives every polymer residue a color based on its `seq_id` value.';
var SequenceIdColorThemeParams = {
    list: param_definition["ParamDefinition"].ColorList('turbo', { presetKind: 'scale' }),
};
function getSequenceIdColorThemeParams(ctx) {
    return SequenceIdColorThemeParams; // TODO return copy
}
function getSeqId(unit, element) {
    var model = unit.model;
    switch (unit.kind) {
        case 0 /* Atomic */:
            var residueIndex = model.atomicHierarchy.residueAtomSegments.index[element];
            return model.atomicHierarchy.residues.label_seq_id.value(residueIndex);
        case 1 /* Spheres */:
            return Math.round((model.coarseHierarchy.spheres.seq_id_begin.value(element) +
                model.coarseHierarchy.spheres.seq_id_end.value(element)) / 2);
        case 2 /* Gaussians */:
            return Math.round((model.coarseHierarchy.gaussians.seq_id_begin.value(element) +
                model.coarseHierarchy.gaussians.seq_id_end.value(element)) / 2);
    }
}
function getSequenceLength(unit, element) {
    var model = unit.model;
    var entityId = '';
    switch (unit.kind) {
        case 0 /* Atomic */:
            var chainIndex = model.atomicHierarchy.chainAtomSegments.index[element];
            entityId = model.atomicHierarchy.chains.label_entity_id.value(chainIndex);
            break;
        case 1 /* Spheres */:
            entityId = model.coarseHierarchy.spheres.entity_id.value(element);
            break;
        case 2 /* Gaussians */:
            entityId = model.coarseHierarchy.gaussians.entity_id.value(element);
            break;
    }
    if (entityId === '')
        return 0;
    var entityIndex = model.entities.getEntityIndex(entityId);
    if (entityIndex === -1)
        return 0;
    return model.sequence.byEntityKey[entityIndex].sequence.length;
}
function SequenceIdColorTheme(ctx, props) {
    var scale = mol_util_color["ColorScale"].create({
        listOrName: props.list.colors,
        minLabel: 'Start',
        maxLabel: 'End',
    });
    var color = function (location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            var unit = location.unit, element = location.element;
            var seq_id = getSeqId(unit, element);
            if (seq_id > 0) {
                scale.setDomain(0, getSequenceLength(unit, element) - 1);
                return scale.color(seq_id);
            }
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            var aUnit = location.aUnit, aIndex = location.aIndex;
            var seq_id = getSeqId(aUnit, aUnit.elements[aIndex]);
            if (seq_id > 0) {
                scale.setDomain(0, getSequenceLength(aUnit, aUnit.elements[aIndex]) - 1);
                return scale.color(seq_id);
            }
        }
        return sequence_id_DefaultColor;
    };
    return {
        factory: SequenceIdColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: sequence_id_Description,
        legend: scale ? scale.legend : undefined
    };
}
var SequenceIdColorThemeProvider = {
    name: 'sequence-id',
    label: 'Sequence Id',
    category: "Residue Property" /* Residue */,
    factory: SequenceIdColorTheme,
    getParams: getSequenceIdColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(SequenceIdColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=sequence-id.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color/shape-group.js
var shape_group = __webpack_require__(361);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/unit-index.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var unit_index_DefaultList = 'dark-2';
var unit_index_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var unit_index_Description = 'Gives every chain instance (single chain or collection of single elements) a unique color based on the position (index) of the chain in the list of chains in the structure.';
var UnitIndexColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: unit_index_DefaultList }));
function getUnitIndexColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(UnitIndexColorThemeParams);
    if (ctx.structure) {
        if (ctx.structure.root.units.length > lists["ColorLists"][unit_index_DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(unit_index_DefaultList).list } });
        }
    }
    return params;
}
function UnitIndexColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var units = ctx.structure.root.units;
        var palette = Object(color_palette["a" /* getPalette */])(units.length, props);
        legend = palette.legend;
        var unitIdColor_1 = new Map();
        for (var i = 0, il = units.length; i < il; ++i) {
            unitIdColor_1.set(units[i].id, palette.color(i));
        }
        color = function (location) {
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                return unitIdColor_1.get(location.unit.id);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                return unitIdColor_1.get(location.aUnit.id);
            }
            return unit_index_DefaultColor;
        };
    }
    else {
        color = function () { return unit_index_DefaultColor; };
    }
    return {
        factory: UnitIndexColorTheme,
        granularity: 'instance',
        color: color,
        props: props,
        description: unit_index_Description,
        legend: legend
    };
}
var UnitIndexColorThemeProvider = {
    name: 'unit-index',
    label: 'Chain Instance',
    category: "Chain Property" /* Chain */,
    factory: UnitIndexColorTheme,
    getParams: getUnitIndexColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(UnitIndexColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=unit-index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/uncertainty.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DefaultUncertaintyColor = Object(mol_util_color["Color"])(0xffff99);
var uncertainty_Description = "Assigns a color based on the uncertainty or disorder of an element's position, e.g. B-factor or RMSF, depending on the data availability and experimental technique.";
var UncertaintyColorThemeParams = {
    domain: param_definition["ParamDefinition"].Interval([0, 100]),
    list: param_definition["ParamDefinition"].ColorList('red-white-blue', { presetKind: 'scale' }),
};
function getUncertaintyColorThemeParams(ctx) {
    return UncertaintyColorThemeParams; // TODO return copy
}
function getUncertainty(unit, element) {
    if (mol_model_structure["Unit"].isAtomic(unit)) {
        return unit.model.atomicConformation.B_iso_or_equiv.value(element);
    }
    else if (mol_model_structure["Unit"].isSpheres(unit)) {
        return unit.model.coarseConformation.spheres.rmsf[element];
    }
    else {
        return 0;
    }
}
function UncertaintyColorTheme(ctx, props) {
    var scale = mol_util_color["ColorScale"].create({
        reverse: true,
        domain: props.domain,
        listOrName: props.list.colors,
    });
    // TODO calc domain based on data, set min/max as 10/90 percentile to be robust against outliers
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            return scale.color(getUncertainty(location.unit, location.element));
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            return scale.color(getUncertainty(location.aUnit, location.aUnit.elements[location.aIndex]));
        }
        return DefaultUncertaintyColor;
    }
    return {
        factory: UncertaintyColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: uncertainty_Description,
        legend: scale ? scale.legend : undefined
    };
}
var UncertaintyColorThemeProvider = {
    name: 'uncertainty',
    label: 'Uncertainty/Disorder',
    category: "Atom Property" /* Atom */,
    factory: UncertaintyColorTheme,
    getParams: getUncertaintyColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(UncertaintyColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure && ctx.structure.models.some(function (m) { return m.atomicConformation.B_iso_or_equiv.isDefined || m.coarseHierarchy.isDefined; }); }
};
//# sourceMappingURL=uncertainty.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/number.js
var number = __webpack_require__(174);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/entity-source.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var entity_source_DefaultList = 'dark-2';
var entity_source_DefaultColor = Object(mol_util_color["Color"])(0xFAFAFA);
var entity_source_Description = 'Gives ranges of a polymer chain a color based on the entity source it originates from (e.g. gene, plasmid, organism).';
var EntitySourceColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: entity_source_DefaultList }));
function getEntitySourceColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(EntitySourceColorThemeParams);
    if (ctx.structure) {
        if (getMaps(ctx.structure.root.models).srcKeySerialMap.size > lists["ColorLists"][entity_source_DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(entity_source_DefaultList).list } });
        }
    }
    return params;
}
function modelEntityKey(modelIndex, entityId) {
    return modelIndex + "|" + entityId;
}
function srcKey(modelIndex, entityId, organism, srcId, plasmid, gene) {
    return modelIndex + "|" + entityId + "|" + organism + "|" + (gene ? gene : (plasmid ? plasmid : srcId));
}
function addSrc(seqToSrcByModelEntity, srcKeySerialMap, modelIndex, model, entity_src, scientific_name, plasmid_name, gene_src_gene) {
    var entity_id = entity_src.entity_id, pdbx_src_id = entity_src.pdbx_src_id, pdbx_beg_seq_num = entity_src.pdbx_beg_seq_num, pdbx_end_seq_num = entity_src.pdbx_end_seq_num;
    for (var j = 0, jl = entity_src._rowCount; j < jl; ++j) {
        var entityId = entity_id.value(j);
        var mK = modelEntityKey(modelIndex, entityId);
        var seqToSrc = void 0;
        if (!seqToSrcByModelEntity.has(mK)) {
            var entityIndex = model.entities.getEntityIndex(entityId);
            var seq = model.sequence.sequences[entityIndex].sequence;
            seqToSrc = new Int16Array(seq.length);
            seqToSrcByModelEntity.set(mK, seqToSrc);
        }
        else {
            seqToSrc = seqToSrcByModelEntity.get(mK);
        }
        var plasmid = plasmid_name ? plasmid_name.value(j) : '';
        var gene = gene_src_gene ? gene_src_gene.value(j)[0] : '';
        var sK = srcKey(modelIndex, entityId, scientific_name.value(j), pdbx_src_id.value(j), plasmid, gene);
        // may not be given (= 0) indicating src is for the whole seq
        var beg = pdbx_beg_seq_num.valueKind(j) === 0 /* Present */ ? pdbx_beg_seq_num.value(j) : 1;
        var end = pdbx_end_seq_num.valueKind(j) === 0 /* Present */ ? pdbx_end_seq_num.value(j) : seqToSrc.length;
        var srcIndex = void 0; // serial no starting from 1
        if (srcKeySerialMap.has(sK)) {
            srcIndex = srcKeySerialMap.get(sK);
        }
        else {
            srcIndex = srcKeySerialMap.size + 1;
            srcKeySerialMap.set(sK, srcIndex);
        }
        // set src index
        for (var i = beg, il = end; i <= il; ++i) {
            seqToSrc[i - 1] = srcIndex;
        }
    }
}
function getMaps(models) {
    var seqToSrcByModelEntity = new Map();
    var srcKeySerialMap = new Map(); // serial no starting from 1
    for (var i = 0, il = models.length; i < il; ++i) {
        var m = models[i];
        if (!mmcif["MmcifFormat"].is(m.sourceData))
            continue;
        var _a = m.sourceData.data.db, entity_src_gen = _a.entity_src_gen, entity_src_nat = _a.entity_src_nat, pdbx_entity_src_syn = _a.pdbx_entity_src_syn;
        addSrc(seqToSrcByModelEntity, srcKeySerialMap, i, m, entity_src_gen, entity_src_gen.pdbx_gene_src_scientific_name, entity_src_gen.plasmid_name, entity_src_gen.pdbx_gene_src_gene);
        addSrc(seqToSrcByModelEntity, srcKeySerialMap, i, m, entity_src_nat, entity_src_nat.pdbx_organism_scientific, entity_src_nat.pdbx_plasmid_name);
        addSrc(seqToSrcByModelEntity, srcKeySerialMap, i, m, pdbx_entity_src_syn, pdbx_entity_src_syn.organism_scientific);
    }
    return { seqToSrcByModelEntity: seqToSrcByModelEntity, srcKeySerialMap: srcKeySerialMap };
}
function getLabelTable(srcKeySerialMap) {
    var unnamedCount = 0;
    return Array.from(srcKeySerialMap.keys()).map(function (v) {
        var vs = v.split('|');
        var organism = vs[2];
        var name = Object(number["d" /* isInteger */])(vs[3]) ? "Unnamed " + ++unnamedCount : vs[3];
        return "" + name + (organism ? " (" + organism + ")" : '');
    });
}
function EntitySourceColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var l_1 = mol_model_structure["StructureElement"].Location.create(ctx.structure);
        var models_1 = ctx.structure.root.models;
        var _a = getMaps(models_1), seqToSrcByModelEntity_1 = _a.seqToSrcByModelEntity, srcKeySerialMap = _a.srcKeySerialMap;
        var labelTable_1 = getLabelTable(srcKeySerialMap);
        props.palette.params.valueLabel = function (i) { return labelTable_1[i]; };
        var palette_1 = Object(color_palette["a" /* getPalette */])(srcKeySerialMap.size, props);
        legend = palette_1.legend;
        var getSrcColor_1 = function (location) {
            var modelIndex = models_1.indexOf(location.unit.model);
            var entityId = mol_model_structure["StructureProperties"].entity.id(location);
            var mK = modelEntityKey(modelIndex, entityId);
            var seqToSrc = seqToSrcByModelEntity_1.get(mK);
            if (seqToSrc) {
                // minus 1 to convert seqId to array index
                return palette_1.color(seqToSrc[mol_model_structure["StructureProperties"].residue.label_seq_id(location) - 1] - 1);
            }
            else {
                return entity_source_DefaultColor;
            }
        };
        color = function (location) {
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                return getSrcColor_1(location);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                l_1.unit = location.aUnit;
                l_1.element = location.aUnit.elements[location.aIndex];
                return getSrcColor_1(l_1);
            }
            return entity_source_DefaultColor;
        };
    }
    else {
        color = function () { return entity_source_DefaultColor; };
    }
    return {
        factory: EntitySourceColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: entity_source_Description,
        legend: legend
    };
}
var EntitySourceColorThemeProvider = {
    name: 'entity-source',
    label: 'Entity Source',
    category: "Chain Property" /* Chain */,
    factory: EntitySourceColorTheme,
    getParams: getEntitySourceColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(EntitySourceColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=entity-source.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/illustrative.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var DefaultIllustrativeColor = Object(mol_util_color["Color"])(0xFFFFFF);
var illustrative_Description = "Assigns an illustrative color similar to David Goodsell's Molecule of the Month style.";
var IllustrativeColorThemeParams = {};
function getIllustrativeColorThemeParams(ctx) {
    return IllustrativeColorThemeParams; // TODO return copy
}
function illustrativeColor(colorMap, typeSymbol, moleculeType) {
    if (Object(types["isNucleic"])(moleculeType)) {
        if (typeSymbol === 'O') {
            return Object(mol_util_color["Color"])(0xFF8C8C);
        }
        else if (typeSymbol === 'P') {
            return Object(mol_util_color["Color"])(0xFF7D7D);
        }
        else {
            return Object(mol_util_color["Color"])(0xFFA6A6);
        }
    }
    else if (Object(types["isProtein"])(moleculeType)) {
        if (typeSymbol === 'C') {
            return Object(mol_util_color["Color"])(0x7FB2FF);
        }
        else {
            return Object(mol_util_color["Color"])(0x6699FF);
        }
    }
    else {
        return Object(element_symbol["elementSymbolColor"])(colorMap, typeSymbol);
    }
}
function IllustrativeColorTheme(ctx, props) {
    var colorMap = Object(color_color["getAdjustedColorMap"])(element_symbol["ElementSymbolColors"], 0, 0.7);
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.unit)) {
                var moleculeType = location.unit.model.atomicHierarchy.derived.residue.moleculeType[location.unit.residueIndex[location.element]];
                var typeSymbol = location.unit.model.atomicHierarchy.atoms.type_symbol.value(location.element);
                return illustrativeColor(colorMap, typeSymbol, moleculeType);
            }
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.aUnit)) {
                var elementIndex = location.aUnit.elements[location.aIndex];
                var moleculeType = location.aUnit.model.atomicHierarchy.derived.residue.moleculeType[location.aUnit.residueIndex[elementIndex]];
                var typeSymbol = location.aUnit.model.atomicHierarchy.atoms.type_symbol.value(elementIndex);
                return illustrativeColor(colorMap, typeSymbol, moleculeType);
            }
        }
        return DefaultIllustrativeColor;
    }
    return {
        factory: IllustrativeColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: illustrative_Description,
    };
}
var IllustrativeColorThemeProvider = {
    name: 'illustrative',
    label: 'Illustrative',
    category: "Miscellaneous" /* Misc */,
    factory: IllustrativeColorTheme,
    getParams: getIllustrativeColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(IllustrativeColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=illustrative.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/hydrophobicity.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var hydrophobicity_Description = 'Assigns a color to every amino acid according to the "Experimentally determined hydrophobicity scale for proteins at membrane interfaces" by Wimely and White (doi:10.1038/nsb1096-842).';
var HydrophobicityColorThemeParams = {
    list: param_definition["ParamDefinition"].ColorList('red-yellow-green', { presetKind: 'scale' }),
    scale: param_definition["ParamDefinition"].Select('DGwif', [['DGwif', 'DG water-membrane'], ['DGwoct', 'DG water-octanol'], ['Oct-IF', 'DG difference']])
};
function getHydrophobicityColorThemeParams(ctx) {
    return HydrophobicityColorThemeParams; // TODO return copy
}
var scaleIndexMap = { 'DGwif': 0, 'DGwoct': 1, 'Oct-IF': 2 };
function hydrophobicity(compId, scaleIndex) {
    var c = types["ResidueHydrophobicity"][compId];
    return c === undefined ? 0 : c[scaleIndex];
}
function hydrophobicity_getAtomicCompId(unit, element) {
    return unit.model.atomicHierarchy.atoms.label_comp_id.value(unit.residueIndex[element]);
}
function hydrophobicity_getCoarseCompId(unit, element) {
    var seqIdBegin = unit.coarseElements.seq_id_begin.value(element);
    var seqIdEnd = unit.coarseElements.seq_id_end.value(element);
    if (seqIdBegin === seqIdEnd) {
        var entityKey = unit.coarseElements.entityKey[element];
        var seq = unit.model.sequence.byEntityKey[entityKey].sequence;
        return seq.compId.value(seqIdBegin - 1); // 1-indexed
    }
}
function HydrophobicityColorTheme(ctx, props) {
    var scaleIndex = scaleIndexMap[props.scale];
    // get domain
    var min = Infinity;
    var max = -Infinity;
    for (var name_1 in types["ResidueHydrophobicity"]) {
        var val = types["ResidueHydrophobicity"][name_1][scaleIndex];
        min = Math.min(min, val);
        max = Math.max(max, val);
    }
    var scale = mol_util_color["ColorScale"].create({
        listOrName: props.list.colors,
        domain: [max, min],
        minLabel: 'Hydrophobic',
        maxLabel: 'Hydrophilic'
    });
    function color(location) {
        var compId;
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.unit)) {
                compId = hydrophobicity_getAtomicCompId(location.unit, location.element);
            }
            else {
                compId = hydrophobicity_getCoarseCompId(location.unit, location.element);
            }
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            if (mol_model_structure["Unit"].isAtomic(location.aUnit)) {
                compId = hydrophobicity_getAtomicCompId(location.aUnit, location.aUnit.elements[location.aIndex]);
            }
            else {
                compId = hydrophobicity_getCoarseCompId(location.aUnit, location.aUnit.elements[location.aIndex]);
            }
        }
        return scale.color(compId ? hydrophobicity(compId, scaleIndex) : 0);
    }
    return {
        factory: HydrophobicityColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: hydrophobicity_Description,
        legend: scale ? scale.legend : undefined
    };
}
var HydrophobicityColorThemeProvider = {
    name: 'hydrophobicity',
    label: 'Hydrophobicity',
    category: "Residue Property" /* Residue */,
    factory: HydrophobicityColorTheme,
    getParams: getHydrophobicityColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(HydrophobicityColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=hydrophobicity.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/model-index.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var model_index_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var model_index_Description = 'Gives every model a unique color based on the position (index) of the model in the list of models in the structure.';
var ModelIndexColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: 'purples' }));
function getModelIndexColorThemeParams(ctx) {
    return ModelIndexColorThemeParams; // TODO return copy
}
function ModelIndexColorTheme(ctx, props) {
    var _a, _b;
    var color;
    var legend;
    if (ctx.structure) {
        var models = ctx.structure.root.models;
        var size = 0;
        for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
            var m = models_1[_i];
            size = Math.max(size, ((_a = mol_model_structure["Model"].TrajectoryInfo.get(m)) === null || _a === void 0 ? void 0 : _a.size) || 0);
        }
        var palette = Object(color_palette["a" /* getPalette */])(size, props);
        legend = palette.legend;
        var modelColor_1 = new Map();
        for (var i = 0, il = models.length; i < il; ++i) {
            var idx = ((_b = mol_model_structure["Model"].TrajectoryInfo.get(models[i])) === null || _b === void 0 ? void 0 : _b.index) || 0;
            modelColor_1.set(idx, palette.color(idx));
        }
        color = function (location) {
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                return modelColor_1.get(mol_model_structure["Model"].TrajectoryInfo.get(location.unit.model).index);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                return modelColor_1.get(mol_model_structure["Model"].TrajectoryInfo.get(location.aUnit.model).index);
            }
            return model_index_DefaultColor;
        };
    }
    else {
        color = function () { return model_index_DefaultColor; };
    }
    return {
        factory: ModelIndexColorTheme,
        granularity: 'instance',
        color: color,
        props: props,
        description: model_index_Description,
        legend: legend
    };
}
var ModelIndexColorThemeProvider = {
    name: 'model-index',
    label: 'Model Index',
    category: "Chain Property" /* Chain */,
    factory: ModelIndexColorTheme,
    getParams: getModelIndexColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(ModelIndexColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure && ctx.structure.elementCount > 0 && mol_model_structure["Model"].TrajectoryInfo.get(ctx.structure.models[0]).size > 1; }
};
//# sourceMappingURL=model-index.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/occupancy.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DefaultOccupancyColor = Object(mol_util_color["Color"])(0xCCCCCC);
var occupancy_Description = "Assigns a color based on the occupancy of an atom.";
var OccupancyColorThemeParams = {
    domain: param_definition["ParamDefinition"].Interval([0, 1]),
    list: param_definition["ParamDefinition"].ColorList('purples', { presetKind: 'scale' }),
};
function getOccupancyColorThemeParams(ctx) {
    return OccupancyColorThemeParams; // TODO return copy
}
function getOccupancy(unit, element) {
    if (mol_model_structure["Unit"].isAtomic(unit)) {
        return unit.model.atomicConformation.occupancy.value(element);
    }
    else {
        return 0;
    }
}
function OccupancyColorTheme(ctx, props) {
    var scale = mol_util_color["ColorScale"].create({
        reverse: false,
        domain: props.domain,
        listOrName: props.list.colors,
    });
    function color(location) {
        if (mol_model_structure["StructureElement"].Location.is(location)) {
            return scale.color(getOccupancy(location.unit, location.element));
        }
        else if (mol_model_structure["Bond"].isLocation(location)) {
            return scale.color(getOccupancy(location.aUnit, location.aUnit.elements[location.aIndex]));
        }
        return DefaultOccupancyColor;
    }
    return {
        factory: OccupancyColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: occupancy_Description,
        legend: scale ? scale.legend : undefined
    };
}
var OccupancyColorThemeProvider = {
    name: 'occupancy',
    label: 'Occupancy',
    category: "Atom Property" /* Atom */,
    factory: OccupancyColorTheme,
    getParams: getOccupancyColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(OccupancyColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure && ctx.structure.models.some(function (m) { return m.atomicConformation.occupancy.isDefined; }); }
};
//# sourceMappingURL=occupancy.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/operator-name.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var operator_name_DefaultList = 'dark-2';
var operator_name_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var operator_name_Description = "Assigns a color based on the operator name of a transformed chain.";
var OperatorNameColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: operator_name_DefaultList }));
function getOperatorNameColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(OperatorNameColorThemeParams);
    if (ctx.structure) {
        if (getOperatorNameSerialMap(ctx.structure.root).size > lists["ColorLists"][operator_name_DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(operator_name_DefaultList).list } });
        }
    }
    return params;
}
function getOperatorNameSerialMap(structure) {
    var map = new Map();
    for (var i = 0, il = structure.units.length; i < il; ++i) {
        var name_1 = structure.units[i].conformation.operator.name;
        if (!map.has(name_1))
            map.set(name_1, map.size);
    }
    return map;
}
function OperatorNameColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var operatorNameSerialMap_1 = getOperatorNameSerialMap(ctx.structure.root);
        var labelTable_1 = Array.from(operatorNameSerialMap_1.keys());
        props.palette.params.valueLabel = function (i) { return labelTable_1[i]; };
        var palette_1 = Object(color_palette["a" /* getPalette */])(operatorNameSerialMap_1.size, props);
        legend = palette_1.legend;
        color = function (location) {
            var serial = undefined;
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                var name_2 = location.unit.conformation.operator.name;
                serial = operatorNameSerialMap_1.get(name_2);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                var name_3 = location.aUnit.conformation.operator.name;
                serial = operatorNameSerialMap_1.get(name_3);
            }
            return serial === undefined ? operator_name_DefaultColor : palette_1.color(serial);
        };
    }
    else {
        color = function () { return operator_name_DefaultColor; };
    }
    return {
        factory: OperatorNameColorTheme,
        granularity: 'instance',
        color: color,
        props: props,
        description: operator_name_Description,
        legend: legend
    };
}
var OperatorNameColorThemeProvider = {
    name: 'operator-name',
    label: 'Operator Name',
    category: "Symmetry" /* Symmetry */,
    factory: OperatorNameColorTheme,
    getParams: getOperatorNameColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(OperatorNameColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=operator-name.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color/operator-hkl.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var operator_hkl_DefaultList = 'dark-2';
var operator_hkl_DefaultColor = Object(mol_util_color["Color"])(0xCCCCCC);
var operator_hkl_Description = "Assigns a color based on the operator HKL value of a transformed chain.";
var OperatorHklColorThemeParams = Object(tslib_es6["__assign"])({}, Object(color_palette["b" /* getPaletteParams */])({ type: 'colors', colorList: operator_hkl_DefaultList }));
function getOperatorHklColorThemeParams(ctx) {
    var params = param_definition["ParamDefinition"].clone(OperatorHklColorThemeParams);
    if (ctx.structure) {
        if (getOperatorHklSerialMap(ctx.structure.root).map.size > lists["ColorLists"][operator_hkl_DefaultList].list.length) {
            params.palette.defaultValue.name = 'colors';
            params.palette.defaultValue.params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.palette.defaultValue.params), { list: { kind: 'interpolate', colors: Object(lists["getColorListFromName"])(operator_hkl_DefaultList).list } });
        }
    }
    return params;
}
var hklOffset = 10000;
function hklKey(hkl) {
    return hkl.map(function (v) { return ("" + (v + hklOffset)).padStart(5, '0'); }).join('');
}
function hklKeySplit(key) {
    var len = Object(number["c" /* integerDigitCount */])(hklOffset, 0);
    var h = parseInt(key.substr(0, len));
    var k = parseInt(key.substr(len, len));
    var l = parseInt(key.substr(len + len, len));
    return [h - hklOffset, k - hklOffset, l - hklOffset];
}
function formatHkl(hkl) {
    return hkl.map(function (v) { return v + 5; }).join('');
}
function getOperatorHklSerialMap(structure) {
    var map = new Map();
    var set = new Set();
    for (var i = 0, il = structure.units.length; i < il; ++i) {
        var k = hklKey(structure.units[i].conformation.operator.hkl);
        set.add(k);
    }
    var arr = Array.from(set.values()).sort();
    arr.forEach(function (k) { return map.set(k, map.size); });
    var min = hklKeySplit(arr[0]);
    var max = hklKeySplit(arr[arr.length - 1]);
    return { min: min, max: max, map: map };
}
function OperatorHklColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var _a = getOperatorHklSerialMap(ctx.structure.root), min = _a.min, max = _a.max, map_1 = _a.map;
        var labelTable_1 = [];
        map_1.forEach(function (v, k) {
            var i = v % map_1.size;
            var label = formatHkl(hklKeySplit(k));
            if (labelTable_1[i] === undefined)
                labelTable_1[i] = label;
            else
                labelTable_1[i] += ", " + label;
        });
        props.palette.params.minLabel = formatHkl(min);
        props.palette.params.maxLabel = formatHkl(max);
        props.palette.params.valueLabel = function (i) { return labelTable_1[i]; };
        var palette_1 = Object(color_palette["a" /* getPalette */])(map_1.size, props);
        legend = palette_1.legend;
        color = function (location) {
            var serial = undefined;
            if (mol_model_structure["StructureElement"].Location.is(location)) {
                var k = hklKey(location.unit.conformation.operator.hkl);
                serial = map_1.get(k);
            }
            else if (mol_model_structure["Bond"].isLocation(location)) {
                var k = hklKey(location.aUnit.conformation.operator.hkl);
                serial = map_1.get(k);
            }
            return serial === undefined ? operator_hkl_DefaultColor : palette_1.color(serial);
        };
    }
    else {
        color = function () { return operator_hkl_DefaultColor; };
    }
    return {
        factory: OperatorHklColorTheme,
        granularity: 'instance',
        color: color,
        props: props,
        description: operator_hkl_Description,
        legend: legend
    };
}
var OperatorHklColorThemeProvider = {
    name: 'operator-hkl',
    label: 'Operator HKL',
    category: "Symmetry" /* Symmetry */,
    factory: OperatorHklColorTheme,
    getParams: getOperatorHklColorThemeParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(OperatorHklColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=operator-hkl.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-theme/color.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

























var color_ColorTheme;
(function (ColorTheme) {
    ColorTheme.EmptyFactory = function () { return ColorTheme.Empty; };
    var EmptyColor = Object(mol_util_color["Color"])(0xCCCCCC);
    ColorTheme.Empty = {
        factory: ColorTheme.EmptyFactory,
        granularity: 'uniform',
        color: function () { return EmptyColor; },
        props: {}
    };
    function areEqual(themeA, themeB) {
        return themeA.contextHash === themeB.contextHash && themeA.factory === themeB.factory && Object(mol_util["h" /* deepEqual */])(themeA.props, themeB.props);
    }
    ColorTheme.areEqual = areEqual;
    ColorTheme.EmptyProvider = { name: '', label: '', category: '', factory: ColorTheme.EmptyFactory, getParams: function () { return ({}); }, defaultValues: {}, isApplicable: function () { return true; } };
    function createRegistry() {
        return new theme["b" /* ThemeRegistry */](ColorTheme.BuiltIn, ColorTheme.EmptyProvider);
    }
    ColorTheme.createRegistry = createRegistry;
    ColorTheme.BuiltIn = {
        'carbohydrate-symbol': CarbohydrateSymbolColorThemeProvider,
        'chain-id': chain_id["b" /* ChainIdColorThemeProvider */],
        'element-index': ElementIndexColorThemeProvider,
        'element-symbol': element_symbol["ElementSymbolColorThemeProvider"],
        'entity-source': EntitySourceColorThemeProvider,
        'hydrophobicity': HydrophobicityColorThemeProvider,
        'illustrative': IllustrativeColorThemeProvider,
        'model-index': ModelIndexColorThemeProvider,
        'molecule-type': MoleculeTypeColorThemeProvider,
        'occupancy': OccupancyColorThemeProvider,
        'operator-hkl': OperatorHklColorThemeProvider,
        'operator-name': OperatorNameColorThemeProvider,
        'polymer-id': PolymerIdColorThemeProvider,
        'polymer-index': PolymerIndexColorThemeProvider,
        'residue-name': ResidueNameColorThemeProvider,
        'secondary-structure': SecondaryStructureColorThemeProvider,
        'sequence-id': SequenceIdColorThemeProvider,
        'shape-group': shape_group["b" /* ShapeGroupColorThemeProvider */],
        'uncertainty': UncertaintyColorThemeProvider,
        'unit-index': UnitIndexColorThemeProvider,
        'uniform': uniform["b" /* UniformColorThemeProvider */],
    };
})(color_ColorTheme || (color_ColorTheme = {}));
function ColorThemeProvider(p) { return p; }
//# sourceMappingURL=color.js.map

/***/ }),
/* 197 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getSymbolIterator */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return iterator; });
/* unused harmony export $$iterator */
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function getSymbolIterator() {
    if (typeof Symbol !== 'function' || !Symbol.iterator) {
        return '@@iterator';
    }
    return Symbol.iterator;
}
var iterator = /*@__PURE__*/ getSymbolIterator();
var $$iterator = iterator;
//# sourceMappingURL=iterator.js.map


/***/ }),
/* 198 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StructureRepresentation3D", function() { return /* binding */ StructureRepresentation3D; });
__webpack_require__.d(__webpack_exports__, "ExplodeStructureRepresentation3D", function() { return /* binding */ ExplodeStructureRepresentation3D; });
__webpack_require__.d(__webpack_exports__, "UnwindStructureAssemblyRepresentation3D", function() { return /* binding */ UnwindStructureAssemblyRepresentation3D; });
__webpack_require__.d(__webpack_exports__, "OverpaintStructureRepresentation3DFromScript", function() { return /* binding */ OverpaintStructureRepresentation3DFromScript; });
__webpack_require__.d(__webpack_exports__, "OverpaintStructureRepresentation3DFromBundle", function() { return /* binding */ OverpaintStructureRepresentation3DFromBundle; });
__webpack_require__.d(__webpack_exports__, "TransparencyStructureRepresentation3DFromScript", function() { return /* binding */ TransparencyStructureRepresentation3DFromScript; });
__webpack_require__.d(__webpack_exports__, "TransparencyStructureRepresentation3DFromBundle", function() { return /* binding */ TransparencyStructureRepresentation3DFromBundle; });
__webpack_require__.d(__webpack_exports__, "ClippingStructureRepresentation3DFromScript", function() { return /* binding */ ClippingStructureRepresentation3DFromScript; });
__webpack_require__.d(__webpack_exports__, "ClippingStructureRepresentation3DFromBundle", function() { return /* binding */ ClippingStructureRepresentation3DFromBundle; });
__webpack_require__.d(__webpack_exports__, "VolumeRepresentation3D", function() { return /* binding */ VolumeRepresentation3D; });
__webpack_require__.d(__webpack_exports__, "VolumeRepresentation3DHelpers", function() { return /* binding */ representation_VolumeRepresentation3DHelpers; });
__webpack_require__.d(__webpack_exports__, "ShapeRepresentation3D", function() { return /* binding */ ShapeRepresentation3D; });
__webpack_require__.d(__webpack_exports__, "ModelUnitcell3D", function() { return /* binding */ ModelUnitcell3D; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionsDistance3D", function() { return /* binding */ StructureSelectionsDistance3D; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionsAngle3D", function() { return /* binding */ StructureSelectionsAngle3D; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionsDihedral3D", function() { return /* binding */ StructureSelectionsDihedral3D; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionsLabel3D", function() { return /* binding */ StructureSelectionsLabel3D; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionsOrientation3D", function() { return /* binding */ StructureSelectionsOrientation3D; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/volume.js
var mol_model_volume = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/theme.js
var theme = __webpack_require__(89);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/names.js
var names = __webpack_require__(47);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/geometry.js
var geometry = __webpack_require__(145);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var representation = __webpack_require__(40);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/shape.js + 1 modules
var mol_model_shape = __webpack_require__(49);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/render-object.js + 8 modules
var render_object = __webpack_require__(115);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/util.js
var util = __webpack_require__(164);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/marker-data.js
var marker_data = __webpack_require__(125);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/marker-action.js
var marker_action = __webpack_require__(45);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/color-data.js
var color_data = __webpack_require__(117);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/size-data.js
var size_data = __webpack_require__(146);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/visual.js
var visual = __webpack_require__(69);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/representation.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















function ShapeRepresentation(getShape, geometryUtils, builder) {
    if (builder === void 0) { builder = {}; }
    var version = 0;
    var updated = new Subject["a" /* Subject */]();
    var _state = representation["a" /* Representation */].createState();
    var materialId = Object(render_object["c" /* getNextMaterialId */])();
    var renderObjects = [];
    var _renderObject;
    var _shape;
    var _theme = theme["a" /* Theme */].createEmpty();
    var currentProps = param_definition["ParamDefinition"].getDefaultValues(geometryUtils.Params); // TODO avoid casting
    var currentParams;
    var locationIt;
    if (builder.modifyState)
        representation["a" /* Representation */].updateState(_state, builder.modifyState(_state));
    var updateState = util["a" /* VisualUpdateState */].create();
    function prepareUpdate(props, shape) {
        if (props === void 0) { props = {}; }
        util["a" /* VisualUpdateState */].reset(updateState);
        if (!shape && !_shape) {
            // console.error('no shape given')
            return;
        }
        else if (shape && !_shape) {
            // console.log('first shape')
            updateState.createNew = true;
        }
        else if (shape && _shape && shape.id === _shape.id) {
            // console.log('same shape')
            // nothing to set
        }
        else if (shape && _shape && shape.id !== _shape.id) {
            // console.log('new shape')
            updateState.updateTransform = true;
            updateState.createGeometry = true;
        }
        else if (!shape) {
            // console.log('only props')
            // nothing to set
        }
        else {
            console.warn('unexpected state');
        }
        if (updateState.updateTransform) {
            updateState.updateColor = true;
            updateState.updateSize = true;
        }
        if (updateState.createGeometry) {
            updateState.updateColor = true;
            updateState.updateSize = true;
        }
    }
    function createOrUpdate(props, data) {
        var _this = this;
        if (props === void 0) { props = {}; }
        if (builder.modifyProps)
            props = builder.modifyProps(props);
        return mol_task["b" /* Task */].create('ShapeRepresentation.create', function (runtime) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var newProps, shape, _a, transform, values, state, instanceCount, groupCount;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        newProps = Object.assign(currentProps, props);
                        if (!data) return [3 /*break*/, 2];
                        return [4 /*yield*/, getShape(runtime, data, newProps, _shape)];
                    case 1:
                        _a = _b.sent();
                        return [3 /*break*/, 3];
                    case 2:
                        _a = undefined;
                        _b.label = 3;
                    case 3:
                        shape = _a;
                        prepareUpdate(props, shape);
                        if (shape) {
                            _shape = shape;
                            Object.assign(_theme, mol_model_shape["a" /* Shape */].getTheme(_shape));
                        }
                        if (updateState.createNew) {
                            renderObjects.length = 0; // clear list o renderObjects
                            locationIt = mol_model_shape["a" /* Shape */].groupIterator(_shape);
                            transform = mol_model_shape["a" /* Shape */].createTransform(_shape.transforms);
                            values = geometryUtils.createValues(_shape.geometry, transform, locationIt, _theme, newProps);
                            state = geometryUtils.createRenderableState(newProps);
                            if (builder.modifyState)
                                Object.assign(state, builder.modifyState(state));
                            representation["a" /* Representation */].updateState(_state, state);
                            _renderObject = Object(render_object["a" /* createRenderObject */])(_shape.geometry.kind, values, state, materialId);
                            if (_renderObject)
                                renderObjects.push(_renderObject); // add new renderObject to list
                        }
                        else {
                            if (!_renderObject) {
                                throw new Error('expected renderObject to be available');
                            }
                            if (updateState.updateTransform) {
                                // console.log('update transform')
                                mol_model_shape["a" /* Shape */].createTransform(_shape.transforms, _renderObject.values);
                                locationIt = mol_model_shape["a" /* Shape */].groupIterator(_shape);
                                instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
                                Object(marker_data["a" /* createMarkers */])(instanceCount * groupCount, _renderObject.values);
                            }
                            if (updateState.createGeometry) {
                                // console.log('update geometry')
                                mol_util["e" /* ValueCell */].update(_renderObject.values.drawCount, geometry["a" /* Geometry */].getDrawCount(_shape.geometry));
                            }
                            if (updateState.updateTransform || updateState.createGeometry) {
                                // console.log('updateBoundingSphere')
                                geometryUtils.updateBoundingSphere(_renderObject.values, _shape.geometry);
                            }
                            if (updateState.updateColor) {
                                // console.log('update color')
                                Object(color_data["a" /* createColors */])(locationIt, _theme.color, _renderObject.values);
                            }
                            if (updateState.updateSize) {
                                // not all geometries have size data, so check here
                                if ('uSize' in _renderObject.values) {
                                    // console.log('update size')
                                    Object(size_data["a" /* createSizes */])(locationIt, _theme.size, _renderObject.values);
                                }
                            }
                            geometryUtils.updateValues(_renderObject.values, newProps);
                            geometryUtils.updateRenderableState(_renderObject.state, newProps);
                        }
                        currentProps = newProps;
                        // increment version
                        updated.next(version++);
                        return [2 /*return*/];
                }
            });
        }); });
    }
    function lociApply(loci, apply) {
        if (Object(mol_model_loci["isEveryLoci"])(loci) || (mol_model_shape["a" /* Shape */].isLoci(loci) && loci.shape === _shape)) {
            return apply(mol_data_int["Interval"].ofBounds(0, _shape.groupCount * _shape.transforms.length));
        }
        else {
            return eachShapeGroup(loci, _shape, apply);
        }
    }
    return {
        label: 'Shape geometry',
        get groupCount() { return locationIt ? locationIt.count : 0; },
        get props() { return currentProps; },
        get params() { return currentParams; },
        get state() { return _state; },
        get theme() { return _theme; },
        renderObjects: renderObjects,
        updated: updated,
        createOrUpdate: createOrUpdate,
        getLoci: function (pickingId) {
            if (pickingId === undefined)
                return mol_model_shape["a" /* Shape */].Loci(_shape);
            var objectId = pickingId.objectId, groupId = pickingId.groupId, instanceId = pickingId.instanceId;
            if (_renderObject && _renderObject.id === objectId) {
                return mol_model_shape["b" /* ShapeGroup */].Loci(_shape, [{ ids: mol_data_int["OrderedSet"].ofSingleton(groupId), instance: instanceId }]);
            }
            return mol_model_loci["EmptyLoci"];
        },
        mark: function (loci, action) {
            if (!marker_action["b" /* MarkerActions */].is(_state.markerActions, action))
                return false;
            if (mol_model_shape["b" /* ShapeGroup */].isLoci(loci) || mol_model_shape["a" /* Shape */].isLoci(loci)) {
                if (loci.shape !== _shape)
                    return false;
            }
            else if (!Object(mol_model_loci["isEveryLoci"])(loci)) {
                return false;
            }
            return visual["a" /* Visual */].mark(_renderObject, loci, action, lociApply);
        },
        setState: function (state) {
            if (builder.modifyState)
                state = builder.modifyState(state);
            if (_renderObject) {
                if (state.visible !== undefined)
                    visual["a" /* Visual */].setVisibility(_renderObject, state.visible);
                if (state.alphaFactor !== undefined)
                    visual["a" /* Visual */].setAlphaFactor(_renderObject, state.alphaFactor);
                if (state.pickable !== undefined)
                    visual["a" /* Visual */].setPickable(_renderObject, state.pickable);
                if (state.overpaint !== undefined) {
                    visual["a" /* Visual */].setOverpaint(_renderObject, state.overpaint, lociApply, true);
                }
                if (state.transparency !== undefined) {
                    visual["a" /* Visual */].setTransparency(_renderObject, state.transparency, lociApply, true);
                }
                if (state.transform !== undefined)
                    visual["a" /* Visual */].setTransform(_renderObject, state.transform);
            }
            representation["a" /* Representation */].updateState(_state, state);
        },
        setTheme: function (theme) {
            console.warn('The `ShapeRepresentation` theme is fixed to `ShapeGroupColorTheme` and `ShapeGroupSizeTheme`. Colors are taken from `Shape.getColor` and sizes from `Shape.getSize`');
        },
        destroy: function () {
            // TODO
            renderObjects.length = 0;
            _renderObject = undefined;
        }
    };
}
function eachShapeGroup(loci, shape, apply) {
    if (!mol_model_shape["b" /* ShapeGroup */].isLoci(loci))
        return false;
    if (loci.shape !== shape)
        return false;
    var changed = false;
    var groupCount = shape.groupCount;
    var groups = loci.groups;
    for (var _a = 0, groups_1 = groups; _a < groups_1.length; _a++) {
        var _b = groups_1[_a], ids = _b.ids, instance = _b.instance;
        if (mol_data_int["Interval"].is(ids)) {
            var start = instance * groupCount + mol_data_int["Interval"].start(ids);
            var end = instance * groupCount + mol_data_int["Interval"].end(ids);
            if (apply(mol_data_int["Interval"].ofBounds(start, end)))
                changed = true;
        }
        else {
            for (var i = 0, _i = ids.length; i < _i; i++) {
                var idx = instance * groupCount + ids[i];
                if (apply(mol_data_int["Interval"].ofSingleton(idx)))
                    changed = true;
            }
        }
    }
    return changed;
}
//# sourceMappingURL=representation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/transform-data.js
var transform_data = __webpack_require__(182);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/unit-transforms.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var tmpMat = Object(linear_algebra["Mat4"])();
var unit_transforms_StructureUnitTransforms = /** @class */ (function () {
    function StructureUnitTransforms(structure) {
        this.structure = structure;
        this.groupUnitTransforms = [];
        /** maps unit.id to offset of transform in unitTransforms */
        this.unitOffsetMap = mol_data_int["IntMap"].Mutable();
        this.groupIndexMap = mol_data_int["IntMap"].Mutable();
        this._isIdentity = undefined;
        this.version = 0;
        this.unitTransforms = new Float32Array(structure.units.length * 16);
        this.size = structure.units.length;
        this.reset(); // to set to identity
        var groupOffset = 0;
        for (var i = 0, il = structure.unitSymmetryGroups.length; i < il; ++i) {
            var g = structure.unitSymmetryGroups[i];
            this.groupIndexMap.set(g.hashCode, i);
            var groupTransforms = this.unitTransforms.subarray(groupOffset, groupOffset + g.units.length * 16);
            this.groupUnitTransforms.push(groupTransforms);
            for (var j = 0, jl = g.units.length; j < jl; ++j) {
                this.unitOffsetMap.set(g.units[j].id, groupOffset + j * 16);
            }
            groupOffset += g.units.length * 16;
        }
    }
    StructureUnitTransforms.prototype.reset = function () {
        this.version = 0;
        Object(transform_data["c" /* fillIdentityTransform */])(this.unitTransforms, this.size);
        this._isIdentity = true;
    };
    Object.defineProperty(StructureUnitTransforms.prototype, "isIdentity", {
        get: function () {
            if (this._isIdentity === undefined) {
                this._isIdentity = true;
                for (var i = 0, il = this.size * 16; i < il; i += 16) {
                    linear_algebra["Mat4"].fromArray(tmpMat, this.unitTransforms, i);
                    if (!linear_algebra["Mat4"].isIdentity(tmpMat)) {
                        this._isIdentity = false;
                        break;
                    }
                }
            }
            return this._isIdentity;
        },
        enumerable: false,
        configurable: true
    });
    StructureUnitTransforms.prototype.setTransform = function (matrix, unit) {
        this.version = (this.version + 1) % 0x7fffffff;
        linear_algebra["Mat4"].toArray(matrix, this.unitTransforms, this.unitOffsetMap.get(unit.id));
        this._isIdentity = undefined;
    };
    StructureUnitTransforms.prototype.getTransform = function (out, unit) {
        return linear_algebra["Mat4"].fromArray(out, this.unitTransforms, this.unitOffsetMap.get(unit.id));
    };
    StructureUnitTransforms.prototype.getSymmetryGroupTransforms = function (group) {
        return this.groupUnitTransforms[this.groupIndexMap.get(group.hashCode)];
    };
    return StructureUnitTransforms;
}());

//# sourceMappingURL=unit-transforms.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var mol_math_geometry = __webpack_require__(11);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/animation/helpers.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var _unwindMatrix = linear_algebra["Mat4"].zero();
function unwindStructureAssembly(structure, unitTransforms, t) {
    for (var i = 0, _i = structure.units.length; i < _i; i++) {
        var u = structure.units[i];
        mol_math_geometry["h" /* SymmetryOperator */].lerpFromIdentity(_unwindMatrix, u.conformation.operator, t);
        unitTransforms.setTransform(_unwindMatrix, u);
    }
}
var _centerVec = linear_algebra["Vec3"].zero(), _transVec = linear_algebra["Vec3"].zero(), _transMat = linear_algebra["Mat4"].zero();
function explodeStructure(structure, unitTransforms, t) {
    var boundary = structure.boundary.sphere;
    var d = boundary.radius * t;
    for (var i = 0, _i = structure.units.length; i < _i; i++) {
        var u = structure.units[i];
        linear_algebra["Vec3"].transformMat4(_centerVec, u.lookup3d.boundary.sphere.center, u.conformation.operator.matrix);
        linear_algebra["Vec3"].sub(_transVec, _centerVec, boundary.center);
        linear_algebra["Vec3"].setMagnitude(_transVec, _transVec, d);
        linear_algebra["Mat4"].fromTranslation(_transMat, _transVec);
        unitTransforms.setTransform(_transMat, u);
    }
}
//# sourceMappingURL=helpers.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/overpaint.js
var mol_theme_overpaint = __webpack_require__(130);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/transparency.js
var mol_theme_transparency = __webpack_require__(131);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/base.js
var base = __webpack_require__(33);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/script.js + 4 modules
var script = __webpack_require__(120);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh-builder.js
var mesh_builder = __webpack_require__(34);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/box.js
var primitive_box = __webpack_require__(242);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/cage.js
var primitive_cage = __webpack_require__(184);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/model/unitcell.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var translate05 = linear_algebra["Mat4"].fromTranslation(Object(linear_algebra["Mat4"])(), linear_algebra["Vec3"].create(0.5, 0.5, 0.5));
var unitCage = Object(primitive_cage["c" /* transformCage */])(Object(primitive_cage["a" /* cloneCage */])(Object(primitive_box["b" /* BoxCage */])()), translate05);
var tmpRef = Object(linear_algebra["Vec3"])();
var tmpTranslate = Object(linear_algebra["Mat4"])();
var CellParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), { cellColor: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].orange), cellScale: param_definition["ParamDefinition"].Numeric(2, { min: 0.1, max: 5, step: 0.1 }) });
var UnitcellVisuals = {
    'mesh': function (ctx, getParams) { return ShapeRepresentation(getUnitcellShape, mesh_mesh["a" /* Mesh */].Utils); },
};
var UnitcellParams = Object(tslib_es6["__assign"])({}, CellParams);
function getUnitcellMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(256, 128, mesh);
    var fromFractional = data.symmetry.spacegroup.cell.fromFractional;
    linear_algebra["Vec3"].floor(tmpRef, data.ref);
    linear_algebra["Mat4"].fromTranslation(tmpTranslate, tmpRef);
    var cellCage = Object(primitive_cage["c" /* transformCage */])(Object(primitive_cage["a" /* cloneCage */])(unitCage), tmpTranslate);
    var radius = (Math.cbrt(data.symmetry.spacegroup.cell.volume) / 300) * props.cellScale;
    state.currentGroup = 1;
    mesh_builder["a" /* MeshBuilder */].addCage(state, fromFractional, cellCage, radius, 2, 20);
    var cpA = linear_algebra["Vec3"].create(0, 0, 0);
    linear_algebra["Vec3"].transformMat4(cpA, linear_algebra["Vec3"].add(cpA, cpA, tmpRef), fromFractional);
    var cpB = linear_algebra["Vec3"].create(1, 1, 1);
    linear_algebra["Vec3"].transformMat4(cpB, linear_algebra["Vec3"].add(cpB, cpB, tmpRef), fromFractional);
    var cpC = linear_algebra["Vec3"].create(1, 0, 0);
    linear_algebra["Vec3"].transformMat4(cpC, linear_algebra["Vec3"].add(cpC, cpC, tmpRef), fromFractional);
    var cpD = linear_algebra["Vec3"].create(0, 1, 1);
    linear_algebra["Vec3"].transformMat4(cpD, linear_algebra["Vec3"].add(cpD, cpD, tmpRef), fromFractional);
    var cpE = linear_algebra["Vec3"].create(0, 0, 1);
    linear_algebra["Vec3"].transformMat4(cpE, linear_algebra["Vec3"].add(cpE, cpE, tmpRef), fromFractional);
    var cpF = linear_algebra["Vec3"].create(1, 0, 1);
    linear_algebra["Vec3"].transformMat4(cpF, linear_algebra["Vec3"].add(cpF, cpF, tmpRef), fromFractional);
    var cpG = linear_algebra["Vec3"].create(1, 1, 0);
    linear_algebra["Vec3"].transformMat4(cpG, linear_algebra["Vec3"].add(cpG, cpG, tmpRef), fromFractional);
    var cpH = linear_algebra["Vec3"].create(0, 1, 0);
    linear_algebra["Vec3"].transformMat4(cpH, linear_algebra["Vec3"].add(cpH, cpH, tmpRef), fromFractional);
    var center = Object(linear_algebra["Vec3"])();
    linear_algebra["Vec3"].add(center, cpA, cpB);
    linear_algebra["Vec3"].scale(center, center, 0.5);
    var d = Math.max(linear_algebra["Vec3"].distance(cpA, cpB), linear_algebra["Vec3"].distance(cpC, cpD));
    var sphere = mol_math_geometry["g" /* Sphere3D */].create(center, d / 2);
    mol_math_geometry["g" /* Sphere3D */].setExtrema(sphere, [cpA, cpB, cpC, cpD, cpE, cpF, cpG, cpH]);
    mol_math_geometry["g" /* Sphere3D */].expand(sphere, sphere, radius);
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(state);
    m.setBoundingSphere(sphere);
    return m;
}
function getUnitcellShape(ctx, data, props, shape) {
    var geo = getUnitcellMesh(data, props, shape && shape.geometry);
    var label = mol_model_structure["Symmetry"].getUnitcellLabel(data.symmetry);
    return mol_model_shape["a" /* Shape */].create(label, data, geo, function () { return props.cellColor; }, function () { return 1; }, function () { return label; });
}
//
function getUnitcellData(model, symmetry) {
    return {
        symmetry: symmetry,
        ref: linear_algebra["Vec3"].transformMat4(Object(linear_algebra["Vec3"])(), mol_model_structure["Model"].getCenter(model), symmetry.spacegroup.cell.toFractional)
    };
}
function UnitcellRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Unit Cell', ctx, getParams, representation["a" /* Representation */].StateBuilder, UnitcellVisuals);
}
//# sourceMappingURL=unitcell.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/lines/lines.js
var lines_lines = __webpack_require__(74);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/text/text.js
var text_text = __webpack_require__(123);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/lines/lines-builder.js
var lines_builder = __webpack_require__(172);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/text/text-builder.js
var text_builder = __webpack_require__(209);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/common.js
var common = __webpack_require__(221);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/distance.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var SharedParams = {
    unitLabel: param_definition["ParamDefinition"].Text('\u212B', { isEssential: true })
};
var LineParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, lines_lines["a" /* Lines */].Params), SharedParams), { lineSizeAttenuation: param_definition["ParamDefinition"].Boolean(true), linesColor: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].lightgreen, { isEssential: true }), linesSize: param_definition["ParamDefinition"].Numeric(0.075, { min: 0.01, max: 5, step: 0.01 }), dashLength: param_definition["ParamDefinition"].Numeric(0.2, { min: 0.01, max: 0.2, step: 0.01 }) });
var TextParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, text_text["a" /* Text */].Params), SharedParams), { borderWidth: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 0.5, step: 0.01 }) }), common["a" /* MeasurementRepresentationCommonTextParams */]);
var DistanceVisuals = {
    'lines': function (ctx, getParams) { return ShapeRepresentation(getLinesShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["b" /* MarkerActions */].Highlighting })); } }); },
    'text': function (ctx, getParams) { return ShapeRepresentation(getTextShape, text_text["a" /* Text */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["a" /* MarkerAction */].None })); } }); },
};
var DistanceParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, LineParams), TextParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['lines', 'text'], param_definition["ParamDefinition"].objectToOptions(DistanceVisuals)) });
//
function getDistanceState() {
    return {
        sphereA: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereB: Object(mol_math_geometry["g" /* Sphere3D */])(),
        center: Object(linear_algebra["Vec3"])(),
        distance: 0,
    };
}
function setDistanceState(pair, state) {
    var sphereA = state.sphereA, sphereB = state.sphereB, center = state.center;
    var _a = pair.loci, lociA = _a[0], lociB = _a[1];
    mol_model_loci["Loci"].getBoundingSphere(lociA, sphereA);
    mol_model_loci["Loci"].getBoundingSphere(lociB, sphereB);
    linear_algebra["Vec3"].add(center, sphereA.center, sphereB.center);
    linear_algebra["Vec3"].scale(center, center, 0.5);
    state.distance = linear_algebra["Vec3"].distance(sphereA.center, sphereB.center);
    return state;
}
var tmpState = getDistanceState();
function getDistanceName(data, unitLabel) {
    return data.pairs.length === 1 ? "Distance " + Object(mol_theme_label["distanceLabel"])(data.pairs[0], { unitLabel: unitLabel, measureOnly: true }) : data.pairs.length + " Distances";
}
//
function buildLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.pairs.length; i < il; ++i) {
        setDistanceState(data.pairs[i], tmpState);
        builder.addFixedLengthDashes(tmpState.sphereA.center, tmpState.sphereB.center, props.dashLength, i);
    }
    return builder.getLines();
}
function getLinesShape(ctx, data, props, shape) {
    var lines = buildLines(data, props, shape && shape.geometry);
    var name = getDistanceName(data, props.unitLabel);
    var getLabel = function (groupId) { return Object(mol_theme_label["distanceLabel"])(data.pairs[groupId], props); };
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.linesColor; }, function () { return props.linesSize; }, getLabel);
}
//
function buildText(data, props, text) {
    var builder = text_builder["a" /* TextBuilder */].create(props, 128, 64, text);
    for (var i = 0, il = data.pairs.length; i < il; ++i) {
        setDistanceState(data.pairs[i], tmpState);
        var center = tmpState.center, distance = tmpState.distance, sphereA = tmpState.sphereA, sphereB = tmpState.sphereB;
        var label = props.customText || distance.toFixed(2) + " " + props.unitLabel;
        var radius = Math.max(2, sphereA.radius, sphereB.radius);
        var scale = radius / 2;
        builder.add(label, center[0], center[1], center[2], 1, scale, i);
    }
    return builder.getText();
}
function getTextShape(ctx, data, props, shape) {
    var text = buildText(data, props, shape && shape.geometry);
    var name = getDistanceName(data, props.unitLabel);
    var getLabel = function (groupId) { return Object(mol_theme_label["distanceLabel"])(data.pairs[groupId], props); };
    return mol_model_shape["a" /* Shape */].create(name, data, text, function () { return props.textColor; }, function () { return props.textSize; }, getLabel);
}
function DistanceRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Distance', ctx, getParams, representation["a" /* Representation */].StateBuilder, DistanceVisuals);
}
//# sourceMappingURL=distance.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/helpers.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function getDistanceDataFromStructureSelections(s) {
    var lociA = s[0].loci;
    var lociB = s[1].loci;
    return { pairs: [{ loci: [lociA, lociB] }] };
}
function getAngleDataFromStructureSelections(s) {
    var lociA = s[0].loci;
    var lociB = s[1].loci;
    var lociC = s[2].loci;
    return { triples: [{ loci: [lociA, lociB, lociC] }] };
}
function getDihedralDataFromStructureSelections(s) {
    var lociA = s[0].loci;
    var lociB = s[1].loci;
    var lociC = s[2].loci;
    var lociD = s[3].loci;
    return { quads: [{ loci: [lociA, lociB, lociC, lociD] }] };
}
function getLabelDataFromStructureSelections(s) {
    var loci = s[0].loci;
    return { infos: [{ loci: loci }] };
}
function getOrientationDataFromStructureSelections(s) {
    var loci = s[0].loci;
    return { locis: [loci] };
}
//# sourceMappingURL=helpers.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/label.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var label_TextParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, text_text["a" /* Text */].Params), { borderWidth: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 0.5, step: 0.01 }) }), common["a" /* MeasurementRepresentationCommonTextParams */]), { offsetZ: param_definition["ParamDefinition"].Numeric(2, { min: 0, max: 10, step: 0.1 }) });
var LabelVisuals = {
    'text': function (ctx, getParams) { return ShapeRepresentation(label_getTextShape, text_text["a" /* Text */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
};
var LabelParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, label_TextParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['text'], param_definition["ParamDefinition"].objectToOptions(LabelVisuals)) });
//
var tmpSphere = Object(mol_math_geometry["g" /* Sphere3D */])();
function label_label(info, condensed) {
    if (condensed === void 0) { condensed = false; }
    return info.label || Object(mol_theme_label["lociLabel"])(info.loci, { hidePrefix: true, htmlStyling: false, condensed: condensed });
}
function getLabelName(data) {
    return data.infos.length === 1 ? label_label(data.infos[0]) : data.infos.length + " Labels";
}
//
function label_buildText(data, props, text) {
    var builder = text_builder["a" /* TextBuilder */].create(props, 128, 64, text);
    for (var i = 0, il = data.infos.length; i < il; ++i) {
        var info = data.infos[i];
        var sphere = mol_model_loci["Loci"].getBoundingSphere(info.loci, tmpSphere);
        if (!sphere)
            continue;
        var center = sphere.center, radius = sphere.radius;
        var text_1 = label_label(info, true);
        builder.add(text_1, center[0], center[1], center[2], radius / 0.9, Math.max(1, radius), i);
    }
    return builder.getText();
}
function label_getTextShape(ctx, data, props, shape) {
    var text = label_buildText(data, props, shape && shape.geometry);
    var name = getLabelName(data);
    var getLabel = function (groupId) {
        return label_label(data.infos[groupId]);
    };
    return mol_model_shape["a" /* Shape */].create(name, data, text, function () { return props.textColor; }, function () { return props.textSize; }, getLabel);
}
function LabelRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Label', ctx, getParams, representation["a" /* Representation */].StateBuilder, LabelVisuals);
}
//# sourceMappingURL=label.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/axes.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var tmpVec = Object(linear_algebra["Vec3"])();
var tmpMatrix = linear_algebra["Mat4"].identity();
var tmpVertices = new Float32Array(6 * 3);
var tmpEdges = new Uint8Array([0, 1, 2, 3, 4, 5]);
function addAxes(state, axes, radiusScale, detail, radialSegments) {
    var origin = axes.origin, dirA = axes.dirA, dirB = axes.dirB, dirC = axes.dirC;
    linear_algebra["Vec3"].add(tmpVec, origin, dirA);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].add(tmpVec, origin, dirA), tmpVertices, 0);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].sub(tmpVec, origin, dirA), tmpVertices, 3);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].add(tmpVec, origin, dirB), tmpVertices, 6);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].sub(tmpVec, origin, dirB), tmpVertices, 9);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].add(tmpVec, origin, dirC), tmpVertices, 12);
    linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].sub(tmpVec, origin, dirC), tmpVertices, 15);
    var cage = Object(primitive_cage["b" /* createCage */])(tmpVertices, tmpEdges);
    var volume = mol_math_geometry["a" /* Axes3D */].volume(axes);
    var radius = (Math.cbrt(volume) / 300) * radiusScale;
    mesh_builder["a" /* MeshBuilder */].addCage(state, tmpMatrix, cage, radius, detail, radialSegments);
}
//# sourceMappingURL=axes.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/cylinder.js + 1 modules
var cylinder = __webpack_require__(81);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/sphere.js
var builder_sphere = __webpack_require__(75);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/box.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var tmpStart = linear_algebra["Vec3"].zero();
var tmpEnd = linear_algebra["Vec3"].zero();
var cylinderProps = {};
function addBoundingBox(state, box, radius, detail, radialSegments) {
    var min = box.min, max = box.max;
    cylinderProps.radiusTop = radius;
    cylinderProps.radiusBottom = radius;
    cylinderProps.radialSegments = radialSegments;
    linear_algebra["Vec3"].set(tmpStart, max[0], max[1], max[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpStart, radius, detail);
    linear_algebra["Vec3"].set(tmpEnd, max[0], max[1], min[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, max[0], min[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, min[0], max[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpStart, min[0], min[1], min[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpStart, radius, detail);
    linear_algebra["Vec3"].set(tmpEnd, min[0], min[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, min[0], max[1], min[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, max[0], min[1], min[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpStart, max[0], min[1], min[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpStart, radius, detail);
    linear_algebra["Vec3"].set(tmpEnd, max[0], min[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, max[0], max[1], min[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpStart, min[0], min[1], max[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpStart, radius, detail);
    linear_algebra["Vec3"].set(tmpEnd, min[0], max[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, max[0], min[1], max[2]);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpStart, min[0], max[1], min[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpStart, radius, detail);
    linear_algebra["Vec3"].set(tmpEnd, max[0], max[1], min[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpEnd, radius, detail);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
    linear_algebra["Vec3"].set(tmpEnd, min[0], max[1], max[2]);
    Object(builder_sphere["a" /* addSphere */])(state, tmpEnd, radius, detail);
    Object(cylinder["a" /* addCylinder */])(state, tmpStart, tmpEnd, 1, cylinderProps);
}
//
var tmpBoxVecCorner = Object(linear_algebra["Vec3"])();
var tmpBoxVecA = Object(linear_algebra["Vec3"])();
var tmpBoxVecB = Object(linear_algebra["Vec3"])();
var tmpBoxVecC = Object(linear_algebra["Vec3"])();
var box_tmpMatrix = linear_algebra["Mat4"].identity();
var box_tmpVertices = new Float32Array(8 * 3);
var box_tmpEdges = new Uint8Array([
    0, 1, 0, 3, 0, 6, 1, 2, 1, 7, 2, 3,
    2, 4, 3, 5, 4, 5, 4, 7, 5, 6, 6, 7
]);
function addOrientedBox(state, axes, radiusScale, detail, radialSegments) {
    var origin = axes.origin, dirA = axes.dirA, dirB = axes.dirB, dirC = axes.dirC;
    var negDirA = linear_algebra["Vec3"].negate(tmpBoxVecA, dirA);
    var negDirB = linear_algebra["Vec3"].negate(tmpBoxVecB, dirB);
    var negDirC = linear_algebra["Vec3"].negate(tmpBoxVecC, dirC);
    var offset = 0;
    var addCornerHelper = function (v1, v2, v3) {
        linear_algebra["Vec3"].copy(tmpBoxVecCorner, origin);
        linear_algebra["Vec3"].add(tmpBoxVecCorner, tmpBoxVecCorner, v1);
        linear_algebra["Vec3"].add(tmpBoxVecCorner, tmpBoxVecCorner, v2);
        linear_algebra["Vec3"].add(tmpBoxVecCorner, tmpBoxVecCorner, v3);
        linear_algebra["Vec3"].toArray(tmpBoxVecCorner, box_tmpVertices, offset);
        offset += 3;
    };
    addCornerHelper(dirA, dirB, dirC);
    addCornerHelper(dirA, dirB, negDirC);
    addCornerHelper(dirA, negDirB, negDirC);
    addCornerHelper(dirA, negDirB, dirC);
    addCornerHelper(negDirA, negDirB, negDirC);
    addCornerHelper(negDirA, negDirB, dirC);
    addCornerHelper(negDirA, dirB, dirC);
    addCornerHelper(negDirA, dirB, negDirC);
    var cage = Object(primitive_cage["b" /* createCage */])(box_tmpVertices, box_tmpEdges);
    var volume = mol_math_geometry["a" /* Axes3D */].volume(axes);
    var radius = (Math.cbrt(volume) / 300) * radiusScale;
    mesh_builder["a" /* MeshBuilder */].addCage(state, box_tmpMatrix, cage, radius, detail, radialSegments);
}
//# sourceMappingURL=box.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/ellipsoid.js
var ellipsoid = __webpack_require__(309);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/orientation.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var orientation_SharedParams = {
    color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].orange),
    scale: param_definition["ParamDefinition"].Numeric(2, { min: 0.1, max: 10, step: 0.1 })
};
var AxesParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), orientation_SharedParams);
var BoxParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), orientation_SharedParams);
var EllipsoidParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), orientation_SharedParams);
var OrientationVisuals = {
    'axes': function (ctx, getParams) { return ShapeRepresentation(getAxesShape, mesh_mesh["a" /* Mesh */].Utils); },
    'box': function (ctx, getParams) { return ShapeRepresentation(getBoxShape, mesh_mesh["a" /* Mesh */].Utils); },
    'ellipsoid': function (ctx, getParams) { return ShapeRepresentation(getEllipsoidShape, mesh_mesh["a" /* Mesh */].Utils); },
};
var OrientationParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, AxesParams), BoxParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['box'], param_definition["ParamDefinition"].objectToOptions(OrientationVisuals)), color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].orange), scale: param_definition["ParamDefinition"].Numeric(2, { min: 0.1, max: 5, step: 0.1 }) });
//
function orientationLabel(loci) {
    var label = Object(mol_theme_label["lociLabel"])(loci, { countsOnly: true });
    return "Principal Axes of " + label;
}
function getOrientationName(data) {
    return data.locis.length === 1 ? orientationLabel(data.locis[0]) : data.locis.length + " Orientations";
}
//
function buildAxesMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(256, 128, mesh);
    for (var i = 0, il = data.locis.length; i < il; ++i) {
        var principalAxes = mol_model_loci["Loci"].getPrincipalAxes(data.locis[i]);
        if (principalAxes) {
            state.currentGroup = i;
            addAxes(state, principalAxes.momentsAxes, props.scale, 2, 20);
        }
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(state);
}
function getAxesShape(ctx, data, props, shape) {
    var mesh = buildAxesMesh(data, props, shape && shape.geometry);
    var name = getOrientationName(data);
    var getLabel = function (groupId) {
        return orientationLabel(data.locis[groupId]);
    };
    return mol_model_shape["a" /* Shape */].create(name, data, mesh, function () { return props.color; }, function () { return 1; }, getLabel);
}
//
function buildBoxMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(256, 128, mesh);
    for (var i = 0, il = data.locis.length; i < il; ++i) {
        var principalAxes = mol_model_loci["Loci"].getPrincipalAxes(data.locis[i]);
        if (principalAxes) {
            state.currentGroup = i;
            addOrientedBox(state, principalAxes.boxAxes, props.scale, 2, 20);
        }
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(state);
}
function getBoxShape(ctx, data, props, shape) {
    var mesh = buildBoxMesh(data, props, shape && shape.geometry);
    var name = getOrientationName(data);
    var getLabel = function (groupId) {
        return orientationLabel(data.locis[groupId]);
    };
    return mol_model_shape["a" /* Shape */].create(name, data, mesh, function () { return props.color; }, function () { return 1; }, getLabel);
}
//
function buildEllipsoidMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(256, 128, mesh);
    for (var i = 0, il = data.locis.length; i < il; ++i) {
        var principalAxes = mol_model_loci["Loci"].getPrincipalAxes(data.locis[i]);
        if (principalAxes) {
            var axes = principalAxes.boxAxes;
            var origin_1 = axes.origin, dirA = axes.dirA, dirB = axes.dirB;
            var size = mol_math_geometry["a" /* Axes3D */].size(Object(linear_algebra["Vec3"])(), axes);
            linear_algebra["Vec3"].scale(size, size, 0.5);
            var radiusScale = linear_algebra["Vec3"].create(size[2], size[1], size[0]);
            state.currentGroup = i;
            Object(ellipsoid["a" /* addEllipsoid */])(state, origin_1, dirA, dirB, radiusScale, 2);
        }
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(state);
}
function getEllipsoidShape(ctx, data, props, shape) {
    var mesh = buildEllipsoidMesh(data, props, shape && shape.geometry);
    var name = getOrientationName(data);
    var getLabel = function (groupId) {
        return orientationLabel(data.locis[groupId]);
    };
    return mol_model_shape["a" /* Shape */].create(name, data, mesh, function () { return props.color; }, function () { return 1; }, getLabel);
}
function OrientationRepresentation(ctx, getParams) {
    var repr = representation["a" /* Representation */].createMulti('Orientation', ctx, getParams, representation["a" /* Representation */].StateBuilder, OrientationVisuals);
    repr.setState({ markerActions: marker_action["b" /* MarkerActions */].Highlighting });
    return repr;
}
//# sourceMappingURL=orientation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/misc.js
var misc = __webpack_require__(46);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/circle.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var DefaultCircleProps = {
    radius: 1,
    segments: 36,
    thetaStart: 0,
    thetaLength: Math.PI * 2
};
function Circle(props) {
    var _a = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultCircleProps), props), radius = _a.radius, segments = _a.segments, thetaStart = _a.thetaStart, thetaLength = _a.thetaLength;
    var isFull = thetaLength === Math.PI * 2;
    var count = isFull ? segments + 1 : segments + 2;
    var vertices = new Float32Array(count * 3);
    var normals = new Float32Array(count * 3);
    var indices = new Uint32Array(segments * 3);
    // center
    vertices[0] = 0;
    vertices[1] = 0;
    vertices[2] = 0;
    normals[0] = 0;
    normals[1] = 1;
    normals[2] = 0;
    // vertices & normals
    for (var s = 0, i = 3; s < segments; ++s, i += 3) {
        var segment = thetaStart + s / segments * thetaLength;
        vertices[i] = radius * Math.sin(segment);
        vertices[i + 1] = 0;
        vertices[i + 2] = radius * Math.cos(segment);
        normals[i] = 0;
        normals[i + 1] = 1;
        normals[i + 2] = 0;
    }
    // indices
    for (var s = 1, i = 0; s < segments; ++s, i += 3) {
        indices[i] = s;
        indices[i + 1] = s + 1;
        indices[i + 2] = 0;
    }
    if (isFull) {
        var j = (segments - 1) * 3;
        indices[j] = segments;
        indices[j + 1] = 1;
        indices[j + 2] = 0;
    }
    else {
        var segment = thetaStart + thetaLength;
        var i = (segments + 1) * 3;
        vertices[i] = radius * Math.sin(segment);
        vertices[i + 1] = 0;
        vertices[i + 2] = radius * Math.cos(segment);
        normals[i] = 0;
        normals[i + 1] = 1;
        normals[i + 2] = 0;
        var j = (segments - 1) * 3;
        indices[j] = segments;
        indices[j + 1] = segments + 1;
        indices[j + 2] = 0;
    }
    return { vertices: vertices, normals: normals, indices: indices };
}
//# sourceMappingURL=circle.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/primitive.js
var primitive = __webpack_require__(127);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/angle.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





















var angle_SharedParams = {
    color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].lightgreen),
    arcScale: param_definition["ParamDefinition"].Numeric(0.7, { min: 0.01, max: 1, step: 0.01 })
};
var LinesParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, lines_lines["a" /* Lines */].Params), angle_SharedParams), { lineSizeAttenuation: param_definition["ParamDefinition"].Boolean(true), linesSize: param_definition["ParamDefinition"].Numeric(0.04, { min: 0.01, max: 5, step: 0.01 }), dashLength: param_definition["ParamDefinition"].Numeric(0.04, { min: 0.01, max: 0.2, step: 0.01 }) });
var VectorsParams = Object(tslib_es6["__assign"])({}, LinesParams);
var ArcParams = Object(tslib_es6["__assign"])({}, LinesParams);
var SectorParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), angle_SharedParams), { ignoreLight: param_definition["ParamDefinition"].Boolean(true), sectorOpacity: param_definition["ParamDefinition"].Numeric(0.75, { min: 0, max: 1, step: 0.01 }) });
var angle_TextParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, text_text["a" /* Text */].Params), common["a" /* MeasurementRepresentationCommonTextParams */]), { borderWidth: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 0.5, step: 0.01 }) });
var AngleVisuals = {
    'vectors': function (ctx, getParams) { return ShapeRepresentation(getVectorsShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'arc': function (ctx, getParams) { return ShapeRepresentation(getArcShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'sector': function (ctx, getParams) { return ShapeRepresentation(getSectorShape, mesh_mesh["a" /* Mesh */].Utils, { modifyProps: function (p) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, p), { alpha: p.sectorOpacity })); }, modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["b" /* MarkerActions */].Highlighting })); } }); },
    'text': function (ctx, getParams) { return ShapeRepresentation(angle_getTextShape, text_text["a" /* Text */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["a" /* MarkerAction */].None })); } }); },
};
var AngleParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, VectorsParams), ArcParams), SectorParams), angle_TextParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['vectors', 'sector', 'text'], param_definition["ParamDefinition"].objectToOptions(AngleVisuals)) });
//
function getAngleState() {
    return {
        sphereA: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereB: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereC: Object(mol_math_geometry["g" /* Sphere3D */])(),
        arcDirA: Object(linear_algebra["Vec3"])(),
        arcDirC: Object(linear_algebra["Vec3"])(),
        arcNormal: Object(linear_algebra["Vec3"])(),
        radius: 0,
        angle: 0,
    };
}
var angle_tmpVec = Object(linear_algebra["Vec3"])();
var angle_tmpMat = Object(linear_algebra["Mat4"])();
function setAngleState(triple, state, arcScale) {
    var sphereA = state.sphereA, sphereB = state.sphereB, sphereC = state.sphereC;
    var arcDirA = state.arcDirA, arcDirC = state.arcDirC, arcNormal = state.arcNormal;
    var _a = triple.loci, lociA = _a[0], lociB = _a[1], lociC = _a[2];
    mol_model_loci["Loci"].getBoundingSphere(lociA, sphereA);
    mol_model_loci["Loci"].getBoundingSphere(lociB, sphereB);
    mol_model_loci["Loci"].getBoundingSphere(lociC, sphereC);
    linear_algebra["Vec3"].sub(arcDirA, sphereA.center, sphereB.center);
    linear_algebra["Vec3"].sub(arcDirC, sphereC.center, sphereB.center);
    linear_algebra["Vec3"].cross(arcNormal, arcDirA, arcDirC);
    var len = Math.min(linear_algebra["Vec3"].magnitude(arcDirA), linear_algebra["Vec3"].magnitude(arcDirC));
    var radius = len * arcScale;
    state.radius = radius;
    state.angle = linear_algebra["Vec3"].angle(arcDirA, arcDirC);
    return state;
}
function getCircle(state, segmentLength) {
    var radius = state.radius, angle = state.angle;
    var segments = segmentLength ? Object(misc["b" /* arcLength */])(angle, radius) / segmentLength : 32;
    linear_algebra["Mat4"].targetTo(angle_tmpMat, state.sphereB.center, state.sphereA.center, state.arcNormal);
    linear_algebra["Mat4"].setTranslation(angle_tmpMat, state.sphereB.center);
    linear_algebra["Mat4"].mul(angle_tmpMat, angle_tmpMat, linear_algebra["Mat4"].rotY180);
    var circle = Circle({ radius: radius, thetaLength: angle, segments: segments });
    return Object(primitive["c" /* transformPrimitive */])(circle, angle_tmpMat);
}
var angle_tmpState = getAngleState();
function getAngleName(data) {
    return data.triples.length === 1 ? "Angle " + Object(mol_theme_label["angleLabel"])(data.triples[0], { measureOnly: true }) : data.triples.length + " Angles";
}
//
function buildVectorsLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.triples.length; i < il; ++i) {
        setAngleState(data.triples[i], angle_tmpState, props.arcScale);
        builder.addFixedLengthDashes(angle_tmpState.sphereB.center, angle_tmpState.sphereA.center, props.dashLength, i);
        builder.addFixedLengthDashes(angle_tmpState.sphereB.center, angle_tmpState.sphereC.center, props.dashLength, i);
    }
    return builder.getLines();
}
function getVectorsShape(ctx, data, props, shape) {
    var lines = buildVectorsLines(data, props, shape && shape.geometry);
    var name = getAngleName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function buildArcLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.triples.length; i < il; ++i) {
        setAngleState(data.triples[i], angle_tmpState, props.arcScale);
        var circle = getCircle(angle_tmpState, props.dashLength);
        var indices = circle.indices, vertices = circle.vertices;
        for (var j = 0, jl = indices.length; j < jl; j += 3) {
            if (j % 2 === 1)
                continue; // draw every other segment to get dashes
            var start = indices[j] * 3;
            var end = indices[j + 1] * 3;
            var startX = vertices[start];
            var startY = vertices[start + 1];
            var startZ = vertices[start + 2];
            var endX = vertices[end];
            var endY = vertices[end + 1];
            var endZ = vertices[end + 2];
            builder.add(startX, startY, startZ, endX, endY, endZ, i);
        }
    }
    return builder.getLines();
}
function getArcShape(ctx, data, props, shape) {
    var lines = buildArcLines(data, props, shape && shape.geometry);
    var name = getAngleName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function buildSectorMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(128, 64, mesh);
    for (var i = 0, il = data.triples.length; i < il; ++i) {
        setAngleState(data.triples[i], angle_tmpState, props.arcScale);
        var circle = getCircle(angle_tmpState);
        state.currentGroup = i;
        mesh_builder["a" /* MeshBuilder */].addPrimitive(state, linear_algebra["Mat4"].id, circle);
        mesh_builder["a" /* MeshBuilder */].addPrimitiveFlipped(state, linear_algebra["Mat4"].id, circle);
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(state);
}
function getSectorShape(ctx, data, props, shape) {
    var mesh = buildSectorMesh(data, props, shape && shape.geometry);
    var name = getAngleName(data);
    var getLabel = function (groupId) { return Object(mol_theme_label["angleLabel"])(data.triples[groupId]); };
    return mol_model_shape["a" /* Shape */].create(name, data, mesh, function () { return props.color; }, function () { return 1; }, getLabel);
}
//
function angle_buildText(data, props, text) {
    var builder = text_builder["a" /* TextBuilder */].create(props, 128, 64, text);
    for (var i = 0, il = data.triples.length; i < il; ++i) {
        setAngleState(data.triples[i], angle_tmpState, props.arcScale);
        linear_algebra["Vec3"].add(angle_tmpVec, angle_tmpState.arcDirA, angle_tmpState.arcDirC);
        linear_algebra["Vec3"].setMagnitude(angle_tmpVec, angle_tmpVec, angle_tmpState.radius);
        linear_algebra["Vec3"].add(angle_tmpVec, angle_tmpState.sphereB.center, angle_tmpVec);
        var angle = Object(misc["f" /* radToDeg */])(angle_tmpState.angle).toFixed(2);
        var label = props.customText || angle + "\u00B0";
        var radius = Math.max(2, angle_tmpState.sphereA.radius, angle_tmpState.sphereB.radius, angle_tmpState.sphereC.radius);
        var scale = radius / 2;
        builder.add(label, angle_tmpVec[0], angle_tmpVec[1], angle_tmpVec[2], 0.1, scale, i);
    }
    return builder.getText();
}
function angle_getTextShape(ctx, data, props, shape) {
    var text = angle_buildText(data, props, shape && shape.geometry);
    var name = getAngleName(data);
    var getLabel = function (groupId) { return Object(mol_theme_label["angleLabel"])(data.triples[groupId]); };
    return mol_model_shape["a" /* Shape */].create(name, data, text, function () { return props.textColor; }, function () { return props.textSize; }, getLabel);
}
function AngleRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Angle', ctx, getParams, representation["a" /* Representation */].StateBuilder, AngleVisuals);
}
//# sourceMappingURL=angle.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/shape/loci/dihedral.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





















var dihedral_SharedParams = {
    color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].lightgreen),
    arcScale: param_definition["ParamDefinition"].Numeric(0.7, { min: 0.01, max: 1, step: 0.01 })
};
var dihedral_LinesParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, lines_lines["a" /* Lines */].Params), dihedral_SharedParams), { lineSizeAttenuation: param_definition["ParamDefinition"].Boolean(true), linesSize: param_definition["ParamDefinition"].Numeric(0.04, { min: 0.01, max: 5, step: 0.01 }), dashLength: param_definition["ParamDefinition"].Numeric(0.04, { min: 0.01, max: 0.2, step: 0.01 }) });
var dihedral_VectorsParams = Object(tslib_es6["__assign"])({}, dihedral_LinesParams);
var ExtendersParams = Object(tslib_es6["__assign"])({}, dihedral_LinesParams);
var dihedral_ArcParams = Object(tslib_es6["__assign"])({}, dihedral_LinesParams);
var dihedral_SectorParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), dihedral_SharedParams), { ignoreLight: param_definition["ParamDefinition"].Boolean(true), sectorOpacity: param_definition["ParamDefinition"].Numeric(0.75, { min: 0, max: 1, step: 0.01 }) });
var dihedral_TextParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, text_text["a" /* Text */].Params), { borderWidth: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 0.5, step: 0.01 }) }), common["a" /* MeasurementRepresentationCommonTextParams */]);
var DihedralVisuals = {
    'vectors': function (ctx, getParams) { return ShapeRepresentation(dihedral_getVectorsShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'extenders': function (ctx, getParams) { return ShapeRepresentation(getExtendersShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'connector': function (ctx, getParams) { return ShapeRepresentation(getConnectorShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'arc': function (ctx, getParams) { return ShapeRepresentation(dihedral_getArcShape, lines_lines["a" /* Lines */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { pickable: false })); } }); },
    'sector': function (ctx, getParams) { return ShapeRepresentation(dihedral_getSectorShape, mesh_mesh["a" /* Mesh */].Utils, { modifyProps: function (p) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, p), { alpha: p.sectorOpacity })); }, modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["b" /* MarkerActions */].Highlighting })); } }); },
    'text': function (ctx, getParams) { return ShapeRepresentation(dihedral_getTextShape, text_text["a" /* Text */].Utils, { modifyState: function (s) { return (Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, s), { markerActions: marker_action["a" /* MarkerAction */].None })); } }); },
};
var DihedralParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, dihedral_VectorsParams), ExtendersParams), dihedral_ArcParams), dihedral_SectorParams), dihedral_TextParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['extenders', 'sector', 'text'], param_definition["ParamDefinition"].objectToOptions(DihedralVisuals)) });
//
function getDihedralState() {
    return {
        sphereA: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereB: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereC: Object(mol_math_geometry["g" /* Sphere3D */])(),
        sphereD: Object(mol_math_geometry["g" /* Sphere3D */])(),
        dirBA: Object(linear_algebra["Vec3"])(),
        dirCD: Object(linear_algebra["Vec3"])(),
        projA: Object(linear_algebra["Vec3"])(),
        projD: Object(linear_algebra["Vec3"])(),
        arcPointA: Object(linear_algebra["Vec3"])(),
        arcPointD: Object(linear_algebra["Vec3"])(),
        arcDirA: Object(linear_algebra["Vec3"])(),
        arcDirD: Object(linear_algebra["Vec3"])(),
        arcCenter: Object(linear_algebra["Vec3"])(),
        arcNormal: Object(linear_algebra["Vec3"])(),
        radius: 0,
        angle: 0,
    };
}
var dihedral_tmpVec = Object(linear_algebra["Vec3"])();
var dihedral_tmpMat = Object(linear_algebra["Mat4"])();
// TODO improper dihedrals are not handled correctly
function setDihedralState(quad, state, arcScale) {
    var sphereA = state.sphereA, sphereB = state.sphereB, sphereC = state.sphereC, sphereD = state.sphereD, dirBA = state.dirBA, dirCD = state.dirCD, projA = state.projA, projD = state.projD;
    var arcPointA = state.arcPointA, arcPointD = state.arcPointD, arcDirA = state.arcDirA, arcDirD = state.arcDirD, arcCenter = state.arcCenter, arcNormal = state.arcNormal;
    var _a = quad.loci, lociA = _a[0], lociB = _a[1], lociC = _a[2], lociD = _a[3];
    mol_model_loci["Loci"].getBoundingSphere(lociA, sphereA);
    mol_model_loci["Loci"].getBoundingSphere(lociB, sphereB);
    mol_model_loci["Loci"].getBoundingSphere(lociC, sphereC);
    mol_model_loci["Loci"].getBoundingSphere(lociD, sphereD);
    linear_algebra["Vec3"].add(arcCenter, sphereB.center, sphereC.center);
    linear_algebra["Vec3"].scale(arcCenter, arcCenter, 0.5);
    linear_algebra["Vec3"].sub(dirBA, sphereA.center, sphereB.center);
    linear_algebra["Vec3"].sub(dirCD, sphereD.center, sphereC.center);
    linear_algebra["Vec3"].add(arcPointA, arcCenter, dirBA);
    linear_algebra["Vec3"].add(arcPointD, arcCenter, dirCD);
    linear_algebra["Vec3"].sub(arcNormal, sphereC.center, sphereB.center);
    linear_algebra["Vec3"].orthogonalize(arcDirA, arcNormal, dirBA);
    linear_algebra["Vec3"].orthogonalize(arcDirD, arcNormal, dirCD);
    linear_algebra["Vec3"].projectPointOnVector(projA, arcPointA, arcDirA, arcCenter);
    linear_algebra["Vec3"].projectPointOnVector(projD, arcPointD, arcDirD, arcCenter);
    var len = Math.min(linear_algebra["Vec3"].distance(projA, arcCenter), linear_algebra["Vec3"].distance(projD, arcCenter));
    var radius = len * arcScale;
    linear_algebra["Vec3"].setMagnitude(arcDirA, arcDirA, radius);
    linear_algebra["Vec3"].setMagnitude(arcDirD, arcDirD, radius);
    linear_algebra["Vec3"].add(arcPointA, arcCenter, arcDirA);
    linear_algebra["Vec3"].add(arcPointD, arcCenter, arcDirD);
    state.radius = radius;
    state.angle = linear_algebra["Vec3"].dihedralAngle(sphereA.center, sphereB.center, sphereC.center, sphereD.center);
    linear_algebra["Vec3"].matchDirection(dihedral_tmpVec, arcNormal, linear_algebra["Vec3"].sub(dihedral_tmpVec, arcPointA, sphereA.center));
    var angleA = linear_algebra["Vec3"].angle(dirBA, dihedral_tmpVec);
    var lenA = radius / Math.cos(angleA > misc["d" /* halfPI */] ? angleA - misc["d" /* halfPI */] : angleA);
    linear_algebra["Vec3"].add(projA, sphereB.center, linear_algebra["Vec3"].setMagnitude(dihedral_tmpVec, dirBA, lenA));
    linear_algebra["Vec3"].matchDirection(dihedral_tmpVec, arcNormal, linear_algebra["Vec3"].sub(dihedral_tmpVec, arcPointD, sphereD.center));
    var angleD = linear_algebra["Vec3"].angle(dirCD, dihedral_tmpVec);
    var lenD = radius / Math.cos(angleD > misc["d" /* halfPI */] ? angleD - misc["d" /* halfPI */] : angleD);
    linear_algebra["Vec3"].add(projD, sphereC.center, linear_algebra["Vec3"].setMagnitude(dihedral_tmpVec, dirCD, lenD));
    return state;
}
function dihedral_getCircle(state, segmentLength) {
    var radius = state.radius, angle = state.angle;
    var segments = segmentLength ? Object(misc["b" /* arcLength */])(angle, radius) / segmentLength : 32;
    linear_algebra["Mat4"].targetTo(dihedral_tmpMat, state.arcCenter, angle < 0 ? state.arcPointD : state.arcPointA, state.arcNormal);
    linear_algebra["Mat4"].setTranslation(dihedral_tmpMat, state.arcCenter);
    linear_algebra["Mat4"].mul(dihedral_tmpMat, dihedral_tmpMat, linear_algebra["Mat4"].rotY180);
    var circle = Circle({ radius: radius, thetaLength: Math.abs(angle), segments: segments });
    return Object(primitive["c" /* transformPrimitive */])(circle, dihedral_tmpMat);
}
var dihedral_tmpState = getDihedralState();
function getDihedralName(data) {
    return data.quads.length === 1 ? "Dihedral " + Object(mol_theme_label["dihedralLabel"])(data.quads[0], { measureOnly: true }) : data.quads.length + " Dihedrals";
}
//
function dihedral_buildVectorsLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        builder.addFixedLengthDashes(dihedral_tmpState.arcCenter, dihedral_tmpState.arcPointA, props.dashLength, i);
        builder.addFixedLengthDashes(dihedral_tmpState.arcCenter, dihedral_tmpState.arcPointD, props.dashLength, i);
    }
    return builder.getLines();
}
function dihedral_getVectorsShape(ctx, data, props, shape) {
    var lines = dihedral_buildVectorsLines(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function buildConnectorLine(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        builder.addFixedLengthDashes(dihedral_tmpState.sphereB.center, dihedral_tmpState.sphereC.center, props.dashLength, i);
    }
    return builder.getLines();
}
function getConnectorShape(ctx, data, props, shape) {
    var lines = buildConnectorLine(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function buildExtendersLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        builder.addFixedLengthDashes(dihedral_tmpState.arcPointA, dihedral_tmpState.projA, props.dashLength, i);
        builder.addFixedLengthDashes(dihedral_tmpState.arcPointD, dihedral_tmpState.projD, props.dashLength, i);
    }
    return builder.getLines();
}
function getExtendersShape(ctx, data, props, shape) {
    var lines = buildExtendersLines(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function dihedral_buildArcLines(data, props, lines) {
    var builder = lines_builder["a" /* LinesBuilder */].create(128, 64, lines);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        var circle = dihedral_getCircle(dihedral_tmpState, props.dashLength);
        var indices = circle.indices, vertices = circle.vertices;
        for (var j = 0, jl = indices.length; j < jl; j += 3) {
            if (j % 2 === 1)
                continue; // draw every other segment to get dashes
            var start = indices[j] * 3;
            var end = indices[j + 1] * 3;
            var startX = vertices[start];
            var startY = vertices[start + 1];
            var startZ = vertices[start + 2];
            var endX = vertices[end];
            var endY = vertices[end + 1];
            var endZ = vertices[end + 2];
            builder.add(startX, startY, startZ, endX, endY, endZ, i);
        }
    }
    return builder.getLines();
}
function dihedral_getArcShape(ctx, data, props, shape) {
    var lines = dihedral_buildArcLines(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    return mol_model_shape["a" /* Shape */].create(name, data, lines, function () { return props.color; }, function () { return props.linesSize; }, function () { return ''; });
}
//
function dihedral_buildSectorMesh(data, props, mesh) {
    var state = mesh_builder["a" /* MeshBuilder */].createState(128, 64, mesh);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        var circle = dihedral_getCircle(dihedral_tmpState);
        state.currentGroup = i;
        mesh_builder["a" /* MeshBuilder */].addPrimitive(state, linear_algebra["Mat4"].id, circle);
        mesh_builder["a" /* MeshBuilder */].addPrimitiveFlipped(state, linear_algebra["Mat4"].id, circle);
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(state);
}
function dihedral_getSectorShape(ctx, data, props, shape) {
    var mesh = dihedral_buildSectorMesh(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    var getLabel = function (groupId) { return Object(mol_theme_label["dihedralLabel"])(data.quads[groupId]); };
    return mol_model_shape["a" /* Shape */].create(name, data, mesh, function () { return props.color; }, function () { return 1; }, getLabel);
}
//
function dihedral_buildText(data, props, text) {
    var builder = text_builder["a" /* TextBuilder */].create(props, 128, 64, text);
    for (var i = 0, il = data.quads.length; i < il; ++i) {
        setDihedralState(data.quads[i], dihedral_tmpState, props.arcScale);
        linear_algebra["Vec3"].add(dihedral_tmpVec, dihedral_tmpState.arcDirA, dihedral_tmpState.arcDirD);
        linear_algebra["Vec3"].setMagnitude(dihedral_tmpVec, dihedral_tmpVec, dihedral_tmpState.radius);
        linear_algebra["Vec3"].add(dihedral_tmpVec, dihedral_tmpState.arcCenter, dihedral_tmpVec);
        var angle = Math.abs(Object(misc["f" /* radToDeg */])(dihedral_tmpState.angle)).toFixed(2);
        var label = props.customText || angle + "\u00B0";
        var radius = Math.max(2, dihedral_tmpState.sphereA.radius, dihedral_tmpState.sphereB.radius, dihedral_tmpState.sphereC.radius, dihedral_tmpState.sphereD.radius);
        var scale = radius / 2;
        builder.add(label, dihedral_tmpVec[0], dihedral_tmpVec[1], dihedral_tmpVec[2], 0.1, scale, i);
    }
    return builder.getText();
}
function dihedral_getTextShape(ctx, data, props, shape) {
    var text = dihedral_buildText(data, props, shape && shape.geometry);
    var name = getDihedralName(data);
    var getLabel = function (groupId) { return Object(mol_theme_label["dihedralLabel"])(data.quads[groupId]); };
    return mol_model_shape["a" /* Shape */].create(name, data, text, function () { return props.textColor; }, function () { return props.textSize; }, getLabel);
}
function DihedralRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Dihedral', ctx, getParams, representation["a" /* Representation */].StateBuilder, DihedralVisuals);
}
//# sourceMappingURL=dihedral.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js + 1 modules
var property_symmetry = __webpack_require__(113);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/clipping.js
var mol_theme_clipping = __webpack_require__(77);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/type-helpers.js
var type_helpers = __webpack_require__(283);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/representation.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





































var StructureRepresentation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-representation-3d',
    display: '3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    params: function (a, ctx) {
        var _a = ctx.representation.structure, registry = _a.registry, themeCtx = _a.themes;
        var type = registry.get(registry.default.name);
        if (!a) {
            var colorThemeInfo_1 = {
                help: function (value) {
                    var name = value.name, params = value.params;
                    var p = themeCtx.colorThemeRegistry.get(name);
                    var ct = p.factory({}, params);
                    return { description: ct.description, legend: ct.legend };
                }
            };
            return {
                type: param_definition["ParamDefinition"].Mapped(registry.default.name, registry.types, function (name) { return param_definition["ParamDefinition"].Group(registry.get(name).getParams(themeCtx, mol_model_structure["Structure"].Empty)); }),
                colorTheme: param_definition["ParamDefinition"].Mapped(type.defaultColorTheme.name, themeCtx.colorThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.colorThemeRegistry.get(name).getParams({ structure: mol_model_structure["Structure"].Empty })); }, colorThemeInfo_1),
                sizeTheme: param_definition["ParamDefinition"].Mapped(type.defaultSizeTheme.name, themeCtx.sizeThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.sizeThemeRegistry.get(name).getParams({ structure: mol_model_structure["Structure"].Empty })); })
            };
        }
        var dataCtx = { structure: a.data };
        var colorThemeInfo = {
            help: function (value) {
                var name = value.name, params = value.params;
                var p = themeCtx.colorThemeRegistry.get(name);
                var ct = p.factory(dataCtx, params);
                return { description: ct.description, legend: ct.legend };
            }
        };
        return ({
            type: param_definition["ParamDefinition"].Mapped(registry.default.name, registry.getApplicableTypes(a.data), function (name) { return param_definition["ParamDefinition"].Group(registry.get(name).getParams(themeCtx, a.data)); }),
            colorTheme: param_definition["ParamDefinition"].Mapped(type.defaultColorTheme.name, themeCtx.colorThemeRegistry.getApplicableTypes(dataCtx), function (name) { return param_definition["ParamDefinition"].Group(themeCtx.colorThemeRegistry.get(name).getParams(dataCtx)); }, colorThemeInfo),
            sizeTheme: param_definition["ParamDefinition"].Mapped(type.defaultSizeTheme.name, themeCtx.sizeThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.sizeThemeRegistry.get(name).getParams(dataCtx)); })
        });
    }
})({
    canAutoUpdate: function (_a) {
        var a = _a.a, oldParams = _a.oldParams, newParams = _a.newParams;
        // TODO: other criteria as well?
        return a.data.elementCount < 10000 || (oldParams.type.name === newParams.type.name && newParams.type.params.quality !== 'custom');
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params, cache = _a.cache;
        return mol_task["b" /* Task */].create('Structure Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var propertyCtx, provider, props, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        propertyCtx = { runtime: ctx, assetManager: plugin.managers.asset };
                        provider = plugin.representation.structure.registry.get(params.type.name);
                        if (!provider.ensureCustomProperties) return [3 /*break*/, 2];
                        return [4 /*yield*/, provider.ensureCustomProperties.attach(propertyCtx, a.data)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        props = params.type.params || {};
                        repr = provider.factory(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), provider.getParams);
                        return [4 /*yield*/, theme["a" /* Theme */].ensureDependencies(propertyCtx, plugin.representation.structure.themes, { structure: a.data }, params)];
                    case 3:
                        _b.sent();
                        repr.setTheme(theme["a" /* Theme */].create(plugin.representation.structure.themes, { structure: a.data }, params));
                        // // TODO: build this into representation?
                        // if (!a.data.coordinateSystem.isIdentity) {
                        //     (cache as any)['transform'] = a.data.coordinateSystem;
                        //     repr.setState({ transform: a.data.coordinateSystem.matrix });
                        // }
                        // TODO set initial state, repr.setState({})
                        return [4 /*yield*/, repr.createOrUpdate(props, a.data).runInContext(ctx)];
                    case 4:
                        // // TODO: build this into representation?
                        // if (!a.data.coordinateSystem.isIdentity) {
                        //     (cache as any)['transform'] = a.data.coordinateSystem;
                        //     repr.setState({ transform: a.data.coordinateSystem.matrix });
                        // }
                        // TODO set initial state, repr.setState({})
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D({ repr: repr, source: a }, { label: provider.label })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache;
        return mol_task["b" /* Task */].create('Structure Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var oldProvider, provider, propertyCtx, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (newParams.type.name !== oldParams.type.name)
                            return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Recreate];
                        oldProvider = plugin.representation.structure.registry.get(oldParams.type.name);
                        if (oldProvider.ensureCustomProperties)
                            oldProvider.ensureCustomProperties.detach(a.data);
                        theme["a" /* Theme */].releaseDependencies(plugin.representation.structure.themes, { structure: a.data }, oldParams);
                        provider = plugin.representation.structure.registry.get(newParams.type.name);
                        propertyCtx = { runtime: ctx, assetManager: plugin.managers.asset };
                        if (!provider.ensureCustomProperties) return [3 /*break*/, 2];
                        return [4 /*yield*/, provider.ensureCustomProperties.attach(propertyCtx, a.data)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams.type.params);
                        return [4 /*yield*/, theme["a" /* Theme */].ensureDependencies(propertyCtx, plugin.representation.structure.themes, { structure: a.data }, newParams)];
                    case 3:
                        _a.sent();
                        b.data.repr.setTheme(theme["a" /* Theme */].create(plugin.representation.structure.themes, { structure: a.data }, newParams));
                        // // TODO: build this into representation?
                        // if ((cache as any)['transform'] !== a.data.coordinateSystem) {
                        //     (cache as any)['transform'] = a.data.coordinateSystem;
                        //     b.data.repr.setState({ transform: a.data.coordinateSystem.matrix });
                        // }
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, a.data).runInContext(ctx)];
                    case 4:
                        // // TODO: build this into representation?
                        // if ((cache as any)['transform'] !== a.data.coordinateSystem) {
                        //     (cache as any)['transform'] = a.data.coordinateSystem;
                        //     b.data.repr.setState({ transform: a.data.coordinateSystem.matrix });
                        // }
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
    dispose: function (_a, plugin) {
        var b = _a.b, params = _a.params;
        if (!b || !params)
            return;
        var structure = b.data.source.data;
        var provider = plugin.representation.structure.registry.get(params.type.name);
        if (provider.ensureCustomProperties)
            provider.ensureCustomProperties.detach(structure);
        theme["a" /* Theme */].releaseDependencies(plugin.representation.structure.themes, { structure: structure }, params);
    },
    interpolate: function (src, tar, t) {
        if (src.colorTheme.name !== 'uniform' || tar.colorTheme.name !== 'uniform') {
            return t <= 0.5 ? src : tar;
        }
        var from = src.colorTheme.params.value, to = tar.colorTheme.params.value;
        var value = color["Color"].interpolate(from, to, t);
        return {
            type: t <= 0.5 ? src.type : tar.type,
            colorTheme: { name: 'uniform', params: { value: value } },
            sizeTheme: t <= 0.5 ? src.sizeTheme : tar.sizeTheme,
        };
    }
});
var UnwindStructureAssemblyRepresentation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'unwind-structure-assembly-representation-3d',
    display: 'Unwind Assembly 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: { t: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 1, step: 0.01 }) }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var unitTransforms = new unit_transforms_StructureUnitTransforms(structure);
        unwindStructureAssembly(structure, unitTransforms, params.t);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { unitTransforms: unitTransforms },
            initialState: { unitTransforms: new unit_transforms_StructureUnitTransforms(structure) },
            info: structure,
            source: a
        }, { label: "Unwind T = " + params.t.toFixed(2) });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = b.data.info;
        if (a.data.source.data !== structure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.t === newParams.t)
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        var unitTransforms = b.data.state.unitTransforms;
        unwindStructureAssembly(structure, unitTransforms, newParams.t);
        b.label = "Unwind T = " + newParams.t.toFixed(2);
        b.data.source = a;
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var ExplodeStructureRepresentation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'explode-structure-representation-3d',
    display: 'Explode 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: { t: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 1, step: 0.01 }) }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var unitTransforms = new unit_transforms_StructureUnitTransforms(structure.root);
        explodeStructure(structure, unitTransforms, params.t);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { unitTransforms: unitTransforms },
            initialState: { unitTransforms: new unit_transforms_StructureUnitTransforms(structure.root) },
            info: structure.root,
            source: a
        }, { label: "Explode T = " + params.t.toFixed(2) });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = a.data.source.data;
        if (b.data.info !== structure.root)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.t === newParams.t)
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        var unitTransforms = b.data.state.unitTransforms;
        explodeStructure(structure.root, unitTransforms, newParams.t);
        b.label = "Explode T = " + newParams.t.toFixed(2);
        b.data.source = a;
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var OverpaintStructureRepresentation3DFromScript = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'overpaint-structure-representation-3d-from-script',
    display: 'Overpaint 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            script: param_definition["ParamDefinition"].Script(Object(script["Script"])('(sel.atom.all)', 'mol-script')),
            color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].blueviolet),
            clear: param_definition["ParamDefinition"].Boolean(false)
        }, function (e) { return "" + (e.clear ? 'Clear' : color["Color"].toRgbString(e.color)); }, {
            defaultValue: [{
                    script: Object(script["Script"])('(sel.atom.all)', 'mol-script'),
                    color: names["a" /* ColorNames */].blueviolet,
                    clear: false
                }]
        }),
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var overpaint = mol_theme_overpaint["a" /* Overpaint */].ofScript(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { overpaint: overpaint },
            initialState: { overpaint: mol_theme_overpaint["a" /* Overpaint */].Empty },
            info: structure,
            source: a
        }, { label: "Overpaint (" + overpaint.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var oldStructure = b.data.info;
        var newStructure = a.data.source.data;
        if (newStructure !== oldStructure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldOverpaint = b.data.state.overpaint;
        var newOverpaint = mol_theme_overpaint["a" /* Overpaint */].ofScript(newParams.layers, newStructure);
        if (mol_theme_overpaint["a" /* Overpaint */].areEqual(oldOverpaint, newOverpaint))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.overpaint = newOverpaint;
        b.data.source = a;
        b.label = "Overpaint (" + newOverpaint.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var OverpaintStructureRepresentation3DFromBundle = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'overpaint-structure-representation-3d-from-bundle',
    display: 'Overpaint 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            bundle: param_definition["ParamDefinition"].Value(mol_model_structure["StructureElement"].Bundle.Empty),
            color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].blueviolet),
            clear: param_definition["ParamDefinition"].Boolean(false)
        }, function (e) { return "" + (e.clear ? 'Clear' : color["Color"].toRgbString(e.color)); }, {
            defaultValue: [{
                    bundle: mol_model_structure["StructureElement"].Bundle.Empty,
                    color: names["a" /* ColorNames */].blueviolet,
                    clear: false
                }],
            isHidden: true
        }),
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var overpaint = mol_theme_overpaint["a" /* Overpaint */].ofBundle(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { overpaint: overpaint },
            initialState: { overpaint: mol_theme_overpaint["a" /* Overpaint */].Empty },
            info: structure,
            source: a
        }, { label: "Overpaint (" + overpaint.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var oldStructure = b.data.info;
        var newStructure = a.data.source.data;
        if (newStructure !== oldStructure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldOverpaint = b.data.state.overpaint;
        var newOverpaint = mol_theme_overpaint["a" /* Overpaint */].ofBundle(newParams.layers, newStructure);
        if (mol_theme_overpaint["a" /* Overpaint */].areEqual(oldOverpaint, newOverpaint))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.overpaint = newOverpaint;
        b.data.source = a;
        b.label = "Overpaint (" + newOverpaint.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var TransparencyStructureRepresentation3DFromScript = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'transparency-structure-representation-3d-from-script',
    display: 'Transparency 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            script: param_definition["ParamDefinition"].Script(Object(script["Script"])('(sel.atom.all)', 'mol-script')),
            value: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.01 }, { label: 'Transparency' }),
        }, function (e) { return "Transparency (" + e.value + ")"; }, {
            defaultValue: [{
                    script: Object(script["Script"])('(sel.atom.all)', 'mol-script'),
                    value: 0.5,
                }]
        })
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var transparency = mol_theme_transparency["a" /* Transparency */].ofScript(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { transparency: transparency },
            initialState: { transparency: mol_theme_transparency["a" /* Transparency */].Empty },
            info: structure,
            source: a
        }, { label: "Transparency (" + transparency.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = b.data.info;
        if (a.data.source.data !== structure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldTransparency = b.data.state.transparency;
        var newTransparency = mol_theme_transparency["a" /* Transparency */].ofScript(newParams.layers, structure);
        if (mol_theme_transparency["a" /* Transparency */].areEqual(oldTransparency, newTransparency))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.transparency = newTransparency;
        b.data.source = a;
        b.label = "Transparency (" + newTransparency.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var TransparencyStructureRepresentation3DFromBundle = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'transparency-structure-representation-3d-from-bundle',
    display: 'Transparency 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            bundle: param_definition["ParamDefinition"].Value(mol_model_structure["StructureElement"].Bundle.Empty),
            value: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.01 }, { label: 'Transparency' }),
        }, function (e) { return "Transparency (" + e.value + ")"; }, {
            defaultValue: [{
                    bundle: mol_model_structure["StructureElement"].Bundle.Empty,
                    value: 0.5,
                }],
            isHidden: true
        })
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var transparency = mol_theme_transparency["a" /* Transparency */].ofBundle(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { transparency: transparency },
            initialState: { transparency: mol_theme_transparency["a" /* Transparency */].Empty },
            info: structure,
            source: a
        }, { label: "Transparency (" + transparency.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = b.data.info;
        if (a.data.source.data !== structure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldTransparency = b.data.state.transparency;
        var newTransparency = mol_theme_transparency["a" /* Transparency */].ofBundle(newParams.layers, structure);
        if (mol_theme_transparency["a" /* Transparency */].areEqual(oldTransparency, newTransparency))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.transparency = newTransparency;
        b.data.source = a;
        b.label = "Transparency (" + newTransparency.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var ClippingStructureRepresentation3DFromScript = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'clipping-structure-representation-3d-from-script',
    display: 'Clipping 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            script: param_definition["ParamDefinition"].Script(Object(script["Script"])('(sel.atom.all)', 'mol-script')),
            groups: param_definition["ParamDefinition"].Converted(function (g) { return mol_theme_clipping["a" /* Clipping */].Groups.toNames(g); }, function (n) { return mol_theme_clipping["a" /* Clipping */].Groups.fromNames(n); }, param_definition["ParamDefinition"].MultiSelect(Object(type_helpers["a" /* ObjectKeys */])(mol_theme_clipping["a" /* Clipping */].Groups.Names), param_definition["ParamDefinition"].objectToOptions(mol_theme_clipping["a" /* Clipping */].Groups.Names))),
        }, function (e) { return mol_theme_clipping["a" /* Clipping */].Groups.toNames(e.groups).length + " group(s)"; }, {
            defaultValue: [{
                    script: Object(script["Script"])('(sel.atom.all)', 'mol-script'),
                    groups: 0 /* None */,
                }]
        }),
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var clipping = mol_theme_clipping["a" /* Clipping */].ofScript(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { clipping: clipping },
            initialState: { clipping: mol_theme_clipping["a" /* Clipping */].Empty },
            info: structure,
            source: a
        }, { label: "Clipping (" + clipping.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = b.data.info;
        if (a.data.source.data !== structure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldClipping = b.data.state.clipping;
        var newClipping = mol_theme_clipping["a" /* Clipping */].ofScript(newParams.layers, structure);
        if (mol_theme_clipping["a" /* Clipping */].areEqual(oldClipping, newClipping))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.clipping = newClipping;
        b.data.source = a;
        b.label = "Clipping (" + newClipping.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var ClippingStructureRepresentation3DFromBundle = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'clipping-structure-representation-3d-from-bundle',
    display: 'Clipping 3D Representation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState,
    params: {
        layers: param_definition["ParamDefinition"].ObjectList({
            bundle: param_definition["ParamDefinition"].Value(mol_model_structure["StructureElement"].Bundle.Empty),
            groups: param_definition["ParamDefinition"].Converted(function (g) { return mol_theme_clipping["a" /* Clipping */].Groups.toNames(g); }, function (n) { return mol_theme_clipping["a" /* Clipping */].Groups.fromNames(n); }, param_definition["ParamDefinition"].MultiSelect(Object(type_helpers["a" /* ObjectKeys */])(mol_theme_clipping["a" /* Clipping */].Groups.Names), param_definition["ParamDefinition"].objectToOptions(mol_theme_clipping["a" /* Clipping */].Groups.Names))),
        }, function (e) { return mol_theme_clipping["a" /* Clipping */].Groups.toNames(e.groups).length + " group(s)"; }, {
            defaultValue: [{
                    bundle: mol_model_structure["StructureElement"].Bundle.Empty,
                    groups: 0 /* None */,
                }],
            isHidden: true
        }),
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var structure = a.data.source.data;
        var clipping = mol_theme_clipping["a" /* Clipping */].ofBundle(params.layers, structure);
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState({
            state: { clipping: clipping },
            initialState: { clipping: mol_theme_clipping["a" /* Clipping */].Empty },
            info: structure,
            source: a
        }, { label: "Clipping (" + clipping.layers.length + " Layers)" });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, newParams = _a.newParams, oldParams = _a.oldParams;
        var structure = b.data.info;
        if (a.data.source.data !== structure)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var oldClipping = b.data.state.clipping;
        var newClipping = mol_theme_clipping["a" /* Clipping */].ofBundle(newParams.layers, structure);
        if (mol_theme_clipping["a" /* Clipping */].areEqual(oldClipping, newClipping))
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        b.data.state.clipping = newClipping;
        b.data.source = a;
        b.label = "Clipping (" + newClipping.layers.length + " Layers)";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
//
var representation_VolumeRepresentation3DHelpers;
(function (VolumeRepresentation3DHelpers) {
    function getDefaultParams(ctx, name, volume, volumeParams) {
        var type = ctx.representation.volume.registry.get(name);
        var themeDataCtx = { volume: volume };
        var colorParams = ctx.representation.volume.themes.colorThemeRegistry.get(type.defaultColorTheme.name).getParams(themeDataCtx);
        var sizeParams = ctx.representation.volume.themes.sizeThemeRegistry.get(type.defaultSizeTheme.name).getParams(themeDataCtx);
        var volumeDefaultParams = param_definition["ParamDefinition"].getDefaultValues(type.getParams(ctx.representation.volume.themes, volume));
        return ({
            type: { name: name, params: volumeParams ? Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, volumeDefaultParams), volumeParams) : volumeDefaultParams },
            colorTheme: { name: type.defaultColorTheme.name, params: param_definition["ParamDefinition"].getDefaultValues(colorParams) },
            sizeTheme: { name: type.defaultSizeTheme.name, params: param_definition["ParamDefinition"].getDefaultValues(sizeParams) }
        });
    }
    VolumeRepresentation3DHelpers.getDefaultParams = getDefaultParams;
    function getDefaultParamsStatic(ctx, name, volumeParams, colorName, colorParams, sizeName, sizeParams) {
        var type = ctx.representation.volume.registry.get(name);
        var colorType = ctx.representation.volume.themes.colorThemeRegistry.get(colorName || type.defaultColorTheme.name);
        var sizeType = ctx.representation.volume.themes.sizeThemeRegistry.get(sizeName || type.defaultSizeTheme.name);
        return ({
            type: { name: name, params: volumeParams ? Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, type.defaultValues), volumeParams) : type.defaultValues },
            colorTheme: { name: type.defaultColorTheme.name, params: colorParams ? Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, colorType.defaultValues), colorParams) : colorType.defaultValues },
            sizeTheme: { name: type.defaultSizeTheme.name, params: sizeParams ? Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, sizeType.defaultValues), sizeParams) : sizeType.defaultValues }
        });
    }
    VolumeRepresentation3DHelpers.getDefaultParamsStatic = getDefaultParamsStatic;
    function getDescription(props) {
        return props.isoValue && mol_model_volume["b" /* Volume */].IsoValue.toString(props.isoValue);
    }
    VolumeRepresentation3DHelpers.getDescription = getDescription;
})(representation_VolumeRepresentation3DHelpers || (representation_VolumeRepresentation3DHelpers = {}));
var VolumeRepresentation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'volume-representation-3d',
    display: '3D Representation',
    from: objects["a" /* PluginStateObject */].Volume.Data,
    to: objects["a" /* PluginStateObject */].Volume.Representation3D,
    params: function (a, ctx) {
        var _a = ctx.representation.volume, registry = _a.registry, themeCtx = _a.themes;
        var type = registry.get(registry.default.name);
        if (!a) {
            return {
                type: param_definition["ParamDefinition"].Mapped(registry.default.name, registry.types, function (name) { return param_definition["ParamDefinition"].Group(registry.get(name).getParams(themeCtx, mol_model_volume["b" /* Volume */].One)); }),
                colorTheme: param_definition["ParamDefinition"].Mapped(type.defaultColorTheme.name, themeCtx.colorThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.colorThemeRegistry.get(name).getParams({ volume: mol_model_volume["b" /* Volume */].One })); }),
                sizeTheme: param_definition["ParamDefinition"].Mapped(type.defaultSizeTheme.name, themeCtx.sizeThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.sizeThemeRegistry.get(name).getParams({ volume: mol_model_volume["b" /* Volume */].One })); })
            };
        }
        var dataCtx = { volume: a.data };
        return ({
            type: param_definition["ParamDefinition"].Mapped(registry.default.name, registry.types, function (name) { return param_definition["ParamDefinition"].Group(registry.get(name).getParams(themeCtx, a.data)); }),
            colorTheme: param_definition["ParamDefinition"].Mapped(type.defaultColorTheme.name, themeCtx.colorThemeRegistry.getApplicableTypes(dataCtx), function (name) { return param_definition["ParamDefinition"].Group(themeCtx.colorThemeRegistry.get(name).getParams(dataCtx)); }),
            sizeTheme: param_definition["ParamDefinition"].Mapped(type.defaultSizeTheme.name, themeCtx.sizeThemeRegistry.types, function (name) { return param_definition["ParamDefinition"].Group(themeCtx.sizeThemeRegistry.get(name).getParams(dataCtx)); })
        });
    }
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        // TODO: allow for small molecules
        return oldParams.type.name === newParams.type.name;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Volume Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var propertyCtx, provider, props, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        propertyCtx = { runtime: ctx, assetManager: plugin.managers.asset };
                        provider = plugin.representation.volume.registry.get(params.type.name);
                        if (!provider.ensureCustomProperties) return [3 /*break*/, 2];
                        return [4 /*yield*/, provider.ensureCustomProperties.attach(propertyCtx, a.data)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2:
                        props = params.type.params || {};
                        repr = provider.factory(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.volume.themes), provider.getParams);
                        repr.setTheme(theme["a" /* Theme */].create(plugin.representation.volume.themes, { volume: a.data }, params));
                        // TODO set initial state, repr.setState({})
                        return [4 /*yield*/, repr.createOrUpdate(props, a.data).runInContext(ctx)];
                    case 3:
                        // TODO set initial state, repr.setState({})
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Representation3D({ repr: repr, source: a }, { label: provider.label, description: representation_VolumeRepresentation3DHelpers.getDescription(props) })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Volume Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var oldProvider, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (newParams.type.name !== oldParams.type.name) {
                            oldProvider = plugin.representation.volume.registry.get(oldParams.type.name);
                            if (oldProvider.ensureCustomProperties) {
                                oldProvider.ensureCustomProperties.detach(a.data);
                            }
                            return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Recreate];
                        }
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams.type.params);
                        b.data.repr.setTheme(theme["a" /* Theme */].create(plugin.representation.volume.themes, { volume: a.data }, newParams));
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, a.data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.description = representation_VolumeRepresentation3DHelpers.getDescription(props);
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    }
});
//

var ShapeRepresentation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'shape-representation-3d',
    display: '3D Representation',
    from: objects["a" /* PluginStateObject */].Shape.Provider,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: function (a, ctx) {
        return a ? a.data.params : base["a" /* BaseGeometry */].Params;
    }
})({
    canAutoUpdate: function () {
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Shape Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, repr;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(a.data.params)), params);
                        repr = ShapeRepresentation(a.data.getShape, a.data.geometryUtils);
                        // TODO set initial state, repr.setState({})
                        return [4 /*yield*/, repr.createOrUpdate(props, a.data.data).runInContext(ctx)];
                    case 1:
                        // TODO set initial state, repr.setState({})
                        _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: a.data.label })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Shape Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, a.data.data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    }
});

var ModelUnitcell3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'model-unitcell-3d',
    display: 'Model Unit Cell',
    from: objects["a" /* PluginStateObject */].Molecule.Model,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, UnitcellParams)
})({
    isApplicable: function (a) { return !!property_symmetry["a" /* ModelSymmetry */].Provider.get(a.data); },
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Model Unit Cell', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var symmetry, data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        symmetry = property_symmetry["a" /* ModelSymmetry */].Provider.get(a.data);
                        if (!symmetry)
                            return [2 /*return*/, mol_state["StateObject"].Null];
                        data = getUnitcellData(a.data, symmetry);
                        repr = UnitcellRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return UnitcellParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Unit Cell", description: symmetry.spacegroup.name })];
                }
            });
        }); });
    },
    update: function (_a) {
        var _this = this;
        var a = _a.a, b = _a.b, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Model Unit Cell', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var symmetry, props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        symmetry = property_symmetry["a" /* ModelSymmetry */].Provider.get(a.data);
                        if (!symmetry)
                            return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Null];
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getUnitcellData(a.data, symmetry);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    }
});

var StructureSelectionsDistance3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selections-distance-3d',
    display: '3D Distance',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, DistanceParams)
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Structure Distance', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        data = getDistanceDataFromStructureSelections(a.data);
                        repr = DistanceRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return DistanceParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Distance" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Structure Distance', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getDistanceDataFromStructureSelections(a.data);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
});

var StructureSelectionsAngle3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selections-angle-3d',
    display: '3D Angle',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, AngleParams)
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Structure Angle', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        data = getAngleDataFromStructureSelections(a.data);
                        repr = AngleRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return AngleParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Angle" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Structure Angle', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getAngleDataFromStructureSelections(a.data);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
});

var StructureSelectionsDihedral3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selections-dihedral-3d',
    display: '3D Dihedral',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, DihedralParams)
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Structure Dihedral', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        data = getDihedralDataFromStructureSelections(a.data);
                        repr = DihedralRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return DihedralParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Dihedral" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Structure Dihedral', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getDihedralDataFromStructureSelections(a.data);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
});

var StructureSelectionsLabel3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selections-label-3d',
    display: '3D Label',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, LabelParams)
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Structure Label', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        data = getLabelDataFromStructureSelections(a.data);
                        repr = LabelRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return LabelParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Label" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Structure Label', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getLabelDataFromStructureSelections(a.data);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
});

var StructureSelectionsOrientation3D = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selections-orientation-3d',
    display: '3D Orientation',
    from: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    to: objects["a" /* PluginStateObject */].Shape.Representation3D,
    params: Object(tslib_es6["__assign"])({}, OrientationParams)
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return true;
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Structure Orientation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        data = getOrientationDataFromStructureSelections(a.data);
                        repr = OrientationRepresentation(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.structure.themes), function () { return OrientationParams; });
                        return [4 /*yield*/, repr.createOrUpdate(params, data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Representation3D({ repr: repr, source: a }, { label: "Orientation" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Structure Orientation', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var props, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), newParams);
                        data = getOrientationDataFromStructureSelections(a.data);
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        b.data.source = a;
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
});
//# sourceMappingURL=representation.js.map

/***/ }),
/* 199 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return noop; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function noop() { }
//# sourceMappingURL=noop.js.map


/***/ }),
/* 200 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ interactions_Interactions; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ InteractionsParams; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ computeInteractions; });

// UNUSED EXPORTS: ContactProviderParams

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/valence-model.js + 1 modules
var valence_model = __webpack_require__(228);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary.js
var boundary = __webpack_require__(185);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/features.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var features_Features;
(function (Features) {
    function setPosition(out, unit, index, features) {
        linear_algebra["Vec3"].set(out, features.x[index], features.y[index], features.z[index]);
        linear_algebra["Vec3"].transformMat4(out, out, unit.conformation.operator.matrix);
        return out;
    }
    Features.setPosition = setPosition;
    function createElementsIndex(data, elementsCount) {
        var offsets = new Int32Array(elementsCount + 1);
        var bucketFill = new Int32Array(elementsCount);
        var bucketSizes = new Int32Array(elementsCount);
        var members = data.members, count = data.count, featureOffsets = data.offsets;
        for (var i = 0, il = featureOffsets[count]; i < il; ++i)
            ++bucketSizes[members[i]];
        var offset = 0;
        for (var i = 0; i < elementsCount; i++) {
            offsets[i] = offset;
            offset += bucketSizes[i];
        }
        offsets[elementsCount] = offset;
        var indices = new Int32Array(offset);
        for (var i = 0; i < count; ++i) {
            for (var j = featureOffsets[i], jl = featureOffsets[i + 1]; j < jl; ++j) {
                var a = members[j];
                var oa = offsets[a] + bucketFill[a];
                indices[oa] = i;
                ++bucketFill[a];
            }
        }
        return { indices: indices, offsets: offsets };
    }
    Features.createElementsIndex = createElementsIndex;
    function create(elementsCount, data) {
        var lookup3d;
        var elementsIndex;
        return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, data), { get lookup3d() {
                if (!lookup3d) {
                    var position_1 = { x: data.x, y: data.y, z: data.z, indices: mol_data_int["OrderedSet"].ofBounds(0, data.count) };
                    lookup3d = Object(geometry["c" /* GridLookup3D */])(position_1, Object(boundary["a" /* getBoundary */])(position_1));
                }
                return lookup3d;
            }, get elementsIndex() {
                return elementsIndex || (elementsIndex = createElementsIndex(data, elementsCount));
            }, subset: function (types) { return createSubset(data, types); } });
    }
    Features.create = create;
    function createSubset(data, types) {
        var lookup3d;
        var count = data.count, _types = data.types;
        var _indices = [];
        for (var i = 0; i < count; ++i) {
            if (types.has(_types[i]))
                _indices.push(i);
        }
        var indices = mol_data_int["SortedArray"].ofSortedArray(_indices);
        return {
            indices: indices,
            get lookup3d() {
                if (!lookup3d) {
                    var position_2 = { x: data.x, y: data.y, z: data.z, indices: indices };
                    lookup3d = Object(geometry["c" /* GridLookup3D */])(position_2, Object(boundary["a" /* getBoundary */])(position_2));
                }
                return lookup3d;
            }
        };
    }
    Features.createSubset = createSubset;
    function Info(structure, unit, features) {
        var valenceModel = valence_model["a" /* ValenceModelProvider */].get(structure).value;
        if (!valenceModel || !valenceModel.has(unit.id))
            throw new Error('valence model required');
        return {
            unit: unit,
            types: features.types,
            feature: -1,
            x: features.x,
            y: features.y,
            z: features.z,
            members: features.members,
            offsets: features.offsets,
            idealGeometry: valenceModel.get(unit.id).idealGeometry
        };
    }
    Features.Info = Info;
    function position(out, info) {
        linear_algebra["Vec3"].set(out, info.x[info.feature], info.y[info.feature], info.z[info.feature]);
        linear_algebra["Vec3"].transformMat4(out, out, info.unit.conformation.operator.matrix);
        return out;
    }
    Features.position = position;
    var tmpVecA = Object(linear_algebra["Vec3"])();
    var tmpVecB = Object(linear_algebra["Vec3"])();
    function distance(infoA, infoB) {
        var elementA = infoA.members[infoA.offsets[infoA.feature]];
        var elementB = infoB.members[infoB.offsets[infoB.feature]];
        infoA.unit.conformation.position(infoA.unit.elements[elementA], tmpVecA);
        infoB.unit.conformation.position(infoB.unit.elements[elementB], tmpVecB);
        return linear_algebra["Vec3"].distance(tmpVecA, tmpVecB);
    }
    Features.distance = distance;
    function Provider(types, add) {
        return { types: new Set(types), add: add };
    }
    Features.Provider = Provider;
})(features_Features || (features_Features = {}));

var features_FeaturesBuilder;
(function (FeaturesBuilder) {
    function create(initialCount, chunkSize, features) {
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        var xCenters = util["a" /* ChunkedArray */].create(Float32Array, 1, chunkSize, features ? features.x : initialCount);
        var yCenters = util["a" /* ChunkedArray */].create(Float32Array, 1, chunkSize, features ? features.y : initialCount);
        var zCenters = util["a" /* ChunkedArray */].create(Float32Array, 1, chunkSize, features ? features.z : initialCount);
        var types = util["a" /* ChunkedArray */].create(Uint8Array, 1, chunkSize, features ? features.types : initialCount);
        var groups = util["a" /* ChunkedArray */].create(Uint8Array, 1, chunkSize, features ? features.groups : initialCount);
        var offsets = util["a" /* ChunkedArray */].create(Uint32Array, 1, chunkSize, features ? features.offsets : initialCount);
        var members = util["a" /* ChunkedArray */].create(Uint32Array, 1, chunkSize, features ? features.members : initialCount);
        var state = { x: 0, y: 0, z: 0, offset: 0, count: 0 };
        return {
            startState: function () {
                state.x = 0;
                state.y = 0;
                state.z = 0;
                state.offset = members.elementCount;
                state.count = 0;
            },
            pushMember: function (x, y, z, member) {
                util["a" /* ChunkedArray */].add(members, member);
                state.x += x;
                state.y += y;
                state.z += z;
                state.count += 1;
            },
            finishState: function (type, group) {
                var count = state.count;
                if (count === 0)
                    return;
                util["a" /* ChunkedArray */].add(types, type);
                util["a" /* ChunkedArray */].add(groups, group);
                util["a" /* ChunkedArray */].add(xCenters, state.x / count);
                util["a" /* ChunkedArray */].add(yCenters, state.y / count);
                util["a" /* ChunkedArray */].add(zCenters, state.z / count);
                util["a" /* ChunkedArray */].add(offsets, state.offset);
            },
            add: function (type, group, x, y, z, member) {
                util["a" /* ChunkedArray */].add(types, type);
                util["a" /* ChunkedArray */].add(groups, group);
                util["a" /* ChunkedArray */].add(xCenters, x);
                util["a" /* ChunkedArray */].add(yCenters, y);
                util["a" /* ChunkedArray */].add(zCenters, z);
                util["a" /* ChunkedArray */].add(offsets, members.elementCount);
                util["a" /* ChunkedArray */].add(members, member);
            },
            getFeatures: function (elementsCount) {
                util["a" /* ChunkedArray */].add(offsets, members.elementCount);
                var x = util["a" /* ChunkedArray */].compact(xCenters, true);
                var y = util["a" /* ChunkedArray */].compact(yCenters, true);
                var z = util["a" /* ChunkedArray */].compact(zCenters, true);
                var count = xCenters.elementCount;
                return features_Features.create(elementsCount, {
                    x: x, y: y, z: z, count: count,
                    types: util["a" /* ChunkedArray */].compact(types, true),
                    groups: util["a" /* ChunkedArray */].compact(groups, true),
                    offsets: util["a" /* ChunkedArray */].compact(offsets, true),
                    members: util["a" /* ChunkedArray */].compact(members, true),
                });
            }
        };
    }
    FeaturesBuilder.create = create;
})(features_FeaturesBuilder || (features_FeaturesBuilder = {}));
//# sourceMappingURL=features.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/common.js
var common = __webpack_require__(252);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph.js + 1 modules
var mol_math_graph = __webpack_require__(171);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph/inter-unit-graph.js
var inter_unit_graph = __webpack_require__(244);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/contacts-builder.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var contacts_builder_IntraContactsBuilder;
(function (IntraContactsBuilder) {
    function create(features, elementsCount) {
        var aIndices = [];
        var bIndices = [];
        var types = [];
        return {
            add: function (indexA, indexB, type) {
                aIndices[aIndices.length] = indexA;
                bIndices[bIndices.length] = indexB;
                types[types.length] = type;
            },
            getContacts: function () {
                var builder = new mol_math_graph["a" /* IntAdjacencyGraph */].EdgeBuilder(features.count, aIndices, bIndices);
                var type = new Int8Array(builder.slotCount);
                var flag = new Int8Array(builder.slotCount);
                for (var i = 0, _i = builder.edgeCount; i < _i; i++) {
                    builder.addNextEdge();
                    builder.assignProperty(type, types[i]);
                }
                var graph = builder.createGraph({ type: type, flag: flag });
                var elementsIndex;
                var contacts = Object.defineProperty(graph, 'elementsIndex', {
                    get: function () {
                        return elementsIndex || (elementsIndex = common["b" /* InteractionsIntraContacts */].createElementsIndex(graph, features, elementsCount));
                    }
                });
                return contacts;
            }
        };
    }
    IntraContactsBuilder.create = create;
})(contacts_builder_IntraContactsBuilder || (contacts_builder_IntraContactsBuilder = {}));

var contacts_builder_InterContactsBuilder;
(function (InterContactsBuilder) {
    function create() {
        var builder = new inter_unit_graph["a" /* InterUnitGraph */].Builder();
        return {
            startUnitPair: function (unitA, unitB) {
                builder.startUnitPair(unitA, unitB);
            },
            finishUnitPair: function () {
                builder.finishUnitPair();
            },
            add: function (indexA, indexB, type) {
                builder.add(indexA, indexB, { type: type, flag: 0 /* None */ });
            },
            getContacts: function (unitsFeatures) {
                return new common["a" /* InteractionsInterContacts */](builder.getMap(), unitsFeatures);
            }
        };
    }
    InterContactsBuilder.create = create;
})(contacts_builder_InterContactsBuilder || (contacts_builder_InterContactsBuilder = {}));
//# sourceMappingURL=contacts-builder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/util.js
var chemistry_util = __webpack_require__(30);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic.js
var atomic = __webpack_require__(119);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/contacts.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var ContactsParams = {
    lineOfSightDistFactor: param_definition["ParamDefinition"].Numeric(1.0, { min: 0, max: 3, step: 0.1 }),
};
var MAX_LINE_OF_SIGHT_DISTANCE = 3;
function validPair(structure, infoA, infoB) {
    var indexA = infoA.members[infoA.offsets[infoA.feature]];
    var indexB = infoB.members[infoB.offsets[infoB.feature]];
    if (indexA === indexB)
        return false; // no self interaction
    var altA = Object(chemistry_util["a" /* altLoc */])(infoA.unit, indexA);
    var altB = Object(chemistry_util["a" /* altLoc */])(infoB.unit, indexB);
    if (altA && altB && altA !== altB)
        return false; // incompatible alternate location id
    if (infoA.unit.residueIndex[infoA.unit.elements[indexA]] === infoB.unit.residueIndex[infoB.unit.elements[indexB]])
        return false; // same residue
    // e.g. no hbond if donor and acceptor are bonded
    if (Object(chemistry_util["f" /* connectedTo */])(structure, infoA.unit, indexA, infoB.unit, indexB))
        return false;
    return true;
}
//
function invalidAltLoc(unitA, indexA, unitB, indexB) {
    var altA = Object(chemistry_util["a" /* altLoc */])(unitA, indexA);
    var altB = Object(chemistry_util["a" /* altLoc */])(unitB, indexB);
    return altA && altB && altA !== altB;
}
function isMember(element, info) {
    var feature = info.feature, offsets = info.offsets, members = info.members;
    for (var i = offsets[feature], il = offsets[feature + 1]; i < il; ++i) {
        if (members[i] === element)
            return true;
    }
    return false;
}
var tmpVec = Object(linear_algebra["Vec3"])();
var contacts_tmpVecA = Object(linear_algebra["Vec3"])();
var contacts_tmpVecB = Object(linear_algebra["Vec3"])();
function checkLineOfSight(structure, infoA, infoB, distFactor) {
    var featureA = infoA.feature;
    var featureB = infoB.feature;
    var indexA = infoA.members[infoA.offsets[featureA]];
    var indexB = infoB.members[infoB.offsets[featureB]];
    features_Features.position(contacts_tmpVecA, infoA);
    features_Features.position(contacts_tmpVecB, infoB);
    linear_algebra["Vec3"].scale(tmpVec, linear_algebra["Vec3"].add(tmpVec, contacts_tmpVecA, contacts_tmpVecB), 0.5);
    var distMax = distFactor * MAX_LINE_OF_SIGHT_DISTANCE;
    var _a = structure.lookup3d.find(tmpVec[0], tmpVec[1], tmpVec[2], distMax), count = _a.count, indices = _a.indices, units = _a.units, squaredDistances = _a.squaredDistances;
    if (count === 0)
        return true;
    for (var r = 0; r < count; ++r) {
        var i = indices[r];
        var unit = units[r];
        if (!mol_model_structure["Unit"].isAtomic(unit))
            continue;
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        // allow hydrogens
        if (element === "H" /* H */)
            continue;
        var vdw = Object(atomic["VdwRadius"])(element);
        // check distance
        if (vdw * vdw * distFactor * distFactor <= squaredDistances[r])
            continue;
        // allow different altlocs
        if (invalidAltLoc(unit, i, infoA.unit, indexA) || invalidAltLoc(unit, i, infoB.unit, indexB))
            continue;
        // allow member atoms
        if ((infoA.unit === unit && isMember(i, infoA)) || (infoB.unit === unit && isMember(i, infoB)))
            continue;
        unit.conformation.position(unit.elements[i], tmpVec);
        // allow atoms at the center of functional groups
        if (linear_algebra["Vec3"].squaredDistance(tmpVec, contacts_tmpVecA) < 1 || linear_algebra["Vec3"].squaredDistance(tmpVec, contacts_tmpVecB) < 1)
            continue;
        return false;
    }
    return true;
}
/**
 * Add all intra-unit contacts, i.e. pairs of features
 */
function addUnitContacts(structure, unit, features, builder, testers, props) {
    for (var _i = 0, testers_1 = testers; _i < testers_1.length; _i++) {
        var tester = testers_1[_i];
        _addUnitContacts(structure, unit, features, builder, tester, props);
    }
}
function _addUnitContacts(structure, unit, features, builder, tester, props) {
    var x = features.x, y = features.y, z = features.z;
    var _a = features.subset(tester.requiredFeatures), lookup3d = _a.lookup3d, subsetIndices = _a.indices;
    var infoA = features_Features.Info(structure, unit, features);
    var infoB = Object(tslib_es6["__assign"])({}, infoA);
    var distFactor = props.lineOfSightDistFactor;
    for (var t = 0, tl = mol_data_int["OrderedSet"].size(subsetIndices); t < tl; ++t) {
        var i = mol_data_int["OrderedSet"].getAt(subsetIndices, t);
        var _b = lookup3d.find(x[i], y[i], z[i], tester.maxDistance), count = _b.count, indices = _b.indices, squaredDistances = _b.squaredDistances;
        if (count === 0)
            continue;
        infoA.feature = i;
        for (var r = 0; r < count; ++r) {
            var j = mol_data_int["OrderedSet"].getAt(subsetIndices, indices[r]);
            if (j <= i)
                continue;
            infoB.feature = j;
            if (!validPair(structure, infoA, infoB))
                continue;
            var type = tester.getType(structure, infoA, infoB, squaredDistances[r]);
            if (type && checkLineOfSight(structure, infoA, infoB, distFactor)) {
                builder.add(i, j, type);
            }
        }
    }
}
var _imageTransform = Object(linear_algebra["Mat4"])();
/**
 * Add all inter-unit contacts, i.e. pairs of features
 */
function addStructureContacts(structure, unitA, featuresA, unitB, featuresB, builder, testers, props) {
    var countA = featuresA.count, xA = featuresA.x, yA = featuresA.y, zA = featuresA.z;
    var lookup3d = featuresB.lookup3d;
    // the lookup queries need to happen in the "unitB space".
    // that means imageA = inverseOperB(operA(i))
    var imageTransform = linear_algebra["Mat4"].mul(_imageTransform, unitB.conformation.operator.inverse, unitA.conformation.operator.matrix);
    var isNotIdentity = !linear_algebra["Mat4"].isIdentity(imageTransform);
    var imageA = Object(linear_algebra["Vec3"])();
    var maxDistance = Math.max.apply(Math, testers.map(function (t) { return t.maxDistance; }));
    var _a = lookup3d.boundary.sphere, center = _a.center, radius = _a.radius;
    var testDistanceSq = (radius + maxDistance) * (radius + maxDistance);
    var distFactor = props.lineOfSightDistFactor;
    var infoA = features_Features.Info(structure, unitA, featuresA);
    var infoB = features_Features.Info(structure, unitB, featuresB);
    builder.startUnitPair(unitA, unitB);
    for (var i = 0; i < countA; ++i) {
        linear_algebra["Vec3"].set(imageA, xA[i], yA[i], zA[i]);
        if (isNotIdentity)
            linear_algebra["Vec3"].transformMat4(imageA, imageA, imageTransform);
        if (linear_algebra["Vec3"].squaredDistance(imageA, center) > testDistanceSq)
            continue;
        var _b = lookup3d.find(imageA[0], imageA[1], imageA[2], maxDistance), indices = _b.indices, count = _b.count, squaredDistances = _b.squaredDistances;
        if (count === 0)
            continue;
        infoA.feature = i;
        for (var r = 0; r < count; ++r) {
            var j = indices[r];
            infoB.feature = j;
            if (!validPair(structure, infoA, infoB))
                continue;
            var distanceSq = squaredDistances[r];
            for (var _i = 0, testers_2 = testers; _i < testers_2.length; _i++) {
                var tester = testers_2[_i];
                if (distanceSq < tester.maxDistance * tester.maxDistance) {
                    var type = tester.getType(structure, infoA, infoB, distanceSq);
                    if (type && checkLineOfSight(structure, infoA, infoB, distFactor)) {
                        builder.add(i, j, type);
                        break;
                    }
                }
            }
        }
    }
    builder.finishUnitPair();
}
//# sourceMappingURL=contacts.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/geometry.js
var chemistry_geometry = __webpack_require__(153);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/misc.js
var misc = __webpack_require__(46);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/halogen-bonds.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */





var HalogenBondsParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(4.0, { min: 1, max: 5, step: 0.1 }),
    angleMax: param_definition["ParamDefinition"].Numeric(30, { min: 0, max: 60, step: 1 }),
};
var halBondElements = ["CL" /* CL */, "BR" /* BR */, "I" /* I */, "AT" /* AT */];
/**
 * Halogen bond donors (X-C, with X one of Cl, Br, I or At) not F!
 */
function addUnitHalogenDonors(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    for (var i = 0, il = elements.length; i < il; ++i) {
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        if (halBondElements.includes(element)) {
            builder.add(6 /* HalogenDonor */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    }
}
var X = ["N" /* N */, "O" /* O */, "S" /* S */];
var Y = ["C" /* C */, "N" /* N */, "P" /* P */, "S" /* S */];
/**
 * Halogen bond acceptors (Y-{O|N|S}, with Y=C,P,N,S)
 */
function addUnitHalogenAcceptors(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var _loop_1 = function (i, il) {
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        if (X.includes(element)) {
            var flag_1 = false;
            Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, i, function (unitB, indexB) {
                if (Y.includes(Object(chemistry_util["i" /* typeSymbol */])(unitB, indexB))) {
                    flag_1 = true;
                }
            });
            if (flag_1) {
                builder.add(7 /* HalogenAcceptor */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
            }
        }
    };
    for (var i = 0, il = elements.length; i < il; ++i) {
        _loop_1(i, il);
    }
}
function isHalogenBond(ti, tj) {
    return ((ti === 7 /* HalogenAcceptor */ && tj === 6 /* HalogenDonor */) ||
        (ti === 6 /* HalogenDonor */ && tj === 7 /* HalogenAcceptor */));
}
// http://www.pnas.org/content/101/48/16789.full
var OptimalHalogenAngle = Object(misc["c" /* degToRad */])(180); // adjusted from 165 to account for spherical statistics
var OptimalAcceptorAngle = Object(misc["c" /* degToRad */])(120);
function getOptions(props) {
    return {
        angleMax: Object(misc["c" /* degToRad */])(props.angleMax),
    };
}
function testHalogenBond(structure, infoA, infoB, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (!isHalogenBond(typeA, typeB))
        return;
    var _a = typeA === 6 /* HalogenDonor */ ? [infoA, infoB] : [infoB, infoA], don = _a[0], acc = _a[1];
    var donIndex = don.members[don.offsets[don.feature]];
    var accIndex = acc.members[acc.offsets[acc.feature]];
    var halogenAngles = Object(chemistry_geometry["c" /* calcAngles */])(structure, don.unit, donIndex, acc.unit, accIndex);
    // Singly bonded halogen only (not bromide ion for example)
    if (halogenAngles.length !== 1)
        return;
    if (OptimalHalogenAngle - halogenAngles[0] > opts.angleMax)
        return;
    var acceptorAngles = Object(chemistry_geometry["c" /* calcAngles */])(structure, acc.unit, accIndex, don.unit, donIndex);
    // Angle must be defined. Excludes water as acceptor. Debatable
    if (acceptorAngles.length === 0)
        return;
    if (acceptorAngles.some(function (acceptorAngle) { return OptimalAcceptorAngle - acceptorAngle > opts.angleMax; }))
        return;
    return 5 /* HalogenBond */;
}
//
var HalogenDonorProvider = features_Features.Provider([6 /* HalogenDonor */], addUnitHalogenDonors);
var HalogenAcceptorProvider = features_Features.Provider([7 /* HalogenAcceptor */], addUnitHalogenAcceptors);
var HalogenBondsProvider = {
    name: 'halogen-bonds',
    params: HalogenBondsParams,
    createTester: function (props) {
        var opts = getOptions(props);
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([6 /* HalogenDonor */, 7 /* HalogenAcceptor */]),
            getType: function (structure, infoA, infoB) { return testHalogenBond(structure, infoA, infoB, opts); }
        };
    }
};
//# sourceMappingURL=halogen-bonds.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var model_types = __webpack_require__(22);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/hydrogen-bonds.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */








var GeometryParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(3.5, { min: 1, max: 5, step: 0.1 }),
    backbone: param_definition["ParamDefinition"].Boolean(true, { description: 'Include backbone-to-backbone hydrogen bonds' }),
    accAngleDevMax: param_definition["ParamDefinition"].Numeric(45, { min: 0, max: 180, step: 1 }, { description: 'Max deviation from ideal acceptor angle' }),
    donAngleDevMax: param_definition["ParamDefinition"].Numeric(45, { min: 0, max: 180, step: 1 }, { description: 'Max deviation from ideal donor angle' }),
    accOutOfPlaneAngleMax: param_definition["ParamDefinition"].Numeric(90, { min: 0, max: 180, step: 1 }),
    donOutOfPlaneAngleMax: param_definition["ParamDefinition"].Numeric(45, { min: 0, max: 180, step: 1 }),
};
var HydrogenBondsParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, GeometryParams), { water: param_definition["ParamDefinition"].Boolean(false, { description: 'Include water-to-water hydrogen bonds' }), sulfurDistanceMax: param_definition["ParamDefinition"].Numeric(4.1, { min: 1, max: 5, step: 0.1 }) });
var WeakHydrogenBondsParams = Object(tslib_es6["__assign"])({}, GeometryParams);
//
// Geometric characteristics of hydrogen bonds involving sulfur atoms in proteins
// https://doi.org/10.1002/prot.22327
// Satisfying Hydrogen Bonding Potential in Proteins (HBPLUS)
// https://doi.org/10.1006/jmbi.1994.1334
// http://www.csb.yale.edu/userguides/datamanip/hbplus/hbplus_descrip.html
function getUnitValenceModel(structure, unit) {
    var valenceModel = valence_model["a" /* ValenceModelProvider */].get(structure).value;
    if (!valenceModel)
        throw Error('expected valence model to be available');
    var unitValenceModel = valenceModel.get(unit.id);
    if (!unitValenceModel)
        throw Error('expected valence model for unit to be available');
    return unitValenceModel;
}
/**
 * Potential hydrogen donor
 */
function addUnitHydrogenDonors(structure, unit, builder) {
    var totalH = getUnitValenceModel(structure, unit).totalH;
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var elementAromaticRingIndices = unit.rings.elementAromaticRingIndices;
    for (var i = 0, il = elements.length; i < il; ++i) {
        if (elementAromaticRingIndices.has(i))
            continue;
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        if ((
        // include both nitrogen atoms in histidine due to
        // their often ambiguous protonation assignment
        isHistidineNitrogen(unit, i)) || (totalH[i] > 0 &&
            (element === "N" /* N */ || element === "O" /* O */ || element === "S" /* S */))) {
            builder.add(4 /* HydrogenDonor */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    }
}
/**
 * Weak hydrogen donor.
 */
function addUnitWeakHydrogenDonors(structure, unit, builder) {
    var totalH = getUnitValenceModel(structure, unit).totalH;
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    for (var i = 0, il = elements.length; i < il; ++i) {
        if (Object(chemistry_util["i" /* typeSymbol */])(unit, i) === "C" /* C */ &&
            totalH[i] > 0 &&
            (Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, i, "N" /* N */) > 0 ||
                Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, i, "O" /* O */) > 0 ||
                inAromaticRingWithElectronNegativeElement(unit, i))) {
            builder.add(9 /* WeakHydrogenDonor */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    }
}
function inAromaticRingWithElectronNegativeElement(unit, index) {
    var _a = unit.rings, elementAromaticRingIndices = _a.elementAromaticRingIndices, all = _a.all;
    var ringIndices = elementAromaticRingIndices.get(index);
    if (ringIndices === undefined)
        return false;
    for (var i = 0, il = ringIndices.length; i < il; ++i) {
        var ring = all[ringIndices[i]];
        for (var j = 0, jl = ring.length; j < jl; ++j) {
            var element = Object(chemistry_util["i" /* typeSymbol */])(unit, ring[j]);
            if (element === "N" /* N */ || element === "O" /* O */) {
                return true;
            }
        }
    }
    return false;
}
/**
 * Potential hydrogen acceptor
 */
function addUnitHydrogenAcceptors(structure, unit, builder) {
    var _a = getUnitValenceModel(structure, unit), charge = _a.charge, implicitH = _a.implicitH, idealGeometry = _a.idealGeometry;
    var elements = unit.elements;
    var _b = unit.model.atomicConformation, x = _b.x, y = _b.y, z = _b.z;
    var elementAromaticRingIndices = unit.rings.elementAromaticRingIndices;
    var add = function (i) {
        builder.add(5 /* HydrogenAcceptor */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
    };
    for (var i = 0, il = elements.length; i < il; ++i) {
        if (elementAromaticRingIndices.has(i))
            continue;
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        if (element === "O" /* O */) {
            // Basically assume all oxygen atoms are acceptors!
            add(i);
        }
        else if (element === "N" /* N */) {
            if (isHistidineNitrogen(unit, i)) {
                // include both nitrogen atoms in histidine due to
                // their often ambiguous protonation assignment
                add(i);
            }
            else if (charge[i] < 1) {
                // Neutral nitrogen might be an acceptor
                // It must have at least one lone pair not conjugated
                var totalBonds = Object(chemistry_util["c" /* bondCount */])(structure, unit, i) + implicitH[i];
                var ig = idealGeometry[i];
                if ((ig === 4 /* Tetrahedral */ && totalBonds < 4) ||
                    (ig === 3 /* Trigonal */ && totalBonds < 3) ||
                    (ig === 2 /* Linear */ && totalBonds < 2)) {
                    add(i);
                }
            }
        }
        else if (element === "S" /* S */) {
            var resname = Object(chemistry_util["e" /* compId */])(unit, i);
            if (resname === 'CYS' || resname === 'MET' || Object(chemistry_util["h" /* formalCharge */])(unit, i) === -1) {
                add(i);
            }
        }
    }
}
function isWater(unit, index) {
    return unit.model.atomicHierarchy.derived.residue.moleculeType[unit.residueIndex[unit.elements[index]]] === 2 /* Water */;
}
function isBackbone(unit, index) {
    return model_types["ProteinBackboneAtoms"].has(Object(chemistry_util["b" /* atomId */])(unit, index));
}
function isRing(unit, index) {
    return unit.rings.elementRingIndices.has(index);
}
function isHistidineNitrogen(unit, index) {
    return Object(chemistry_util["e" /* compId */])(unit, index) === 'HIS' && Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "N" /* N */ && isRing(unit, index);
}
function isBackboneHydrogenBond(unitA, indexA, unitB, indexB) {
    return isBackbone(unitA, indexA) && isBackbone(unitB, indexB);
}
function isWaterHydrogenBond(unitA, indexA, unitB, indexB) {
    return isWater(unitA, indexA) && isWater(unitB, indexB);
}
function isHydrogenBond(ti, tj) {
    return ((ti === 5 /* HydrogenAcceptor */ && tj === 4 /* HydrogenDonor */) ||
        (ti === 4 /* HydrogenDonor */ && tj === 5 /* HydrogenAcceptor */));
}
function isWeakHydrogenBond(ti, tj) {
    return ((ti === 9 /* WeakHydrogenDonor */ && tj === 5 /* HydrogenAcceptor */) ||
        (ti === 5 /* HydrogenAcceptor */ && tj === 9 /* WeakHydrogenDonor */));
}
function getGeometryOptions(props) {
    return {
        includeBackbone: props.backbone,
        maxAccAngleDev: Object(misc["c" /* degToRad */])(props.accAngleDevMax),
        maxDonAngleDev: Object(misc["c" /* degToRad */])(props.donAngleDevMax),
        maxAccOutOfPlaneAngle: Object(misc["c" /* degToRad */])(props.accOutOfPlaneAngleMax),
        maxDonOutOfPlaneAngle: Object(misc["c" /* degToRad */])(props.donOutOfPlaneAngleMax),
    };
}
function getHydrogenBondsOptions(props) {
    return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, getGeometryOptions(props)), { includeWater: props.water, maxSulfurDistSq: props.sulfurDistanceMax * props.sulfurDistanceMax, maxDistSq: props.distanceMax * props.distanceMax });
}
var deg120InRad = Object(misc["c" /* degToRad */])(120);
function checkGeometry(structure, don, acc, opts) {
    var donIndex = don.members[don.offsets[don.feature]];
    var accIndex = acc.members[acc.offsets[acc.feature]];
    if (!opts.includeBackbone && isBackboneHydrogenBond(don.unit, donIndex, acc.unit, accIndex))
        return;
    var donAngles = Object(chemistry_geometry["c" /* calcAngles */])(structure, don.unit, donIndex, acc.unit, accIndex);
    var idealDonAngle = chemistry_geometry["a" /* AtomGeometryAngles */].get(don.idealGeometry[donIndex]) || deg120InRad;
    if (donAngles.some(function (donAngle) { return Math.abs(idealDonAngle - donAngle) > opts.maxDonAngleDev; }))
        return;
    if (don.idealGeometry[donIndex] === 3 /* Trigonal */) {
        var outOfPlane = Object(chemistry_geometry["d" /* calcPlaneAngle */])(structure, don.unit, donIndex, acc.unit, accIndex);
        if (outOfPlane !== undefined && outOfPlane > opts.maxDonOutOfPlaneAngle)
            return;
    }
    var accAngles = Object(chemistry_geometry["c" /* calcAngles */])(structure, acc.unit, accIndex, don.unit, donIndex);
    var idealAccAngle = chemistry_geometry["a" /* AtomGeometryAngles */].get(acc.idealGeometry[accIndex]) || deg120InRad;
    // Do not limit large acceptor angles
    if (accAngles.some(function (accAngle) { return idealAccAngle - accAngle > opts.maxAccAngleDev; }))
        return;
    if (acc.idealGeometry[accIndex] === 3 /* Trigonal */) {
        var outOfPlane = Object(chemistry_geometry["d" /* calcPlaneAngle */])(structure, acc.unit, accIndex, don.unit, donIndex);
        if (outOfPlane !== undefined && outOfPlane > opts.maxAccOutOfPlaneAngle)
            return;
    }
    return true;
}
function testHydrogenBond(structure, infoA, infoB, distanceSq, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (!isHydrogenBond(typeA, typeB))
        return;
    var _a = typeB === 5 /* HydrogenAcceptor */ ? [infoA, infoB] : [infoB, infoA], don = _a[0], acc = _a[1];
    var donIndex = don.members[don.offsets[don.feature]];
    var accIndex = acc.members[acc.offsets[acc.feature]];
    // check if distance is ok depending on non-sulfur-containing hbond
    var maxDistSq = Object(chemistry_util["i" /* typeSymbol */])(don.unit, donIndex) === "S" /* S */ || Object(chemistry_util["i" /* typeSymbol */])(acc.unit, accIndex) === "S" /* S */ ? opts.maxSulfurDistSq : opts.maxDistSq;
    if (distanceSq > maxDistSq)
        return;
    if (!opts.includeWater && isWaterHydrogenBond(don.unit, donIndex, acc.unit, accIndex))
        return;
    if (!checkGeometry(structure, don, acc, opts))
        return;
    return 4 /* HydrogenBond */;
}
function testWeakHydrogenBond(structure, infoA, infoB, distanceSq, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (!isWeakHydrogenBond(typeA, typeB))
        return;
    var _a = typeB === 5 /* HydrogenAcceptor */ ? [infoA, infoB] : [infoB, infoA], don = _a[0], acc = _a[1];
    if (!checkGeometry(structure, don, acc, opts))
        return;
    return 8 /* WeakHydrogenBond */;
}
//
var HydrogenDonorProvider = features_Features.Provider([4 /* HydrogenDonor */], addUnitHydrogenDonors);
var WeakHydrogenDonorProvider = features_Features.Provider([9 /* WeakHydrogenDonor */], addUnitWeakHydrogenDonors);
var HydrogenAcceptorProvider = features_Features.Provider([5 /* HydrogenAcceptor */], addUnitHydrogenAcceptors);
var HydrogenBondsProvider = {
    name: 'hydrogen-bonds',
    params: HydrogenBondsParams,
    createTester: function (props) {
        var maxDistance = Math.max(props.distanceMax, props.sulfurDistanceMax);
        var opts = getHydrogenBondsOptions(props);
        return {
            maxDistance: maxDistance,
            requiredFeatures: new Set([4 /* HydrogenDonor */, 5 /* HydrogenAcceptor */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testHydrogenBond(structure, infoA, infoB, distanceSq, opts); }
        };
    }
};
var WeakHydrogenBondsProvider = {
    name: 'weak-hydrogen-bonds',
    params: WeakHydrogenBondsParams,
    createTester: function (props) {
        var opts = getGeometryOptions(props);
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([9 /* WeakHydrogenDonor */, 5 /* HydrogenAcceptor */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testWeakHydrogenBond(structure, infoA, infoB, distanceSq, opts); }
        };
    }
};
//# sourceMappingURL=hydrogen-bonds.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic/types.js
var atomic_types = __webpack_require__(245);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/functional-group.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function isAromatic(unit, index) {
    // TODO also extend unit.rings with geometry/composition-based aromaticity detection and use it here in addition
    var _a = unit.bonds, offset = _a.offset, edgeProps = _a.edgeProps;
    for (var i = offset[index], il = offset[index + 1]; i < il; ++i) {
        if (model_types["BondType"].is(16 /* Aromatic */, edgeProps.flags[i]))
            return true;
    }
    return false;
}
function bondToCarbonylCount(structure, unit, index) {
    var carbonylCount = 0;
    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
        if (isCarbonyl(structure, unit, index))
            carbonylCount += 1;
    });
    return carbonylCount;
}
//
/**
 * Nitrogen in a quaternary amine
 */
function isQuaternaryAmine(structure, unit, index) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "N" /* N */ &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 4 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */) === 0);
}
/**
 * Nitrogen in a tertiary amine
 */
function isTertiaryAmine(structure, unit, index, idealValence) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "N" /* N */ &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 4 &&
        idealValence === 3);
}
/**
 * Nitrogen in an imide
 */
function isImide(structure, unit, index) {
    var flag = false;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "N" /* N */ &&
        (Object(chemistry_util["c" /* bondCount */])(structure, unit, index) - Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */)) === 2) {
        flag = bondToCarbonylCount(structure, unit, index) === 2;
    }
    return flag;
}
/**
 * Nitrogen in an amide
 */
function isAmide(structure, unit, index) {
    var flag = false;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "N" /* N */ &&
        (Object(chemistry_util["c" /* bondCount */])(structure, unit, index) - Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */)) === 2) {
        flag = bondToCarbonylCount(structure, unit, index) === 1;
    }
    return flag;
}
/**
 * Sulfur in a sulfonium group
 */
function isSulfonium(structure, unit, index) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "S" /* S */ &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 3 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */) === 0);
}
/**
 * Sulfur in a sulfonic acid or sulfonate group
 */
function isSulfonicAcid(structure, unit, index) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "S" /* S */ &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "O" /* O */) === 3);
}
/**
 * Sulfur in a sulfate group
 */
function isSulfate(structure, unit, index) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "S" /* S */ &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "O" /* O */) === 4);
}
/**
 * Phosphor in a phosphate group
 */
function isPhosphate(structure, unit, index) {
    return (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "P" /* P */ &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "O" /* O */) === Object(chemistry_util["c" /* bondCount */])(structure, unit, index));
}
/**
 * Halogen with one bond to a carbon
 */
function isHalocarbon(structure, unit, index) {
    return (Object(atomic_types["b" /* isHalogen */])(Object(chemistry_util["i" /* typeSymbol */])(unit, index)) &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 1 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "C" /* C */) === 1);
}
/**
 * Carbon in a carbonyl/acyl group
 *
 * TODO currently only checks intra bonds for group detection
 */
function isCarbonyl(structure, unit, index) {
    var flag = false;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "C" /* C */) {
        var _a = unit.bonds, offset = _a.offset, edgeProps = _a.edgeProps, b = _a.b;
        for (var i = offset[index], il = offset[index + 1]; i < il; ++i) {
            if (edgeProps.order[i] === 2 && Object(chemistry_util["i" /* typeSymbol */])(unit, b[i]) === "O" /* O */) {
                flag = true;
                break;
            }
        }
    }
    return flag;
}
/**
 * Carbon in a carboxylate group
 */
function isCarboxylate(structure, unit, index) {
    var terminalOxygenCount = 0;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "C" /* C */ &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "O" /* O */) === 2 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "C" /* C */) === 1) {
        Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
            if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "O" /* O */ &&
                Object(chemistry_util["c" /* bondCount */])(structure, unit, index) - Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */) === 1) {
                terminalOxygenCount += 1;
            }
        });
    }
    return terminalOxygenCount === 2;
}
/**
 * Carbon in a guanidine group
 */
function isGuanidine(structure, unit, index) {
    var terminalNitrogenCount = 0;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "C" /* C */ &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 3 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "N" /* N */) === 3) {
        Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
            if (Object(chemistry_util["c" /* bondCount */])(structure, unit, index) - Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */) === 1) {
                terminalNitrogenCount += 1;
            }
        });
    }
    return terminalNitrogenCount === 2;
}
/**
 * Carbon in a acetamidine group
 */
function isAcetamidine(structure, unit, index) {
    var terminalNitrogenCount = 0;
    if (Object(chemistry_util["i" /* typeSymbol */])(unit, index) === "C" /* C */ &&
        Object(chemistry_util["c" /* bondCount */])(structure, unit, index) === 3 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "N" /* N */) === 2 &&
        Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "C" /* C */) === 1) {
        Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
            if (Object(chemistry_util["c" /* bondCount */])(structure, unit, index) - Object(chemistry_util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */) === 1) {
                terminalNitrogenCount += 1;
            }
        });
    }
    return terminalNitrogenCount === 2;
}
var PolarElements = new Set(['N', 'O', 'S', 'F', 'CL', 'BR', 'I']);
function isPolar(element) { return PolarElements.has(element); }
function hasPolarNeighbour(structure, unit, index) {
    var flag = false;
    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
        if (isPolar(Object(chemistry_util["i" /* typeSymbol */])(unit, index)))
            flag = true;
    });
    return flag;
}
function hasAromaticNeighbour(structure, unit, index) {
    var flag = false;
    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, index, function (unit, index) {
        if (isAromatic(unit, index))
            flag = true;
    });
    return flag;
}
//# sourceMappingURL=functional-group.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/charged.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */









var IonicParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(5.0, { min: 0, max: 8, step: 0.1 }),
};
var PiStackingParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(5.5, { min: 1, max: 8, step: 0.1 }),
    offsetMax: param_definition["ParamDefinition"].Numeric(2.0, { min: 0, max: 4, step: 0.1 }),
    angleDevMax: param_definition["ParamDefinition"].Numeric(30, { min: 0, max: 180, step: 1 }),
};
var CationPiParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(6.0, { min: 1, max: 8, step: 0.1 }),
    offsetMax: param_definition["ParamDefinition"].Numeric(2.0, { min: 0, max: 4, step: 0.1 }),
};
//
var PositvelyCharged = ['ARG', 'HIS', 'LYS'];
var NegativelyCharged = ['GLU', 'ASP'];
function charged_getUnitValenceModel(structure, unit) {
    var valenceModel = valence_model["a" /* ValenceModelProvider */].get(structure).value;
    if (!valenceModel)
        throw Error('expected valence model to be available');
    var unitValenceModel = valenceModel.get(unit.id);
    if (!unitValenceModel)
        throw Error('expected valence model for unit to be available');
    return unitValenceModel;
}
function addUnitPositiveCharges(structure, unit, builder) {
    var charge = charged_getUnitValenceModel(structure, unit).charge;
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var addedElements = new Set();
    var label_comp_id = unit.model.atomicHierarchy.atoms.label_comp_id;
    var residueIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements);
    while (residueIt.hasNext) {
        var _b = residueIt.move(), residueIndex = _b.index, start = _b.start, end = _b.end;
        var compId = label_comp_id.value(unit.model.atomicHierarchy.residueAtomSegments.offsets[residueIndex]);
        if (PositvelyCharged.includes(compId)) {
            builder.startState();
            for (var j = start; j < end; ++j) {
                if (Object(chemistry_util["i" /* typeSymbol */])(unit, j) === "N" /* N */ && !model_types["ProteinBackboneAtoms"].has(Object(chemistry_util["b" /* atomId */])(unit, j))) {
                    builder.pushMember(x[elements[j]], y[elements[j]], z[elements[j]], j);
                }
            }
            builder.finishState(1 /* PositiveCharge */, 0 /* None */);
        }
        else if (!model_types["PolymerNames"].has(compId)) {
            addedElements.clear();
            for (var j = start; j < end; ++j) {
                var group = 0 /* None */;
                if (isGuanidine(structure, unit, j)) {
                    group = 8 /* Guanidine */;
                }
                else if (isAcetamidine(structure, unit, j)) {
                    group = 9 /* Acetamidine */;
                }
                if (group) {
                    builder.startState();
                    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, j, function (_, k) {
                        if (Object(chemistry_util["i" /* typeSymbol */])(unit, k) === "N" /* N */) {
                            addedElements.add(k);
                            builder.pushMember(x[elements[k]], y[elements[k]], z[elements[k]], k);
                        }
                    });
                    builder.finishState(1 /* PositiveCharge */, group);
                }
            }
            for (var j = start; j < end; ++j) {
                if (charge[j] > 0 && !addedElements.has(j)) {
                    builder.add(1 /* PositiveCharge */, 0 /* None */, x[elements[j]], y[elements[j]], z[elements[j]], j);
                }
            }
        }
    }
}
function addUnitNegativeCharges(structure, unit, builder) {
    var charge = charged_getUnitValenceModel(structure, unit).charge;
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var addedElements = new Set();
    var label_comp_id = unit.model.atomicHierarchy.atoms.label_comp_id;
    var residueIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements);
    while (residueIt.hasNext) {
        var _b = residueIt.move(), residueIndex = _b.index, start = _b.start, end = _b.end;
        var compId = label_comp_id.value(unit.model.atomicHierarchy.residueAtomSegments.offsets[residueIndex]);
        if (NegativelyCharged.includes(compId)) {
            builder.startState();
            for (var j = start; j < end; ++j) {
                if (Object(chemistry_util["i" /* typeSymbol */])(unit, j) === "O" /* O */ && !model_types["ProteinBackboneAtoms"].has(Object(chemistry_util["b" /* atomId */])(unit, j))) {
                    builder.pushMember(x[elements[j]], y[elements[j]], z[elements[j]], j);
                }
            }
            builder.finishState(2 /* NegativeCharge */, 0 /* None */);
        }
        else if (model_types["BaseNames"].has(compId)) {
            for (var j = start; j < end; ++j) {
                if (isPhosphate(structure, unit, j)) {
                    builder.startState();
                    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, j, function (_, k) {
                        if (Object(chemistry_util["i" /* typeSymbol */])(unit, k) === "O" /* O */) {
                            builder.pushMember(x[elements[k]], y[elements[k]], z[elements[k]], k);
                        }
                    });
                    builder.finishState(2 /* NegativeCharge */, 6 /* Phosphate */);
                }
            }
        }
        else if (!model_types["PolymerNames"].has(compId)) {
            for (var j = start; j < end; ++j) {
                builder.startState();
                if (Object(chemistry_util["i" /* typeSymbol */])(unit, j) === "N" /* N */ && !model_types["ProteinBackboneAtoms"].has(Object(chemistry_util["b" /* atomId */])(unit, j))) {
                    builder.pushMember(x[elements[j]], y[elements[j]], z[elements[j]], j);
                }
                builder.finishState(2 /* NegativeCharge */, 0 /* None */);
                var group = 0 /* None */;
                if (isSulfonicAcid(structure, unit, j)) {
                    group = 4 /* SulfonicAcid */;
                }
                else if (isPhosphate(structure, unit, j)) {
                    group = 6 /* Phosphate */;
                }
                else if (isSulfate(structure, unit, j)) {
                    group = 5 /* Sulfate */;
                }
                else if (isCarboxylate(structure, unit, j)) {
                    group = 10 /* Carboxylate */;
                }
                if (group) {
                    builder.startState();
                    Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, j, function (_, k) {
                        if (Object(chemistry_util["i" /* typeSymbol */])(unit, k) === "O" /* O */) {
                            addedElements.add(k);
                            builder.pushMember(x[elements[k]], y[elements[k]], z[elements[k]], k);
                        }
                    });
                    builder.finishState(2 /* NegativeCharge */, group);
                }
            }
            for (var j = start; j < end; ++j) {
                if (charge[j] < 0 && !addedElements.has(j)) {
                    builder.add(2 /* NegativeCharge */, 0 /* None */, x[elements[j]], y[elements[j]], z[elements[j]], j);
                }
            }
        }
    }
}
function addUnitAromaticRings(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    for (var _i = 0, _b = unit.rings.aromaticRings; _i < _b.length; _i++) {
        var ringIndex = _b[_i];
        var ring = unit.rings.all[ringIndex];
        builder.startState();
        for (var i = 0, il = ring.length; i < il; ++i) {
            var j = ring[i];
            builder.pushMember(x[elements[j]], y[elements[j]], z[elements[j]], j);
        }
        builder.finishState(3 /* AromaticRing */, 0 /* None */);
    }
}
function isIonic(ti, tj) {
    return ((ti === 2 /* NegativeCharge */ && tj === 1 /* PositiveCharge */) ||
        (ti === 1 /* PositiveCharge */ && tj === 2 /* NegativeCharge */));
}
function isPiStacking(ti, tj) {
    return ti === 3 /* AromaticRing */ && tj === 3 /* AromaticRing */;
}
function isCationPi(ti, tj) {
    return ((ti === 3 /* AromaticRing */ && tj === 1 /* PositiveCharge */) ||
        (ti === 1 /* PositiveCharge */ && tj === 3 /* AromaticRing */));
}
var tmpPointA = Object(linear_algebra["Vec3"])();
var tmpPointB = Object(linear_algebra["Vec3"])();
function areFeaturesWithinDistanceSq(infoA, infoB, distanceSq) {
    var featureA = infoA.feature, offsetsA = infoA.offsets, membersA = infoA.members;
    var featureB = infoB.feature, offsetsB = infoB.offsets, membersB = infoB.members;
    for (var i = offsetsA[featureA], il = offsetsA[featureA + 1]; i < il; ++i) {
        var elementA = membersA[i];
        infoA.unit.conformation.position(infoA.unit.elements[elementA], tmpPointA);
        for (var j = offsetsB[featureB], jl = offsetsB[featureB + 1]; j < jl; ++j) {
            var elementB = membersB[j];
            infoB.unit.conformation.position(infoB.unit.elements[elementB], tmpPointB);
            if (linear_algebra["Vec3"].squaredDistance(tmpPointA, tmpPointB) < distanceSq)
                return true;
        }
    }
    return false;
}
var charged_tmpVecA = Object(linear_algebra["Vec3"])();
var charged_tmpVecB = Object(linear_algebra["Vec3"])();
var tmpVecC = Object(linear_algebra["Vec3"])();
var tmpVecD = Object(linear_algebra["Vec3"])();
function getNormal(out, info) {
    var unit = info.unit, feature = info.feature, offsets = info.offsets, members = info.members;
    var elements = unit.elements;
    var i = offsets[feature];
    info.unit.conformation.position(elements[members[i]], charged_tmpVecA);
    info.unit.conformation.position(elements[members[i + 1]], charged_tmpVecB);
    info.unit.conformation.position(elements[members[i + 2]], tmpVecC);
    return linear_algebra["Vec3"].triangleNormal(out, charged_tmpVecA, charged_tmpVecB, tmpVecC);
}
var getOffset = function (infoA, infoB, normal) {
    features_Features.position(charged_tmpVecA, infoA);
    features_Features.position(charged_tmpVecB, infoB);
    linear_algebra["Vec3"].sub(tmpVecC, charged_tmpVecA, charged_tmpVecB);
    linear_algebra["Vec3"].projectOnPlane(tmpVecD, tmpVecC, normal);
    linear_algebra["Vec3"].add(tmpVecD, tmpVecD, charged_tmpVecB);
    return linear_algebra["Vec3"].distance(tmpVecD, charged_tmpVecB);
};
function getIonicOptions(props) {
    return {
        distanceMaxSq: props.distanceMax * props.distanceMax,
    };
}
function getPiStackingOptions(props) {
    return {
        offsetMax: props.offsetMax,
        angleDevMax: Object(misc["c" /* degToRad */])(props.angleDevMax),
    };
}
function getCationPiOptions(props) {
    return {
        offsetMax: props.offsetMax
    };
}
var deg180InRad = Object(misc["c" /* degToRad */])(180);
var deg90InRad = Object(misc["c" /* degToRad */])(90);
var tmpNormalA = Object(linear_algebra["Vec3"])();
var tmpNormalB = Object(linear_algebra["Vec3"])();
function testIonic(structure, infoA, infoB, distanceSq, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (isIonic(typeA, typeB)) {
        if (areFeaturesWithinDistanceSq(infoA, infoB, opts.distanceMaxSq)) {
            return 1 /* Ionic */;
        }
    }
}
function testPiStacking(structure, infoA, infoB, distanceSq, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (isPiStacking(typeA, typeB)) {
        getNormal(tmpNormalA, infoA);
        getNormal(tmpNormalB, infoB);
        var angle = linear_algebra["Vec3"].angle(tmpNormalA, tmpNormalB);
        var offset = Math.min(getOffset(infoA, infoB, tmpNormalB), getOffset(infoB, infoA, tmpNormalA));
        if (offset <= opts.offsetMax) {
            if (angle <= opts.angleDevMax || angle >= deg180InRad - opts.angleDevMax) {
                return 3 /* PiStacking */; // parallel
            }
            else if (angle <= opts.angleDevMax + deg90InRad && angle >= deg90InRad - opts.angleDevMax) {
                return 3 /* PiStacking */; // t-shaped
            }
        }
    }
}
function testCationPi(structure, infoA, infoB, distanceSq, opts) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (isCationPi(typeA, typeB)) {
        var _a = typeA === 3 /* AromaticRing */ ? [infoA, infoB] : [infoB, infoA], infoR = _a[0], infoC = _a[1];
        getNormal(tmpNormalA, infoR);
        var offset = getOffset(infoC, infoR, tmpNormalA);
        if (offset <= opts.offsetMax) {
            return 2 /* CationPi */;
        }
    }
}
//
var NegativChargeProvider = features_Features.Provider([2 /* NegativeCharge */], addUnitNegativeCharges);
var PositiveChargeProvider = features_Features.Provider([1 /* PositiveCharge */], addUnitPositiveCharges);
var AromaticRingProvider = features_Features.Provider([3 /* AromaticRing */], addUnitAromaticRings);
var IonicProvider = {
    name: 'ionic',
    params: IonicParams,
    createTester: function (props) {
        var opts = getIonicOptions(props);
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([2 /* NegativeCharge */, 1 /* PositiveCharge */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testIonic(structure, infoA, infoB, distanceSq, opts); }
        };
    }
};
var PiStackingProvider = {
    name: 'pi-stacking',
    params: PiStackingParams,
    createTester: function (props) {
        var opts = getPiStackingOptions(props);
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([3 /* AromaticRing */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testPiStacking(structure, infoA, infoB, distanceSq, opts); }
        };
    }
};
var CationPiProvider = {
    name: 'cation-pi',
    params: CationPiParams,
    createTester: function (props) {
        var opts = getCationPiOptions(props);
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([3 /* AromaticRing */, 1 /* PositiveCharge */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testCationPi(structure, infoA, infoB, distanceSq, opts); }
        };
    }
};
//# sourceMappingURL=charged.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/hydrophobic.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */



var HydrophobicParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(4.0, { min: 1, max: 5, step: 0.1 }),
};
/**
 * Hydropbobic atoms
 * - Carbon only bonded to carbon or hydrogen
 * - Fluorine
 */
function addHydrophobicAtom(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    var _loop_1 = function (i, il) {
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        var flag = false;
        if (element === "C" /* C */) {
            flag = true;
            Object(chemistry_util["g" /* eachBondedAtom */])(structure, unit, i, function (unitB, indexB) {
                var elementB = Object(chemistry_util["i" /* typeSymbol */])(unitB, indexB);
                if (elementB !== "C" /* C */ && elementB !== "H" /* H */)
                    flag = false;
            });
        }
        else if (element === "F" /* F */) {
            flag = true;
        }
        if (flag) {
            builder.add(8 /* HydrophobicAtom */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    };
    for (var i = 0, il = elements.length; i < il; ++i) {
        _loop_1(i, il);
    }
}
function isHydrophobicContact(ti, tj) {
    return ti === 8 /* HydrophobicAtom */ && tj === 8 /* HydrophobicAtom */;
}
function testHydrophobic(structure, infoA, infoB, distanceSq) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (!isHydrophobicContact(typeA, typeB))
        return;
    var indexA = infoA.members[infoA.offsets[infoA.feature]];
    var indexB = infoB.members[infoB.offsets[infoB.feature]];
    if (Object(chemistry_util["i" /* typeSymbol */])(infoA.unit, indexA) === "F" /* F */ && Object(chemistry_util["i" /* typeSymbol */])(infoB.unit, indexB) === "F" /* F */)
        return;
    return 6 /* Hydrophobic */;
}
//
var HydrophobicAtomProvider = features_Features.Provider([8 /* HydrophobicAtom */], addHydrophobicAtom);
var HydrophobicProvider = {
    name: 'hydrophobic',
    params: HydrophobicParams,
    createTester: function (props) {
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([8 /* HydrophobicAtom */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testHydrophobic(structure, infoA, infoB, distanceSq); }
        };
    }
};
//# sourceMappingURL=hydrophobic.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var mol_util_set = __webpack_require__(90);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/metal.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */





var MetalCoordinationParams = {
    distanceMax: param_definition["ParamDefinition"].Numeric(3.0, { min: 1, max: 5, step: 0.1 }),
};
var IonicTypeMetals = [
    "LI" /* LI */, "NA" /* NA */, "K" /* K */, "RB" /* RB */, "CS" /* CS */,
    "MG" /* MG */, "CA" /* CA */, "SR" /* SR */, "BA" /* BA */, "AL" /* AL */,
    "GA" /* GA */, "IN" /* IN */, "TL" /* TL */, "SC" /* SC */, "SN" /* SN */,
    "PB" /* PB */, "BI" /* BI */, "SB" /* SB */, "HG" /* HG */
];
function addMetal(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    for (var i = 0, il = elements.length; i < il; ++i) {
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        var type = 0 /* None */;
        if (IonicTypeMetals.includes(element)) {
            type = 13 /* IonicTypeMetal */;
        }
        else if (Object(atomic_types["d" /* isTransitionMetal */])(element) || element === "ZN" /* ZN */ || element === "CD" /* CD */) {
            type = 12 /* TransitionMetal */;
        }
        if (type) {
            builder.add(type, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    }
}
function isProteinSidechain(atomname) {
    return !model_types["ProteinBackboneAtoms"].has(atomname);
}
function isProteinBackbone(atomname) {
    return model_types["ProteinBackboneAtoms"].has(atomname);
}
function isNucleicBackbone(atomname) {
    return model_types["NucleicBackboneAtoms"].has(atomname);
}
/**
 * Metal binding partners (dative bond or ionic-type interaction)
 */
function addMetalBinding(structure, unit, builder) {
    var elements = unit.elements;
    var _a = unit.model.atomicConformation, x = _a.x, y = _a.y, z = _a.z;
    for (var i = 0, il = elements.length; i < il; ++i) {
        var element = Object(chemistry_util["i" /* typeSymbol */])(unit, i);
        var resname = Object(chemistry_util["e" /* compId */])(unit, i);
        var atomname = Object(chemistry_util["b" /* atomId */])(unit, i);
        var dative = false;
        var ionic = false;
        var isStandardAminoacid = model_types["AminoAcidNames"].has(resname);
        var isStandardBase = model_types["BaseNames"].has(resname);
        if (!isStandardAminoacid && !isStandardBase) {
            if (Object(atomic_types["b" /* isHalogen */])(element) || element === "O" /* O */ || element === "S" /* S */) {
                dative = true;
                ionic = true;
            }
            else if (element === "N" /* N */) {
                dative = true;
            }
        }
        else if (isStandardAminoacid) {
            // main chain oxygen atom or oxygen, nitrogen and sulfur from specific amino acids
            if (element === "O" /* O */) {
                if (['ASP', 'GLU', 'SER', 'THR', 'TYR', 'ASN', 'GLN'].includes(resname) && isProteinSidechain(atomname)) {
                    dative = true;
                    ionic = true;
                }
                else if (isProteinBackbone(atomname)) {
                    dative = true;
                    ionic = true;
                }
            }
            else if (element === "S" /* S */ && (resname === 'CYS' || resname === 'MET')) {
                dative = true;
                ionic = true;
            }
            else if (element === "N" /* N */) {
                if (resname === 'HIS' && isProteinSidechain(atomname)) {
                    dative = true;
                }
            }
        }
        else if (isStandardBase) {
            // http://pubs.acs.org/doi/pdf/10.1021/acs.accounts.6b00253
            // http://onlinelibrary.wiley.com/doi/10.1002/anie.200900399/full
            if (element === "O" /* O */ && isNucleicBackbone(atomname)) {
                dative = true;
                ionic = true;
            }
            else if (['N3', 'N4', 'N7'].includes(atomname)) {
                dative = true;
            }
            else if (['O2', 'O4', 'O6'].includes(atomname)) {
                dative = true;
                ionic = true;
            }
        }
        if (dative) {
            builder.add(11 /* DativeBondPartner */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
        if (ionic) {
            builder.add(10 /* IonicTypePartner */, 0 /* None */, x[elements[i]], y[elements[i]], z[elements[i]], i);
        }
    }
}
function isMetalCoordination(ti, tj) {
    if (ti === 12 /* TransitionMetal */) {
        return (tj === 11 /* DativeBondPartner */ ||
            tj === 12 /* TransitionMetal */);
    }
    else if (ti === 13 /* IonicTypeMetal */) {
        return (tj === 10 /* IonicTypePartner */);
    }
}
function testMetalCoordination(structure, infoA, infoB, distanceSq) {
    var typeA = infoA.types[infoA.feature];
    var typeB = infoB.types[infoB.feature];
    if (!isMetalCoordination(typeA, typeB) && !isMetalCoordination(typeB, typeA))
        return;
    return 7 /* MetalCoordination */;
}
//
var MetalProvider = features_Features.Provider([13 /* IonicTypeMetal */, 12 /* TransitionMetal */], addMetal);
var MetalBindingProvider = features_Features.Provider([10 /* IonicTypePartner */, 11 /* DativeBondPartner */], addMetalBinding);
var MetalCoordinationProvider = {
    name: 'metal-coordination',
    params: MetalCoordinationParams,
    createTester: function (props) {
        return {
            maxDistance: props.distanceMax,
            requiredFeatures: new Set([13 /* IonicTypeMetal */, 12 /* TransitionMetal */, 10 /* IonicTypePartner */, 11 /* DativeBondPartner */]),
            getType: function (structure, infoA, infoB, distanceSq) { return testMetalCoordination(structure, infoA, infoB, distanceSq); }
        };
    }
};
//# sourceMappingURL=metal.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/refine.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * based in part on NGL (https://github.com/arose/ngl)
 */


function refineInteractions(structure, interactions) {
    var contacts = interactions.contacts, unitsContacts = interactions.unitsContacts, unitsFeatures = interactions.unitsFeatures;
    var contactRefiners = [
        hydrophobicRefiner(structure, interactions),
        weakHydrogenBondsRefiner(structure, interactions),
        saltBridgeRefiner(structure, interactions),
        piStackingRefiner(structure, interactions),
        metalCoordinationRefiner(structure, interactions),
    ];
    for (var i = 0, il = contacts.edgeCount; i < il; ++i) {
        var e = contacts.edges[i];
        var infoA = features_Features.Info(structure, e.unitA, unitsFeatures.get(e.unitA.id));
        infoA.feature = e.indexA;
        var infoB = features_Features.Info(structure, e.unitB, unitsFeatures.get(e.unitB.id));
        infoB.feature = e.indexB;
        for (var _i = 0, contactRefiners_1 = contactRefiners; _i < contactRefiners_1.length; _i++) {
            var refiner = contactRefiners_1[_i];
            if (refiner.isApplicable(e.props.type))
                refiner.handleInterContact(i, infoA, infoB);
        }
    }
    //
    var ucKeys = unitsContacts.keys();
    while (true) {
        var _a = ucKeys.next(), done = _a.done, value = _a.value;
        if (done)
            break;
        var contacts_1 = unitsContacts.get(value);
        var features = unitsFeatures.get(value);
        var unit = structure.unitMap.get(value);
        if (!mol_model_structure["Unit"].isAtomic(unit))
            continue;
        var infoA = features_Features.Info(structure, unit, features);
        var infoB = features_Features.Info(structure, unit, features);
        for (var _b = 0, contactRefiners_2 = contactRefiners; _b < contactRefiners_2.length; _b++) {
            var refiner = contactRefiners_2[_b];
            refiner.startUnit(unit, contacts_1, features);
        }
        for (var i = 0, il = contacts_1.edgeCount * 2; i < il; ++i) {
            infoA.feature = contacts_1.a[i];
            infoB.feature = contacts_1.b[i];
            // console.log(i, contacts.a[i], contacts.b[i])
            for (var _c = 0, contactRefiners_3 = contactRefiners; _c < contactRefiners_3.length; _c++) {
                var refiner = contactRefiners_3[_c];
                if (refiner.isApplicable(contacts_1.edgeProps.type[i]))
                    refiner.handleIntraContact(i, infoA, infoB);
            }
        }
    }
}
/**
 * For atoms interacting with several atoms in the same residue
 * only the one with the closest distance is kept.
 */
function hydrophobicRefiner(structure, interactions) {
    var contacts = interactions.contacts;
    /* keep only closest contact between residues */
    var handleResidueContact = function (dist, edge, key, map, set) {
        var _a = map.get(key) || [Infinity, -1], minDist = _a[0], minIndex = _a[1];
        if (dist < minDist) {
            if (minIndex !== -1)
                set(minIndex);
            map.set(key, [dist, edge]);
        }
        else {
            set(edge);
        }
    };
    function handleEdge(edge, infoA, infoB, map, set) {
        var elementA = infoA.members[infoA.offsets[infoA.feature]];
        var elementB = infoB.members[infoB.offsets[infoB.feature]];
        var residueA = infoA.unit.getResidueIndex(elementA);
        var residueB = infoB.unit.getResidueIndex(elementB);
        var keyA = elementA + "|" + infoA.unit.id + "|" + residueB + "|" + infoB.unit.id + "|A";
        var keyB = elementB + "|" + infoB.unit.id + "|" + residueA + "|" + infoA.unit.id + "|B";
        var dist = features_Features.distance(infoA, infoB);
        handleResidueContact(dist, edge, keyA, map, set);
        handleResidueContact(dist, edge, keyB, map, set);
    }
    var residueInterMap = new Map();
    var setInterFiltered = function (i) { return contacts.edges[i].props.flag = 1 /* Filtered */; };
    var residueIntraMap;
    var setIntraFiltered;
    return {
        isApplicable: function (type) { return type === 6 /* Hydrophobic */; },
        handleInterContact: function (index, infoA, infoB) {
            handleEdge(index, infoA, infoB, residueInterMap, setInterFiltered);
        },
        startUnit: function (unit, contacts, features) {
            residueIntraMap = new Map();
            setIntraFiltered = function (i) { return contacts.edgeProps.flag[i] = 1 /* Filtered */; };
        },
        handleIntraContact: function (index, infoA, infoB) {
            handleEdge(index, infoA, infoB, residueIntraMap, setIntraFiltered);
        }
    };
}
/**
 * Remove weak hydrogen bonds when the acceptor is involved in
 * a normal/strong hydrogen bond
 */
function weakHydrogenBondsRefiner(structure, interactions) {
    var contacts = interactions.contacts;
    var hasHydrogenBond = function (infoA, infoB) {
        var acc = infoA.types[infoA.feature] === 9 /* WeakHydrogenDonor */ ? infoB : infoA;
        // check intra
        var eI = acc.members[acc.offsets[acc.feature]];
        var _a = interactions.unitsContacts.get(acc.unit.id), type = _a.edgeProps.type, _b = _a.elementsIndex, offsets = _b.offsets, indices = _b.indices;
        for (var i = offsets[eI], il = offsets[eI + 1]; i < il; ++i) {
            if (type[indices[i]] === 4 /* HydrogenBond */)
                return true;
        }
        // check inter
        var interIndices = contacts.getEdgeIndices(acc.feature, acc.unit);
        for (var i = 0, il = interIndices.length; i < il; ++i) {
            if (contacts.edges[interIndices[i]].props.type === 4 /* HydrogenBond */)
                return true;
        }
        return false;
    };
    return {
        isApplicable: function (type) { return type === 8 /* WeakHydrogenBond */; },
        handleInterContact: function (index, infoA, infoB) {
            if (hasHydrogenBond(infoA, infoB)) {
                contacts.edges[index].props.flag = 1 /* Filtered */;
            }
        },
        startUnit: function () { },
        handleIntraContact: function (index, infoA, infoB) {
            if (hasHydrogenBond(infoA, infoB)) {
                var flag = interactions.unitsContacts.get(infoA.unit.id).edgeProps.flag;
                flag[index] = 1 /* Filtered */;
            }
        }
    };
}
/**
 * Filter inter-unit contact `index` if there is a contact of `types` between its members
 */
function filterInter(types, index, infoA, infoB, contacts) {
    var offsetsA = infoA.offsets, featureA = infoA.feature;
    var offsetsB = infoB.offsets, featureB = infoB.feature;
    for (var i = offsetsA[featureA], il = offsetsA[featureA + 1]; i < il; ++i) {
        var aI = infoA.members[i];
        var indices = contacts.getContactIndicesForElement(aI, infoA.unit);
        for (var k = 0, kl = indices.length; k < kl; ++k) {
            var cI = indices[k];
            if (types.includes(contacts.edges[cI].props.type)) {
                for (var j = offsetsB[featureB], jl = offsetsB[featureB + 1]; j < jl; ++j) {
                    var bI = infoB.members[j];
                    if (contacts.getContactIndicesForElement(bI, infoB.unit).includes(cI)) {
                        contacts.edges[index].props.flag = 1 /* Filtered */;
                        return;
                    }
                }
            }
        }
    }
}
/**
 * Filter intra-unit contact `index` if there is a contact of `types` between its members
 */
function filterIntra(types, index, infoA, infoB, contacts) {
    var _a = contacts.edgeProps, type = _a.type, flag = _a.flag, _b = contacts.elementsIndex, offsets = _b.offsets, indices = _b.indices;
    var offsetsA = infoA.offsets, featureA = infoA.feature;
    var offsetsB = infoB.offsets, featureB = infoB.feature;
    for (var i = offsetsA[featureA], il = offsetsA[featureA + 1]; i < il; ++i) {
        var aI = infoA.members[i];
        for (var k = offsets[aI], kl = offsets[aI + 1]; k < kl; ++k) {
            var cI = indices[k];
            if (types.includes(type[cI])) {
                for (var j = offsetsB[featureB], jl = offsetsB[featureB + 1]; j < jl; ++j) {
                    var bI = infoB.members[j];
                    for (var l = offsets[bI], ll = offsets[bI + 1]; l < ll; ++l) {
                        if (cI === indices[l]) {
                            flag[index] = 1 /* Filtered */;
                            return;
                        }
                    }
                }
            }
        }
    }
}
/**
 * Remove hydrogen bonds (normal and weak) between groups that also form
 * an ionic interaction between each other
 */
function saltBridgeRefiner(structure, interactions) {
    var contacts = interactions.contacts;
    return {
        isApplicable: function (type) { return type === 1 /* Ionic */; },
        handleInterContact: function (index, infoA, infoB) {
            filterInter([4 /* HydrogenBond */, 8 /* WeakHydrogenBond */], index, infoA, infoB, contacts);
        },
        startUnit: function () { },
        handleIntraContact: function (index, infoA, infoB) {
            filterIntra([4 /* HydrogenBond */, 8 /* WeakHydrogenBond */], index, infoA, infoB, interactions.unitsContacts.get(infoA.unit.id));
        }
    };
}
/**
 * Remove hydrophobic and cation-pi interactions between groups that also form
 * a pi-stacking interaction between each other
 */
function piStackingRefiner(structure, interactions) {
    var contacts = interactions.contacts;
    return {
        isApplicable: function (type) { return type === 6 /* Hydrophobic */ || type === 2 /* CationPi */; },
        handleInterContact: function (index, infoA, infoB) {
            filterInter([3 /* PiStacking */], index, infoA, infoB, contacts);
        },
        startUnit: function () { },
        handleIntraContact: function (index, infoA, infoB) {
            filterIntra([3 /* PiStacking */], index, infoA, infoB, interactions.unitsContacts.get(infoA.unit.id));
        }
    };
}
/**
 * Remove ionic interactions between groups that also form
 * a metal coordination between each other
 */
function metalCoordinationRefiner(structure, interactions) {
    var contacts = interactions.contacts;
    return {
        isApplicable: function (type) { return type === 1 /* Ionic */; },
        handleInterContact: function (index, infoA, infoB) {
            filterInter([7 /* MetalCoordination */], index, infoA, infoB, contacts);
        },
        startUnit: function () { },
        handleIntraContact: function (index, infoA, infoB) {
            filterIntra([7 /* MetalCoordination */], index, infoA, infoB, interactions.unitsContacts.get(infoA.unit.id));
        }
    };
}
//# sourceMappingURL=refine.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/location.js
var mol_model_location = __webpack_require__(144);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/centroid-helper.js
var centroid_helper = __webpack_require__(195);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var label = __webpack_require__(72);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/type-helpers.js
var type_helpers = __webpack_require__(283);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/interactions.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






















var interactions_Interactions;
(function (Interactions) {
    function Location(interactions, structure, unitA, indexA, unitB, indexB) {
        return Object(mol_model_location["a" /* DataLocation */])('interactions', { structure: structure, interactions: interactions }, { unitA: unitA, indexA: indexA, unitB: unitB, indexB: indexB });
    }
    Interactions.Location = Location;
    function isLocation(x) {
        return !!x && x.kind === 'data-location' && x.tag === 'interactions';
    }
    Interactions.isLocation = isLocation;
    function areLocationsEqual(locA, locB) {
        return (locA.data.structure === locB.data.structure &&
            locA.data.interactions === locB.data.interactions &&
            locA.element.indexA === locB.element.indexA &&
            locA.element.indexB === locB.element.indexB &&
            locA.element.unitA === locB.element.unitA &&
            locA.element.unitB === locB.element.unitB);
    }
    Interactions.areLocationsEqual = areLocationsEqual;
    function _label(interactions, element) {
        var unitA = element.unitA, indexA = element.indexA, unitB = element.unitB, indexB = element.indexB;
        var contacts = interactions.contacts, unitsContacts = interactions.unitsContacts;
        if (unitA === unitB) {
            var contacts_1 = unitsContacts.get(unitA.id);
            var idx = contacts_1.getDirectedEdgeIndex(indexA, indexB);
            return Object(common["e" /* interactionTypeLabel */])(contacts_1.edgeProps.type[idx]);
        }
        else {
            var idx = contacts.getEdgeIndex(indexA, unitA, indexB, unitB);
            return Object(common["e" /* interactionTypeLabel */])(contacts.edges[idx].props.type);
        }
    }
    function locationLabel(location) {
        return _label(location.data.interactions, location.element);
    }
    Interactions.locationLabel = locationLabel;
    function Loci(structure, interactions, elements) {
        return Object(loci["DataLoci"])('interactions', { structure: structure, interactions: interactions }, elements, function (boundingSphere) { return getBoundingSphere(interactions, elements, boundingSphere); }, function () { return getLabel(structure, interactions, elements); });
    }
    Interactions.Loci = Loci;
    function isLoci(x) {
        return !!x && x.kind === 'data-loci' && x.tag === 'interactions';
    }
    Interactions.isLoci = isLoci;
    function getBoundingSphere(interactions, elements, boundingSphere) {
        var unitsFeatures = interactions.unitsFeatures;
        return centroid_helper["a" /* CentroidHelper */].fromPairProvider(elements.length, function (i, pA, pB) {
            var e = elements[i];
            features_Features.setPosition(pA, e.unitA, e.indexA, unitsFeatures.get(e.unitA.id));
            features_Features.setPosition(pB, e.unitB, e.indexB, unitsFeatures.get(e.unitB.id));
        }, boundingSphere);
    }
    Interactions.getBoundingSphere = getBoundingSphere;
    function getLabel(structure, interactions, elements) {
        var element = elements[0];
        if (element === undefined)
            return '';
        var unitA = element.unitA, indexA = element.indexA, unitB = element.unitB, indexB = element.indexB;
        var unitsFeatures = interactions.unitsFeatures;
        var _a = unitsFeatures.get(unitA.id), mA = _a.members, oA = _a.offsets;
        var _b = unitsFeatures.get(unitB.id), mB = _b.members, oB = _b.offsets;
        var options = { granularity: 'element' };
        if (oA[indexA + 1] - oA[indexA] > 1 || oB[indexB + 1] - oB[indexB] > 1) {
            options.granularity = 'residue';
        }
        return [
            _label(interactions, element),
            Object(label["bondLabel"])(mol_model_structure["Bond"].Location(structure, unitA, mA[oA[indexA]], structure, unitB, mB[oB[indexB]]), options)
        ].join('</br>');
    }
    Interactions.getLabel = getLabel;
})(interactions_Interactions || (interactions_Interactions = {}));
var FeatureProviders = [
    HydrogenDonorProvider, WeakHydrogenDonorProvider, HydrogenAcceptorProvider,
    NegativChargeProvider, PositiveChargeProvider, AromaticRingProvider,
    HalogenDonorProvider, HalogenAcceptorProvider,
    HydrophobicAtomProvider,
    MetalProvider, MetalBindingProvider,
];
var ContactProviders = {
    'ionic': IonicProvider,
    'pi-stacking': PiStackingProvider,
    'cation-pi': CationPiProvider,
    'halogen-bonds': HalogenBondsProvider,
    'hydrogen-bonds': HydrogenBondsProvider,
    'weak-hydrogen-bonds': WeakHydrogenBondsProvider,
    'hydrophobic': HydrophobicProvider,
    'metal-coordination': MetalCoordinationProvider,
};
function getProvidersParams(defaultOn) {
    if (defaultOn === void 0) { defaultOn = []; }
    var params = Object.create(null);
    Object.keys(ContactProviders).forEach(function (k) {
        params[k] = param_definition["ParamDefinition"].MappedStatic(defaultOn.includes(k) ? 'on' : 'off', {
            on: param_definition["ParamDefinition"].Group(ContactProviders[k].params),
            off: param_definition["ParamDefinition"].Group({})
        }, { cycle: true });
    });
    return params;
}
var ContactProviderParams = getProvidersParams([
    // 'ionic',
    'cation-pi',
    'pi-stacking',
    'hydrogen-bonds',
    'halogen-bonds',
    // 'hydrophobic',
    'metal-coordination',
]);
var InteractionsParams = {
    providers: param_definition["ParamDefinition"].Group(ContactProviderParams, { isFlat: true }),
    contacts: param_definition["ParamDefinition"].Group(ContactsParams, { label: 'Advanced Options' }),
};
function computeInteractions(ctx, structure, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var p, contactTesters, requiredFeatures, featureProviders, unitsFeatures, unitsContacts, i, il, group, features, intraUnitContacts, j, jl, u, contacts, interactions;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(InteractionsParams)), props);
                    return [4 /*yield*/, valence_model["a" /* ValenceModelProvider */].attach(ctx, structure)];
                case 1:
                    _a.sent();
                    contactTesters = [];
                    Object(type_helpers["a" /* ObjectKeys */])(ContactProviders).forEach(function (k) {
                        var _a = p.providers[k], name = _a.name, params = _a.params;
                        if (name === 'on') {
                            contactTesters.push(ContactProviders[k].createTester(params));
                        }
                    });
                    requiredFeatures = new Set();
                    contactTesters.forEach(function (l) { return mol_util_set["a" /* SetUtils */].add(requiredFeatures, l.requiredFeatures); });
                    featureProviders = FeatureProviders.filter(function (f) { return mol_util_set["a" /* SetUtils */].areIntersecting(requiredFeatures, f.types); });
                    unitsFeatures = mol_data_int["IntMap"].Mutable();
                    unitsContacts = mol_data_int["IntMap"].Mutable();
                    i = 0, il = structure.unitSymmetryGroups.length;
                    _a.label = 2;
                case 2:
                    if (!(i < il)) return [3 /*break*/, 6];
                    group = structure.unitSymmetryGroups[i];
                    if (!ctx.runtime.shouldUpdate) return [3 /*break*/, 4];
                    return [4 /*yield*/, ctx.runtime.update({ message: 'computing interactions', current: i, max: il })];
                case 3:
                    _a.sent();
                    _a.label = 4;
                case 4:
                    features = findUnitFeatures(structure, group.units[0], featureProviders);
                    intraUnitContacts = findIntraUnitContacts(structure, group.units[0], features, contactTesters, p.contacts);
                    for (j = 0, jl = group.units.length; j < jl; ++j) {
                        u = group.units[j];
                        unitsFeatures.set(u.id, features);
                        unitsContacts.set(u.id, intraUnitContacts);
                    }
                    _a.label = 5;
                case 5:
                    ++i;
                    return [3 /*break*/, 2];
                case 6:
                    contacts = findInterUnitContacts(structure, unitsFeatures, contactTesters, p.contacts);
                    interactions = { unitsFeatures: unitsFeatures, unitsContacts: unitsContacts, contacts: contacts };
                    refineInteractions(structure, interactions);
                    return [2 /*return*/, interactions];
            }
        });
    });
}
function findUnitFeatures(structure, unit, featureProviders) {
    var count = unit.elements.length;
    var featuresBuilder = features_FeaturesBuilder.create(count, count / 2);
    if (mol_model_structure["Unit"].isAtomic(unit)) {
        for (var _i = 0, featureProviders_1 = featureProviders; _i < featureProviders_1.length; _i++) {
            var fp = featureProviders_1[_i];
            fp.add(structure, unit, featuresBuilder);
        }
    }
    return featuresBuilder.getFeatures(count);
}
function findIntraUnitContacts(structure, unit, features, contactTesters, props) {
    var builder = contacts_builder_IntraContactsBuilder.create(features, unit.elements.length);
    if (mol_model_structure["Unit"].isAtomic(unit)) {
        addUnitContacts(structure, unit, features, builder, contactTesters, props);
    }
    return builder.getContacts();
}
function findInterUnitContacts(structure, unitsFeatures, contactTesters, props) {
    var builder = contacts_builder_InterContactsBuilder.create();
    mol_model_structure["Structure"].eachUnitPair(structure, function (unitA, unitB) {
        var featuresA = unitsFeatures.get(unitA.id);
        var featuresB = unitsFeatures.get(unitB.id);
        addStructureContacts(structure, unitA, featuresA, unitB, featuresB, builder, contactTesters, props);
    }, {
        maxRadius: Math.max.apply(Math, contactTesters.map(function (t) { return t.maxDistance; })),
        validUnit: function (unit) { return mol_model_structure["Unit"].isAtomic(unit); },
        validUnitPair: function (unitA, unitB) { return mol_model_structure["Structure"].validUnitPair(structure, unitA, unitB); }
    });
    return builder.getContacts(unitsFeatures);
}
//# sourceMappingURL=interactions.js.map

/***/ }),
/* 201 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ rings_UnitRing; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ rings_UnitRings; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/graph.js + 1 modules
var mol_math_graph = __webpack_require__(171);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/rings/compute.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function computeRings(unit) {
    var size = largestResidue(unit);
    var state = State(unit, size);
    var residuesIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements);
    while (residuesIt.hasNext) {
        var seg = residuesIt.move();
        processResidue(state, seg.start, seg.end);
    }
    return state.rings;
}
function State(unit, capacity) {
    return {
        startVertex: 0,
        endVertex: 0,
        count: 0,
        visited: new Int32Array(capacity),
        queue: new Int32Array(capacity),
        pred: new Int32Array(capacity),
        left: new Int32Array(4 /* MaxDepth */),
        right: new Int32Array(4 /* MaxDepth */),
        color: new Int32Array(capacity),
        currentColor: 0,
        currentAltLoc: '',
        hasAltLoc: false,
        rings: [],
        currentRings: [],
        unit: unit,
        bonds: unit.bonds,
        altLoc: unit.model.atomicHierarchy.atoms.label_alt_id
    };
}
function resetState(state) {
    state.count = state.endVertex - state.startVertex;
    var visited = state.visited, pred = state.pred, color = state.color;
    for (var i = 0; i < state.count; i++) {
        visited[i] = -1;
        pred[i] = -1;
        color[i] = 0;
    }
    state.currentColor = 0;
    state.currentAltLoc = '';
    state.hasAltLoc = false;
}
function largestResidue(unit) {
    var residuesIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements);
    var size = 0;
    while (residuesIt.hasNext) {
        var seg = residuesIt.move();
        size = Math.max(size, seg.end - seg.start);
    }
    return size;
}
function processResidue(state, start, end) {
    var visited = state.visited;
    state.startVertex = start;
    state.endVertex = end;
    // no two atom rings
    if (state.endVertex - state.startVertex < 3)
        return;
    state.currentRings = [];
    var elements = state.unit.elements;
    var altLocs = [];
    for (var i = state.startVertex; i < state.endVertex; i++) {
        var altLoc = state.altLoc.value(elements[i]);
        Object(array["arraySetAdd"])(altLocs, altLoc);
    }
    Object(array["arraySetRemove"])(altLocs, '');
    if (altLocs.length === 0) {
        resetState(state);
        for (var i = 0; i < state.count; i++) {
            if (visited[i] >= 0)
                continue;
            findRings(state, i);
        }
    }
    else {
        for (var aI = 0; aI < altLocs.length; aI++) {
            resetState(state);
            state.hasAltLoc = true;
            state.currentAltLoc = altLocs[aI];
            for (var i = 0; i < state.count; i++) {
                if (visited[i] >= 0)
                    continue;
                var altLoc = state.altLoc.value(elements[state.startVertex + i]);
                if (altLoc && altLoc !== state.currentAltLoc) {
                    continue;
                }
                findRings(state, i);
            }
        }
    }
    for (var i = 0, _i = state.currentRings.length; i < _i; i++) {
        state.rings.push(state.currentRings[i]);
    }
}
function addRing(state, a, b) {
    // only "monotonous" rings
    if (b < a) {
        return;
    }
    var pred = state.pred, color = state.color, left = state.left, right = state.right;
    var nc = ++state.currentColor;
    var current = a;
    for (var t = 0; t < 4 /* MaxDepth */; t++) {
        color[current] = nc;
        current = pred[current];
        if (current < 0)
            break;
    }
    var leftOffset = 0, rightOffset = 0;
    var found = false, target = 0;
    current = b;
    for (var t = 0; t < 4 /* MaxDepth */; t++) {
        if (color[current] === nc) {
            target = current;
            found = true;
            break;
        }
        right[rightOffset++] = current;
        current = pred[current];
        if (current < 0)
            break;
    }
    if (!found) {
        return;
    }
    current = a;
    for (var t = 0; t < 4 /* MaxDepth */; t++) {
        left[leftOffset++] = current;
        if (target === current)
            break;
        current = pred[current];
        if (current < 0)
            break;
    }
    var len = leftOffset + rightOffset;
    // rings must have at least three elements
    if (len < 3) {
        return;
    }
    var ring = new Int32Array(len);
    var ringOffset = 0;
    for (var t = 0; t < leftOffset; t++)
        ring[ringOffset++] = state.startVertex + left[t];
    for (var t = rightOffset - 1; t >= 0; t--)
        ring[ringOffset++] = state.startVertex + right[t];
    Object(util["q" /* sortArray */])(ring);
    if (state.hasAltLoc) {
        // we need to check if the ring was already added because alt locs are present.
        for (var rI = 0, _rI = state.currentRings.length; rI < _rI; rI++) {
            var r = state.currentRings[rI];
            if (ring[0] !== r[0])
                continue;
            if (ring.length !== r.length)
                continue;
            var areSame = true;
            for (var aI = 0, _aI = ring.length; aI < _aI; aI++) {
                if (ring[aI] !== r[aI]) {
                    areSame = false;
                    break;
                }
            }
            if (areSame) {
                return;
            }
        }
    }
    state.currentRings.push(mol_data_int["SortedArray"].ofSortedArray(ring));
}
function findRings(state, from) {
    var bonds = state.bonds, startVertex = state.startVertex, endVertex = state.endVertex, visited = state.visited, queue = state.queue, pred = state.pred;
    var elements = state.unit.elements;
    var neighbor = bonds.b, bondFlags = bonds.edgeProps.flags, offset = bonds.offset;
    visited[from] = 1;
    queue[0] = from;
    var head = 0, size = 1;
    while (head < size) {
        var top_1 = queue[head++];
        var a = startVertex + top_1;
        var start = offset[a], end = offset[a + 1];
        for (var i = start; i < end; i++) {
            var b = neighbor[i];
            if (b < startVertex || b >= endVertex || !types["BondType"].isCovalent(bondFlags[i]))
                continue;
            if (state.hasAltLoc) {
                var altLoc = state.altLoc.value(elements[b]);
                if (altLoc && state.currentAltLoc !== altLoc) {
                    continue;
                }
            }
            var other = b - startVertex;
            if (visited[other] > 0) {
                if (pred[other] !== top_1 && pred[top_1] !== other) {
                    addRing(state, top_1, other);
                }
                continue;
            }
            visited[other] = 1;
            queue[size++] = other;
            pred[other] = top_1;
        }
    }
}
function getFingerprint(elements) {
    var len = elements.length;
    var reversed = new Array(len);
    for (var i = 0; i < len; i++)
        reversed[i] = elements[len - i - 1];
    var rotNormal = getMinimalRotation(elements);
    var rotReversed = getMinimalRotation(reversed);
    var isNormalSmaller = false;
    for (var i = 0; i < len; i++) {
        var u = elements[(i + rotNormal) % len], v = reversed[(i + rotReversed) % len];
        if (u !== v) {
            isNormalSmaller = u < v;
            break;
        }
    }
    if (isNormalSmaller)
        return buildFinderprint(elements, rotNormal);
    return buildFinderprint(reversed, rotReversed);
}
function getMinimalRotation(elements) {
    // adapted from http://en.wikipedia.org/wiki/Lexicographically_minimal_string_rotation
    var len = elements.length;
    var f = new Int32Array(len * 2);
    for (var i = 0; i < f.length; i++)
        f[i] = -1;
    var u = '', v = '', k = 0;
    for (var j = 1; j < f.length; j++) {
        var i = f[j - k - 1];
        while (i !== -1) {
            u = elements[j % len];
            v = elements[(k + i + 1) % len];
            if (u === v)
                break;
            if (u < v)
                k = j - i - 1;
            i = f[i];
        }
        if (i === -1) {
            u = elements[j % len];
            v = elements[(k + i + 1) % len];
            if (u !== v) {
                if (u < v)
                    k = j;
                f[j - k] = -1;
            }
            else
                f[j - k] = i + 1;
        }
        else
            f[j - k] = i + 1;
    }
    return k;
}
function buildFinderprint(elements, offset) {
    var len = elements.length;
    var ret = [];
    var i;
    for (i = 0; i < len - 1; i++) {
        ret.push(elements[(i + offset) % len]);
        ret.push('-');
    }
    ret.push(elements[(i + offset) % len]);
    return ret.join('');
}
function createIndex(rings, aromaticRings) {
    var elementRingIndices = new Map();
    var elementAromaticRingIndices = new Map();
    // for each ring atom, assign all rings that it is present in
    for (var rI = 0, _rI = rings.length; rI < _rI; rI++) {
        var r = rings[rI];
        for (var i = 0, _i = r.length; i < _i; i++) {
            var e = r[i];
            if (elementRingIndices.has(e))
                elementRingIndices.get(e).push(rI);
            else
                elementRingIndices.set(e, [rI]);
        }
    }
    // for each ring atom, assign all aromatic rings that it is present in
    for (var aI = 0, _aI = aromaticRings.length; aI < _aI; aI++) {
        var rI = aromaticRings[aI];
        var r = rings[rI];
        for (var i = 0, _i = r.length; i < _i; i++) {
            var e = r[i];
            if (elementAromaticRingIndices.has(e))
                elementAromaticRingIndices.get(e).push(rI);
            else
                elementAromaticRingIndices.set(e, [rI]);
        }
    }
    // create a graph where vertices are rings, edge if two rings share at least one atom
    var graph = new mol_math_graph["a" /* IntAdjacencyGraph */].UniqueEdgeBuilder(rings.length);
    for (var rI = 0, _rI = rings.length; rI < _rI; rI++) {
        var r = rings[rI];
        for (var i = 0, _i = r.length; i < _i; i++) {
            var e = r[i];
            var containedRings = elementRingIndices.get(e);
            if (containedRings.length === 1)
                continue;
            for (var j = 0, _j = containedRings.length; j < _j; j++) {
                var rJ = containedRings[j];
                if (rI >= rJ)
                    continue;
                graph.addEdge(rI, rJ);
            }
        }
    }
    var components = mol_math_graph["a" /* IntAdjacencyGraph */].connectedComponents(graph.getGraph());
    var ringComponentIndex = components.componentIndex;
    var ringComponents = [];
    for (var i = 0; i < components.componentCount; i++)
        ringComponents[i] = [];
    for (var rI = 0, _rI = rings.length; rI < _rI; rI++) {
        ringComponents[ringComponentIndex[rI]].push(rI);
    }
    return { elementRingIndices: elementRingIndices, elementAromaticRingIndices: elementAromaticRingIndices, ringComponentIndex: ringComponentIndex, ringComponents: ringComponents };
}
//# sourceMappingURL=compute.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/util.js
var structure_util = __webpack_require__(147);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/principal-axes.js + 1 modules
var principal_axes = __webpack_require__(227);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/rings.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var rings_UnitRings = /** @class */ (function () {
    function UnitRings(all, unit) {
        this.unit = unit;
        this.all = all;
    }
    Object.defineProperty(UnitRings.prototype, "index", {
        get: function () {
            if (this._index)
                return this._index;
            this._index = createIndex(this.all, this.aromaticRings);
            return this._index;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "byFingerprint", {
        get: function () {
            if (this._byFingerprint)
                return this._byFingerprint;
            this._byFingerprint = createByFingerprint(this.unit, this.all);
            return this._byFingerprint;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "elementRingIndices", {
        /** Maps atom index inside a Unit to ring indices (an atom can be part of more than one ring) */
        get: function () {
            return this.index.elementRingIndices;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "elementAromaticRingIndices", {
        get: function () {
            return this.index.elementAromaticRingIndices;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "ringComponentIndex", {
        /** Maps UnitRings.Index to index to ringComponents */
        get: function () {
            return this.index.ringComponentIndex;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "ringComponents", {
        get: function () {
            return this.index.ringComponents;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(UnitRings.prototype, "aromaticRings", {
        get: function () {
            if (this._aromaticRings)
                return this._aromaticRings;
            this._aromaticRings = getAromaticRings(this.unit, this.all);
            return this._aromaticRings;
        },
        enumerable: false,
        configurable: true
    });
    return UnitRings;
}());
var rings_UnitRing;
(function (UnitRing) {
    function fingerprint(unit, ring) {
        var elements = unit.elements;
        var type_symbol = unit.model.atomicHierarchy.atoms.type_symbol;
        var symbols = [];
        for (var i = 0, _i = ring.length; i < _i; i++)
            symbols[symbols.length] = type_symbol.value(elements[ring[i]]);
        return elementFingerprint(symbols);
    }
    UnitRing.fingerprint = fingerprint;
    function elementFingerprint(elements) {
        return getFingerprint(elements);
    }
    UnitRing.elementFingerprint = elementFingerprint;
    var AromaticRingElements = new Set([
        "B" /* B */, "C" /* C */, "N" /* N */, "O" /* O */,
        "SI" /* SI */, "P" /* P */, "S" /* S */,
        "GE" /* GE */, "AS" /* AS */,
        "SN" /* SN */, "SB" /* SB */,
        "BI" /* BI */
    ]);
    var AromaticRingPlanarityThreshold = 0.05;
    function isAromatic(unit, ring) {
        var elements = unit.elements, _a = unit.bonds, b = _a.b, offset = _a.offset, flags = _a.edgeProps.flags;
        var _b = unit.model.atomicHierarchy.atoms, type_symbol = _b.type_symbol, label_comp_id = _b.label_comp_id;
        // ignore Proline (can be flat because of bad geometry)
        if (label_comp_id.value(unit.elements[ring[0]]) === 'PRO')
            return false;
        var aromaticBondCount = 0;
        var hasAromaticRingElement = false;
        for (var i = 0, il = ring.length; i < il; ++i) {
            var aI = ring[i];
            if (!hasAromaticRingElement && AromaticRingElements.has(type_symbol.value(elements[aI]))) {
                hasAromaticRingElement = true;
            }
            for (var j = offset[aI], jl = offset[aI + 1]; j < jl; ++j) {
                // comes e.g. from `chem_comp_bond.pdbx_aromatic_flag`
                if (types["BondType"].is(16 /* Aromatic */, flags[j])) {
                    if (mol_data_int["SortedArray"].has(ring, b[j]))
                        aromaticBondCount += 1;
                }
            }
        }
        if (aromaticBondCount === 2 * ring.length)
            return true;
        if (!hasAromaticRingElement)
            return false;
        var ma = principal_axes["a" /* PrincipalAxes */].calculateMomentsAxes(Object(structure_util["c" /* getPositions */])(unit, ring));
        return linear_algebra["Vec3"].magnitude(ma.dirC) < AromaticRingPlanarityThreshold;
    }
    UnitRing.isAromatic = isAromatic;
    /** Get the alternate location of the 1st non '' alt loc atom. */
    function getAltId(unit, ring) {
        var label_alt_id = unit.model.atomicHierarchy.atoms.label_alt_id;
        var elements = unit.elements;
        for (var i = 0, il = ring.length; i < il; ++i) {
            var eI = elements[ring[i]];
            var altId = label_alt_id.value(eI);
            if (altId)
                return altId;
        }
        return '';
    }
    UnitRing.getAltId = getAltId;
})(rings_UnitRing || (rings_UnitRing = {}));
(function (UnitRings) {
    function create(unit) {
        var rings = computeRings(unit);
        return new UnitRings(rings, unit);
    }
    UnitRings.create = create;
    /** Creates a mapping ResidueIndex -> list or rings that are on that residue and have one of the specified fingerprints. */
    function byFingerprintAndResidue(rings, fingerprints) {
        var map = new Map();
        for (var fI = 0, _fI = fingerprints.length; fI < _fI; fI++) {
            var fp = fingerprints[fI];
            addSingleResidueRings(rings, fp, map);
        }
        return map;
    }
    UnitRings.byFingerprintAndResidue = byFingerprintAndResidue;
})(rings_UnitRings || (rings_UnitRings = {}));
function createByFingerprint(unit, rings) {
    var byFingerprint = new Map();
    var idx = 0;
    for (var rI = 0, _rI = rings.length; rI < _rI; rI++) {
        var r = rings[rI];
        var fp = rings_UnitRing.fingerprint(unit, r);
        if (byFingerprint.has(fp))
            byFingerprint.get(fp).push(idx);
        else
            byFingerprint.set(fp, [idx]);
        idx++;
    }
    return byFingerprint;
}
function ringResidueIdx(unit, ring) {
    var elements = unit.elements;
    var residueIndex = unit.model.atomicHierarchy.residueAtomSegments.index;
    var idx = residueIndex[elements[ring[0]]];
    for (var rI = 1, _rI = ring.length; rI < _rI; rI++) {
        if (idx !== residueIndex[elements[ring[rI]]])
            return -1;
    }
    return idx;
}
function addSingleResidueRings(rings, fp, map) {
    var byFp = rings.byFingerprint.get(fp);
    if (!byFp)
        return;
    for (var rI = 0, _rI = byFp.length; rI < _rI; rI++) {
        var r = byFp[rI];
        var idx = ringResidueIdx(rings.unit, rings.all[r]);
        if (idx >= 0) {
            if (map.has(idx))
                map.get(idx).push(r);
            else
                map.set(idx, [r]);
        }
    }
}
function getAromaticRings(unit, rings) {
    var aromaticRings = [];
    for (var i = 0, il = rings.length; i < il; ++i) {
        if (rings_UnitRing.isAromatic(unit, rings[i]))
            aromaticRings.push(i);
    }
    return aromaticRings;
}

//# sourceMappingURL=rings.js.map

/***/ }),
/* 202 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Types; });
/* unused harmony export TTargs */
/* unused harmony export SymbolList */
/* unused harmony export SymbolMap */
/* harmony import */ var _type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _symbol__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(18);
/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(42);
/**
 * Copyright (c) 2018 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var Types;
(function (Types) {
    Types.AnyVar = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any);
    Types.AnyValueVar = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any);
    Types.ConstrainedVar = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any, true);
    Types.Regex = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Core', 'Regex');
    Types.Set = function (t) { return _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Container('Core', 'Set', t || Types.AnyValueVar); };
    Types.List = function (t) { return _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Container('Core', 'List', t || Types.AnyVar); };
    Types.Fn = function (t, alias) { return _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Container('Core', 'Fn', t || Types.AnyVar, alias); };
    Types.Flags = function (t, alias) { return _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Container('Core', 'Flags', t, alias); };
    Types.BitFlags = Types.Flags(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'BitFlags');
})(Types || (Types = {}));
function unaryOp(type, description) {
    return Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(type) }), type, description);
}
function binOp(type, description) {
    return Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].List(type, { nonEmpty: true }), type, description);
}
function binRel(src, target, description) {
    return Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(src),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(src)
    }), target, description);
}
var TTargs = _symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
    0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num)
});
var XX = { test: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str) };
var t = 0;
t.test;
var type = {
    '@header': 'Types',
    bool: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Convert a value to boolean.'),
    num: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Convert a value to number.'),
    str: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, 'Convert a value to string.'),
    regex: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'Expression' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { isOptional: true, description: "Flags, e.g. 'i' for ignore case" })
    }), Types.Regex, 'Creates a regular expression from a string using the ECMAscript syntax.'),
    list: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].List(Types.AnyVar), Types.List()),
    set: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].List(Types.AnyValueVar), Types.Set()),
    bitflags: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num) }), Types.BitFlags, 'Interpret a number as bitflags.'),
    compositeKey: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].List(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue),
};
var logic = {
    '@header': 'Logic',
    not: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    and: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    or: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
};
var ctrl = {
    '@header': 'Control',
    eval: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Fn(Types.AnyVar)) }), Types.AnyVar, 'Evaluate a function.'),
    fn: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.AnyVar) }), Types.Fn(Types.AnyVar), 'Wrap an expression to a "lazy" function.'),
    if: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { description: 'Condition' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any), { description: 'If true' }),
        2: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('b', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any), { description: 'If false' })
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Union([_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('b', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any)])),
    assoc: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'Name' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any), { description: 'Value to assign' })
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any))
};
var rel = {
    '@header': 'Relational',
    eq: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    neq: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    lt: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    lte: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    gr: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    gre: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool),
    inRange: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'Value to test' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'Minimum value' }),
        2: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'Maximum value' })
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Check if the value of the 1st argument is >= 2nd and <= 3rd.'),
};
var math = {
    '@header': 'Math',
    add: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    sub: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    mult: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    div: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    pow: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    mod: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    min: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    max: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    floor: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    ceil: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    roundInt: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    abs: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    sqrt: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    cbrt: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    sin: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    cos: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    tan: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    asin: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    acos: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    atan: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    sinh: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    cosh: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    tanh: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    exp: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    log: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    log10: unaryOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    atan2: binRel(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num)
};
var str = {
    '@header': 'Strings',
    concat: binOp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
    match: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Regex), 1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool)
};
var list = {
    '@header': 'Lists',
    getAt: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.List()), 1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num) }), Types.AnyVar),
    equal: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.List()), 1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.List()) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool)
};
var set = {
    '@header': 'Sets',
    has: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Set(Types.ConstrainedVar)), 1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.ConstrainedVar) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Check if the the 1st argument includes the value of the 2nd.'),
    isSubset: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Set(Types.ConstrainedVar)), 1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Set(Types.ConstrainedVar)) }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Check if the the 1st argument is a subset of the 2nd.')
};
var flags = {
    '@header': 'Flags',
    hasAny: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Flags(Types.ConstrainedVar)),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Flags(Types.ConstrainedVar))
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Check if the the 1st argument has at least one of the 2nd one\'s flags.'),
    hasAll: Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Flags(Types.ConstrainedVar)),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_1__[/* Argument */ "a"])(Types.Flags(Types.ConstrainedVar))
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Check if the the 1st argument has all 2nd one\'s flags.'),
};
var table = {
    '@header': 'Language Primitives',
    type: type,
    logic: logic,
    ctrl: ctrl,
    rel: rel,
    math: math,
    str: str,
    list: list,
    set: set,
    flags: flags
};
Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* normalizeTable */ "a"])(table);
var SymbolList = Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[/* symbolList */ "c"])(table);
var SymbolMap = (function () {
    var map = Object.create(null);
    for (var _i = 0, SymbolList_1 = SymbolList; _i < SymbolList_1.length; _i++) {
        var s = SymbolList_1[_i];
        map[s.id] = s;
    }
    return map;
})();
/* harmony default export */ __webpack_exports__["b"] = (table);
//# sourceMappingURL=core.js.map

/***/ }),
/* 203 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return observable; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })();
//# sourceMappingURL=observable.js.map


/***/ }),
/* 204 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CustomStructureProperty; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var CustomStructureProperty;
(function (CustomStructureProperty) {
    function createProvider(builder) {
        var _this = this;
        var descriptorName = builder.descriptor.name;
        var propertyDataName = builder.type === 'root' ? 'inheritedPropertyData' : 'currentPropertyData';
        var get = function (data) {
            if (!(descriptorName in data[propertyDataName])) {
                data[propertyDataName][descriptorName] = {
                    props: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(builder.getParams(data))),
                    data: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueBox */ "d"].create(undefined)
                };
            }
            return data[propertyDataName][descriptorName];
        };
        var set = function (data, props, value) {
            var property = get(data);
            data[propertyDataName][descriptorName] = {
                props: props,
                data: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueBox */ "d"].withValue(property.data, value)
            };
        };
        return {
            label: builder.label,
            descriptor: builder.descriptor,
            isHidden: builder.isHidden,
            getParams: function (data) {
                var params = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].clone(builder.getParams(data));
                _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].setDefaultValues(params, get(data).props);
                return params;
            },
            defaultParams: builder.defaultParams,
            isApplicable: builder.isApplicable,
            attach: function (ctx, data, props, addRef) {
                if (props === void 0) { props = {}; }
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                    var rootProps, property, p, _a, value, assets;
                    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                if (addRef)
                                    data.customPropertyDescriptors.reference(builder.descriptor, true);
                                if (builder.type === 'root')
                                    data = data.root;
                                rootProps = get(data.root).props;
                                property = get(data);
                                p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].merge(builder.defaultParams, rootProps, props);
                                if (property.data.value && _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].areEqual(builder.defaultParams, property.props, p))
                                    return [2 /*return*/];
                                return [4 /*yield*/, builder.obtain(ctx, data, p)];
                            case 1:
                                _a = _b.sent(), value = _a.value, assets = _a.assets;
                                data.customPropertyDescriptors.add(builder.descriptor);
                                data.customPropertyDescriptors.assets(builder.descriptor, assets);
                                set(data, p, value);
                                return [2 /*return*/];
                        }
                    });
                });
            },
            ref: function (data, add) { return data.customPropertyDescriptors.reference(builder.descriptor, add); },
            get: function (data) { return get(data).data; },
            set: function (data, props, value) {
                if (props === void 0) { props = {}; }
                if (builder.type === 'root')
                    data = data.root;
                var property = get(data);
                var p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].merge(builder.defaultParams, property.props, props);
                if (!_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].areEqual(builder.defaultParams, property.props, p)) {
                    // this invalidates property.value
                    set(data, p, value);
                    // dispose of assets
                    data.customPropertyDescriptors.assets(builder.descriptor);
                }
            },
            props: function (data) { return get(data).props; },
        };
    }
    CustomStructureProperty.createProvider = createProvider;
    function createSimple(name, type, defaultValue) {
        var _this = this;
        var defaultParams = { value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Value(defaultValue, { isHidden: true }) };
        return createProvider({
            label: Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* stringToWords */ "d"])(name),
            descriptor: Object(_mol_model_custom_property__WEBPACK_IMPORTED_MODULE_3__["CustomPropertyDescriptor"])({ name: name }),
            isHidden: true,
            type: type,
            defaultParams: defaultParams,
            getParams: function () { return ({ value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Value(defaultValue, { isHidden: true }) }); },
            isApplicable: function () { return true; },
            obtain: function (ctx, data, props) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                    return [2 /*return*/, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(defaultParams)), props)];
                });
            }); }
        });
    }
    CustomStructureProperty.createSimple = createSimple;
})(CustomStructureProperty || (CustomStructureProperty = {}));
//# sourceMappingURL=custom-structure-property.js.map

/***/ }),
/* 205 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ __webpack_exports__["a"] = ("\nprecision highp float;\n\nattribute vec2 aPosition;\nuniform vec2 uQuadScale;\n\nvoid main(void) {\n    vec2 position = aPosition * uQuadScale - vec2(1.0, 1.0) + uQuadScale;\n    gl_Position = vec4(position, 0.0, 1.0);\n}\n");
//# sourceMappingURL=quad.vert.js.map

/***/ }),
/* 206 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleSelectionModeButton", function() { return ToggleSelectionModeButton; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureSelectionActionsControls", function() { return StructureSelectionActionsControls; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureSelectionStatsControls", function() { return StructureSelectionStatsControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mol_plugin_state_helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(80);
/* harmony import */ var _mol_plugin_state_manager_interactivity__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(370);
/* harmony import */ var _mol_plugin_state_manager_structure_component__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(246);
/* harmony import */ var _mol_util_memoize__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(155);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(41);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(32);
/* harmony import */ var _controls_action_menu__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(56);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(19);
/* harmony import */ var _controls_parameters__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(66);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(14);
/* harmony import */ var _components__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(322);
/* harmony import */ var _viewport_help__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(189);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */















var ToggleSelectionModeButton = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ToggleSelectionModeButton, _super);
    function ToggleSelectionModeButton() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._toggleSelMode = function () {
            _this.plugin.selectionMode = !_this.plugin.selectionMode;
        };
        return _this;
    }
    ToggleSelectionModeButton.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.layout.events.updated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.behaviors.interaction.selectionMode, function () { return _this.forceUpdate(); });
    };
    ToggleSelectionModeButton.prototype.render = function () {
        var style = this.props.inline
            ? { background: 'transparent', width: 'auto', height: 'auto', lineHeight: 'unset' }
            : { background: 'transparent' };
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SelectionModeSvg"], onClick: this._toggleSelMode, title: 'Toggle Selection Mode', style: style, toggleState: this.plugin.selectionMode });
    };
    return ToggleSelectionModeButton;
}(_base__WEBPACK_IMPORTED_MODULE_8__["PurePluginUIComponent"]));

var StructureSelectionParams = {
    granularity: _mol_plugin_state_manager_interactivity__WEBPACK_IMPORTED_MODULE_3__[/* InteractivityManager */ "a"].Params.granularity,
};
var ActionHeader = new Map([
    ['add', 'Add/Union Selection'],
    ['remove', 'Remove/Subtract Selection'],
    ['intersect', 'Intersect Selection'],
    ['set', 'Set Selection']
]);
var StructureSelectionActionsControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StructureSelectionActionsControls, _super);
    function StructureSelectionActionsControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            action: void 0,
            isEmpty: true,
            isBusy: false,
            canUndo: false,
        };
        _this.set = function (modifier, selectionQuery) {
            _this.plugin.managers.structure.selection.fromSelectionQuery(modifier, selectionQuery, false);
        };
        _this.selectQuery = function (item, e) {
            if (!item || !_this.state.action) {
                _this.setState({ action: void 0 });
                return;
            }
            var q = _this.state.action;
            if (e === null || e === void 0 ? void 0 : e.shiftKey) {
                _this.set(q, item.value);
            }
            else {
                _this.setState({ action: void 0 }, function () {
                    _this.set(q, item.value);
                });
            }
        };
        _this.queriesItems = [];
        _this.queriesVersion = -1;
        _this.toggleAdd = _this.showAction('add');
        _this.toggleRemove = _this.showAction('remove');
        _this.toggleIntersect = _this.showAction('intersect');
        _this.toggleSet = _this.showAction('set');
        _this.toggleTheme = _this.showAction('theme');
        _this.toggleAddComponent = _this.showAction('add-component');
        _this.toggleHelp = _this.showAction('help');
        _this.setGranuality = function (_a) {
            var value = _a.value;
            _this.plugin.managers.interactivity.setProps({ granularity: value });
        };
        _this.turnOff = function () { return _this.plugin.selectionMode = false; };
        _this.undo = function () {
            var task = _this.plugin.state.data.undo();
            if (task)
                _this.plugin.runTask(task);
        };
        _this.subtract = function () {
            var sel = _this.plugin.managers.structure.hierarchy.getStructuresWithSelection();
            var components = [];
            for (var _i = 0, sel_1 = sel; _i < sel_1.length; _i++) {
                var s = sel_1[_i];
                components.push.apply(components, s.components);
            }
            if (components.length === 0)
                return;
            _this.plugin.managers.structure.component.modifyByCurrentSelection(components, 'subtract');
        };
        return _this;
    }
    StructureSelectionActionsControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) {
            var isEmpty = c.hierarchy.structures.length === 0;
            if (_this.state.isEmpty !== isEmpty) {
                _this.setState({ isEmpty: isEmpty });
            }
            // trigger elementQueries and nonStandardResidueQueries recalculation
            _this.queriesVersion = -1;
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v, action: void 0 });
        });
        this.subscribe(this.plugin.managers.interactivity.events.propsUpdated, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.data.events.historyUpdated, function (_a) {
            var state = _a.state;
            _this.setState({ canUndo: state.canUndo });
        });
    };
    Object.defineProperty(StructureSelectionActionsControls.prototype, "isDisabled", {
        get: function () {
            return this.state.isBusy || this.state.isEmpty;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSelectionActionsControls.prototype, "structures", {
        get: function () {
            var _a;
            var structures = [];
            for (var _i = 0, _b = this.plugin.managers.structure.hierarchy.selection.structures; _i < _b.length; _i++) {
                var s = _b[_i];
                var structure = (_a = s.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
                if (structure)
                    structures.push(structure);
            }
            return structures;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSelectionActionsControls.prototype, "queries", {
        get: function () {
            var registry = this.plugin.query.structure.registry;
            if (registry.version !== this.queriesVersion) {
                var structures = this.structures;
                var queries = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(registry.list, Object(_mol_plugin_state_helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_2__[/* getPolymerAndBranchedEntityQueries */ "g"])(structures), Object(_mol_plugin_state_helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_2__[/* getNonStandardResidueQueries */ "f"])(structures), Object(_mol_plugin_state_helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_2__[/* getElementQueries */ "e"])(structures)).sort(function (a, b) { return b.priority - a.priority; });
                this.queriesItems = _controls_action_menu__WEBPACK_IMPORTED_MODULE_9__[/* ActionMenu */ "a"].createItems(queries, {
                    filter: function (q) { return q !== _mol_plugin_state_helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_2__[/* StructureSelectionQueries */ "b"].current && !q.isHidden; },
                    label: function (q) { return q.label; },
                    category: function (q) { return q.category; },
                    description: function (q) { return q.description; }
                });
                this.queriesVersion = registry.version;
            }
            return this.queriesItems;
        },
        enumerable: false,
        configurable: true
    });
    StructureSelectionActionsControls.prototype.showAction = function (q) {
        var _this = this;
        return function () { return _this.setState({ action: _this.state.action === q ? void 0 : q }); };
    };
    StructureSelectionActionsControls.prototype.render = function () {
        var granularity = this.plugin.managers.interactivity.props.granularity;
        var undoTitle = this.state.canUndo
            ? "Undo " + this.plugin.state.data.latestUndoLabel
            : 'Some mistakes of the past can be undone.';
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row', style: { background: 'none' } },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_11__["PureSelectControl"], { title: "Picking Level for selecting and highlighting", param: StructureSelectionParams.granularity, name: 'granularity', value: granularity, onChange: this.setGranuality, isDisabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["UnionSvg"], title: ActionHeader.get('add') + ". Hold shift key to keep menu open.", toggle: this.toggleAdd, isSelected: this.state.action === 'add', disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SubtractSvg"], title: ActionHeader.get('remove') + ". Hold shift key to keep menu open.", toggle: this.toggleRemove, isSelected: this.state.action === 'remove', disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["IntersectSvg"], title: ActionHeader.get('intersect') + ". Hold shift key to keep menu open.", toggle: this.toggleIntersect, isSelected: this.state.action === 'intersect', disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SetSvg"], title: ActionHeader.get('set') + ". Hold shift key to keep menu open.", toggle: this.toggleSet, isSelected: this.state.action === 'set', disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["BrushSvg"], title: 'Apply Theme to Selection', toggle: this.toggleTheme, isSelected: this.state.action === 'theme', disabled: this.isDisabled, style: { marginLeft: '10px' } }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CubeOutlineSvg"], title: 'Create Component of Selection with Representation', toggle: this.toggleAddComponent, isSelected: this.state.action === 'add-component', disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RemoveSvg"], title: 'Remove/subtract Selection from all Components', onClick: this.subtract, disabled: this.isDisabled }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RestoreSvg"], onClick: this.undo, disabled: !this.state.canUndo || this.isDisabled, title: undoTitle }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["HelpOutlineSvg"], title: 'Show/hide help', toggle: this.toggleHelp, style: { marginLeft: '10px' }, isSelected: this.state.action === 'help' }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CancelOutlinedSvg"], title: 'Turn selection mode off', onClick: this.turnOff })),
            (this.state.action && this.state.action !== 'theme' && this.state.action !== 'add-component' && this.state.action !== 'help') && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-selection-viewport-controls-actions' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_9__[/* ActionMenu */ "a"], { header: ActionHeader.get(this.state.action), title: 'Click to close.', items: this.queries, onSelect: this.selectQuery, noOffset: true })),
            this.state.action === 'theme' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-selection-viewport-controls-actions' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ControlGroup"], { header: 'Theme', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleTheme, topRightIcon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CloseSvg"] },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ApplyThemeControls, { onApply: this.toggleTheme }))),
            this.state.action === 'add-component' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-selection-viewport-controls-actions' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ControlGroup"], { header: 'Add Component', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleAddComponent, topRightIcon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CloseSvg"] },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_components__WEBPACK_IMPORTED_MODULE_13__["AddComponentControls"], { onApply: this.toggleAddComponent, forSelection: true }))),
            this.state.action === 'help' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-selection-viewport-controls-actions' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ControlGroup"], { header: 'Help', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleHelp, topRightIcon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CloseSvg"], maxHeight: '300px' },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_14__["HelpGroup"], { header: 'Selection Operations' },
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_14__["HelpText"], null,
                            "Use ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["UnionSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SubtractSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["IntersectSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SetSvg"], inline: true }),
                            " to modify the selection.")),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_14__["HelpGroup"], { header: 'Representation Operations' },
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_14__["HelpText"], null,
                            "Use ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["BrushSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CubeOutlineSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RemoveSvg"], inline: true }),
                            " ",
                            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RestoreSvg"], inline: true }),
                            " to color, create components, remove from components, or undo actions.")),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_14__["ViewportHelpContent"], { selectOnly: true }))));
    };
    return StructureSelectionActionsControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["PluginUIComponent"]));

var StructureSelectionStatsControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StructureSelectionStatsControls, _super);
    function StructureSelectionStatsControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isEmpty: true,
            isBusy: false
        };
        _this.clear = function () { return _this.plugin.managers.interactivity.lociSelects.deselectAll(); };
        _this.focus = function () {
            if (_this.plugin.managers.structure.selection.stats.elementCount === 0)
                return;
            var sphere = _this.plugin.managers.structure.selection.getBoundary().sphere;
            _this.plugin.managers.camera.focusSphere(sphere);
        };
        _this.highlight = function (e) {
            _this.plugin.managers.interactivity.lociHighlights.clearHighlights();
            _this.plugin.managers.structure.selection.entries.forEach(function (e) {
                _this.plugin.managers.interactivity.lociHighlights.highlight({ loci: e.selection }, false);
            });
        };
        _this.clearHighlight = function () {
            _this.plugin.managers.interactivity.lociHighlights.clearHighlights();
        };
        return _this;
    }
    StructureSelectionStatsControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.selection.events.changed, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) {
            var isEmpty = c.structures.length === 0;
            if (_this.state.isEmpty !== isEmpty) {
                _this.setState({ isEmpty: isEmpty });
            }
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(StructureSelectionStatsControls.prototype, "isDisabled", {
        get: function () {
            return this.state.isBusy || this.state.isEmpty;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSelectionStatsControls.prototype, "stats", {
        get: function () {
            var stats = this.plugin.managers.structure.selection.stats;
            if (stats.structureCount === 0 || stats.elementCount === 0) {
                return 'Nothing Selected';
            }
            else {
                return Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_7__[/* stripTags */ "e"])(stats.label) + " Selected";
            }
        },
        enumerable: false,
        configurable: true
    });
    StructureSelectionStatsControls.prototype.render = function () {
        var stats = this.plugin.managers.structure.selection.stats;
        var empty = stats.structureCount === 0 || stats.elementCount === 0;
        if (empty && this.props.hideOnEmpty)
            return null;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["Button"], { noOverflow: true, onClick: this.focus, title: 'Click to Focus Selection', disabled: empty, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight, style: { textAlignLast: !empty ? 'left' : void 0 } }, this.stats),
                !empty && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CancelOutlinedSvg"], onClick: this.clear, title: 'Clear', className: 'msp-form-control', flex: true })));
    };
    return StructureSelectionStatsControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["PluginUIComponent"]));

var ApplyThemeControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ApplyThemeControls, _super);
    function ApplyThemeControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._params = Object(_mol_util_memoize__WEBPACK_IMPORTED_MODULE_5__[/* memoizeLatest */ "b"])(function (pivot) { return _mol_plugin_state_manager_structure_component__WEBPACK_IMPORTED_MODULE_4__["StructureComponentManager"].getThemeParams(_this.plugin, pivot); });
        _this.state = { values: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].getDefaultValues(_this.params) };
        _this.apply = function () {
            var _a, _b;
            _this.plugin.managers.structure.component.applyTheme(_this.state.values, _this.plugin.managers.structure.hierarchy.current.structures);
            (_b = (_a = _this.props).onApply) === null || _b === void 0 ? void 0 : _b.call(_a);
        };
        _this.paramsChanged = function (values) { return _this.setState({ values: values }); };
        return _this;
    }
    Object.defineProperty(ApplyThemeControls.prototype, "params", {
        get: function () { return this._params(this.plugin.managers.structure.component.pivotStructure); },
        enumerable: false,
        configurable: true
    });
    ApplyThemeControls.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_11__["ParameterControls"], { params: this.params, values: this.state.values, onChangeValues: this.paramsChanged }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["Button"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["BrushSvg"], className: 'msp-btn-commit msp-btn-commit-on', onClick: this.apply, style: { marginTop: '1px' } }, "Apply Theme"));
    };
    return ApplyThemeControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["PurePluginUIComponent"]));
//# sourceMappingURL=selection.js.map

/***/ }),
/* 207 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var BitFlags;
(function (BitFlags) {
    function create(flags) { return flags; }
    BitFlags.create = create;
    function has(flags, flag) { return (flags & flag) !== 0; }
    BitFlags.has = has;
    /** toCheck must be non-zero */
    function hasAll(flags, toCheck) { return !!toCheck && (flags & toCheck) === toCheck; }
    BitFlags.hasAll = hasAll;
})(BitFlags || (BitFlags = {}));
/* harmony default export */ __webpack_exports__["a"] = (BitFlags);
//# sourceMappingURL=bit-flags.js.map

/***/ }),
/* 208 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ObjectUnsubscribedError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () {
    function ObjectUnsubscribedErrorImpl() {
        Error.call(this);
        this.message = 'object unsubscribed';
        this.name = 'ObjectUnsubscribedError';
        return this;
    }
    ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return ObjectUnsubscribedErrorImpl;
})();
var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl;
//# sourceMappingURL=ObjectUnsubscribedError.js.map


/***/ }),
/* 209 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TextBuilder; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _text__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(123);
/* harmony import */ var _font_atlas__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(381);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var quadIndices = new Uint16Array([
    0, 1, 2,
    1, 3, 2
]);
var TextBuilder;
(function (TextBuilder) {
    function create(props, initialCount, chunkSize, text) {
        if (props === void 0) { props = {}; }
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        initialCount *= 2;
        chunkSize *= 2;
        var centers = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Float32Array, 3, chunkSize, text ? text.centerBuffer.ref.value : initialCount);
        var mappings = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Float32Array, 2, chunkSize, text ? text.mappingBuffer.ref.value : initialCount);
        var depths = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Float32Array, 1, chunkSize, text ? text.depthBuffer.ref.value : initialCount);
        var indices = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Uint32Array, 3, chunkSize, text ? text.indexBuffer.ref.value : initialCount);
        var groups = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Float32Array, 1, chunkSize, text ? text.groupBuffer.ref.value : initialCount);
        var tcoords = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].create(Float32Array, 2, chunkSize, text ? text.tcoordBuffer.ref.value : initialCount);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(_text__WEBPACK_IMPORTED_MODULE_3__[/* Text */ "a"].Params)), props);
        var attachment = p.attachment, background = p.background, backgroundMargin = p.backgroundMargin, tether = p.tether, tetherLength = p.tetherLength, tetherBaseWidth = p.tetherBaseWidth;
        var fontAtlas = Object(_font_atlas__WEBPACK_IMPORTED_MODULE_4__[/* getFontAtlas */ "b"])(p);
        var margin = (1 / 2.5) * backgroundMargin;
        var outline = fontAtlas.buffer / fontAtlas.lineHeight;
        var add = function (x, y, z, depth, group) {
            _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(centers, x, y, z);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add(depths, depth);
            _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add(groups, group);
        };
        return {
            add: function (str, x, y, z, depth, scale, group) {
                var bWidth = 0;
                var nChar = str.length;
                // calculate width
                for (var iChar = 0; iChar < nChar; ++iChar) {
                    var c = fontAtlas.get(str[iChar]);
                    bWidth += c.nw - 2 * outline;
                }
                var bHeight = 1 / 1.25;
                // attachment
                var yShift, xShift;
                // vertical
                if (attachment.startsWith('top')) {
                    yShift = bHeight;
                }
                else if (attachment.startsWith('middle')) {
                    yShift = bHeight / 2;
                }
                else {
                    yShift = 0; // "bottom"
                }
                // horizontal
                if (attachment.endsWith('right')) {
                    xShift = bWidth;
                }
                else if (attachment.endsWith('center')) {
                    xShift = bWidth / 2;
                }
                else {
                    xShift = 0; // "left"
                }
                if (tether) {
                    switch (attachment) {
                        case 'bottom-left':
                            xShift -= tetherLength / 2 + margin + 0.1;
                            yShift -= tetherLength / 2 + margin;
                            break;
                        case 'bottom-center':
                            yShift -= tetherLength + margin;
                            break;
                        case 'bottom-right':
                            xShift += tetherLength / 2 + margin + 0.1;
                            yShift -= tetherLength / 2 + margin;
                            break;
                        case 'middle-left':
                            xShift -= tetherLength + margin + 0.1;
                            break;
                        case 'middle-center':
                            break;
                        case 'middle-right':
                            xShift += tetherLength + margin + 0.1;
                            break;
                        case 'top-left':
                            xShift -= tetherLength / 2 + margin + 0.1;
                            yShift += tetherLength / 2 + margin;
                            break;
                        case 'top-center':
                            yShift += tetherLength + margin;
                            break;
                        case 'top-right':
                            xShift += tetherLength / 2 + margin + 0.1;
                            yShift += tetherLength / 2 + margin;
                            break;
                    }
                }
                var xLeft = (-xShift - margin - 0.1) * scale;
                var xRight = (bWidth - xShift + margin + 0.1) * scale;
                var yTop = (bHeight - yShift + margin) * scale;
                var yBottom = (-yShift - margin) * scale;
                // background
                if (background) {
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xLeft, yTop); // top left
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xLeft, yBottom); // bottom left
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xRight, yTop); // top right
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xRight, yBottom); // bottom right
                    var offset = centers.elementCount;
                    for (var i = 0; i < 4; ++i) {
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, 10, 10);
                        add(x, y, z, depth, group);
                    }
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset + quadIndices[0], offset + quadIndices[1], offset + quadIndices[2]);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset + quadIndices[3], offset + quadIndices[4], offset + quadIndices[5]);
                }
                if (tether) {
                    var xTip = void 0, yTip = void 0;
                    var xBaseA = void 0, yBaseA = void 0;
                    var xBaseB = void 0, yBaseB = void 0;
                    var xBaseCenter = void 0, yBaseCenter = void 0;
                    var scaledTetherLength = tetherLength * scale;
                    var scaledTetherBaseWidth = tetherBaseWidth * scale;
                    switch (attachment) {
                        case 'bottom-left':
                            xTip = xLeft - scaledTetherLength / 2;
                            xBaseA = xLeft + scaledTetherBaseWidth / 2;
                            xBaseB = xLeft;
                            xBaseCenter = xLeft;
                            yTip = yBottom - scaledTetherLength / 2;
                            yBaseA = yBottom;
                            yBaseB = yBottom + scaledTetherBaseWidth / 2;
                            yBaseCenter = yBottom;
                            break;
                        case 'bottom-center':
                            xTip = 0;
                            xBaseA = scaledTetherBaseWidth / 2;
                            xBaseB = -scaledTetherBaseWidth / 2;
                            xBaseCenter = 0;
                            yTip = yBottom - scaledTetherLength;
                            yBaseA = yBottom;
                            yBaseB = yBottom;
                            yBaseCenter = yBottom;
                            break;
                        case 'bottom-right':
                            xTip = xRight + scaledTetherLength / 2;
                            xBaseA = xRight;
                            xBaseB = xRight - scaledTetherBaseWidth / 2;
                            xBaseCenter = xRight;
                            yTip = yBottom - scaledTetherLength / 2;
                            yBaseA = yBottom + scaledTetherBaseWidth / 2;
                            yBaseB = yBottom;
                            yBaseCenter = yBottom;
                            break;
                        case 'middle-left':
                            xTip = xLeft - scaledTetherLength;
                            xBaseA = xLeft;
                            xBaseB = xLeft;
                            xBaseCenter = xLeft;
                            yTip = 0;
                            yBaseA = -scaledTetherBaseWidth / 2;
                            yBaseB = scaledTetherBaseWidth / 2;
                            yBaseCenter = 0;
                            break;
                        case 'middle-center':
                            xTip = 0;
                            xBaseA = 0;
                            xBaseB = 0;
                            xBaseCenter = 0;
                            yTip = 0;
                            yBaseA = 0;
                            yBaseB = 0;
                            yBaseCenter = 0;
                            break;
                        case 'middle-right':
                            xTip = xRight + scaledTetherLength;
                            xBaseA = xRight;
                            xBaseB = xRight;
                            xBaseCenter = xRight;
                            yTip = 0;
                            yBaseA = scaledTetherBaseWidth / 2;
                            yBaseB = -scaledTetherBaseWidth / 2;
                            yBaseCenter = 0;
                            break;
                        case 'top-left':
                            xTip = xLeft - scaledTetherLength / 2;
                            xBaseA = xLeft + scaledTetherBaseWidth / 2;
                            xBaseB = xLeft;
                            xBaseCenter = xLeft;
                            yTip = yTop + scaledTetherLength / 2;
                            yBaseA = yTop;
                            yBaseB = yTop - scaledTetherBaseWidth / 2;
                            yBaseCenter = yTop;
                            break;
                        case 'top-center':
                            xTip = 0;
                            xBaseA = scaledTetherBaseWidth / 2;
                            xBaseB = -scaledTetherBaseWidth / 2;
                            xBaseCenter = 0;
                            yTip = yTop + scaledTetherLength;
                            yBaseA = yTop;
                            yBaseB = yTop;
                            yBaseCenter = yTop;
                            break;
                        case 'top-right':
                            xTip = xRight + scaledTetherLength / 2;
                            xBaseA = xRight;
                            xBaseB = xRight - scaledTetherBaseWidth / 2;
                            xBaseCenter = xRight;
                            yTip = yTop + scaledTetherLength / 2;
                            yBaseA = yTop - scaledTetherBaseWidth / 2;
                            yBaseB = yTop;
                            yBaseCenter = yTop;
                            break;
                        default:
                            throw new Error('unsupported attachment');
                    }
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xTip, yTip); // tip
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xBaseA, yBaseA); // base A
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xBaseB, yBaseB); // base B
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, xBaseCenter, yBaseCenter); // base center
                    var offset = centers.elementCount;
                    for (var i = 0; i < 4; ++i) {
                        _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, 10, 10);
                        add(x, y, z, depth, group);
                    }
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset, offset + 1, offset + 3);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset, offset + 3, offset + 2);
                }
                xShift += outline;
                yShift += outline;
                var xadvance = 0;
                for (var iChar = 0; iChar < nChar; ++iChar) {
                    var c = fontAtlas.get(str[iChar]);
                    var left = (xadvance - xShift) * scale;
                    var right = (xadvance + c.nw - xShift) * scale;
                    var top_1 = (c.nh - yShift) * scale;
                    var bottom = (-yShift) * scale;
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, left, top_1);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, left, bottom);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, right, top_1);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(mappings, right, bottom);
                    var texWidth = fontAtlas.texture.width;
                    var texHeight = fontAtlas.texture.height;
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, c.x / texWidth, c.y / texHeight); // top left
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, c.x / texWidth, (c.y + c.h) / texHeight); // bottom left
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, (c.x + c.w) / texWidth, c.y / texHeight); // top right
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add2(tcoords, (c.x + c.w) / texWidth, (c.y + c.h) / texHeight); // bottom right
                    xadvance += c.nw - 2 * outline;
                    var offset = centers.elementCount;
                    for (var i = 0; i < 4; ++i)
                        add(x, y, z, depth, group);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset + quadIndices[0], offset + quadIndices[1], offset + quadIndices[2]);
                    _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].add3(indices, offset + quadIndices[3], offset + quadIndices[4], offset + quadIndices[5]);
                }
            },
            getText: function () {
                var ft = fontAtlas.texture;
                var cb = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(centers, true);
                var mb = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(mappings, true);
                var db = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(depths, true);
                var ib = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(indices, true);
                var gb = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(groups, true);
                var tb = _mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* ChunkedArray */ "a"].compact(tcoords, true);
                return _text__WEBPACK_IMPORTED_MODULE_3__[/* Text */ "a"].create(ft, cb, mb, db, ib, gb, tb, indices.elementCount / 2, text);
            }
        };
    }
    TextBuilder.create = create;
})(TextBuilder || (TextBuilder = {}));
//# sourceMappingURL=text-builder.js.map

/***/ }),
/* 210 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ computeMarchingCubesMesh; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ computeMarchingCubesLines; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/marching-cubes/tables.js
var tables = __webpack_require__(187);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/lines/lines-builder.js
var lines_builder = __webpack_require__(172);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/util/marching-cubes/builder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 */





function MarchinCubesMeshBuilder(vertexChunkSize, mesh) {
    var triangleChunkSize = Math.min(1 << 16, vertexChunkSize * 4);
    var vertices = util["a" /* ChunkedArray */].create(Float32Array, 3, vertexChunkSize, mesh && mesh.vertexBuffer.ref.value);
    var normals = util["a" /* ChunkedArray */].create(Float32Array, 3, vertexChunkSize, mesh && mesh.normalBuffer.ref.value);
    var groups = util["a" /* ChunkedArray */].create(Float32Array, 1, vertexChunkSize, mesh && mesh.groupBuffer.ref.value);
    var indices = util["a" /* ChunkedArray */].create(Uint32Array, 3, triangleChunkSize, mesh && mesh.indexBuffer.ref.value);
    var vertexCount = 0;
    var triangleCount = 0;
    return {
        addVertex: function (x, y, z) {
            ++vertexCount;
            return util["a" /* ChunkedArray */].add3(vertices, x, y, z);
        },
        addNormal: function (x, y, z) {
            util["a" /* ChunkedArray */].add3(normals, x, y, z);
        },
        addGroup: function (group) {
            util["a" /* ChunkedArray */].add(groups, group);
        },
        addTriangle: function (vertList, a, b, c) {
            var i = vertList[a], j = vertList[b], k = vertList[c];
            // vertex indices <0 mean that the vertex was ignored and is not available
            // and hence we don't add a triangle when this occurs
            if (i >= 0 && j >= 0 && k >= 0) {
                ++triangleCount;
                util["a" /* ChunkedArray */].add3(indices, i, j, k);
            }
        },
        get: function () {
            var vb = util["a" /* ChunkedArray */].compact(vertices, true);
            var nb = util["a" /* ChunkedArray */].compact(normals, true);
            var ib = util["a" /* ChunkedArray */].compact(indices, true);
            var gb = util["a" /* ChunkedArray */].compact(groups, true);
            return mesh_mesh["a" /* Mesh */].create(vb, ib, nb, gb, vertexCount, triangleCount, mesh);
        }
    };
}
function MarchinCubesLinesBuilder(vertexChunkSize, lines) {
    var vertices = util["a" /* ChunkedArray */].create(Float32Array, 3, vertexChunkSize);
    var groups = util["a" /* ChunkedArray */].create(Float32Array, 1, vertexChunkSize);
    var indices = util["a" /* ChunkedArray */].create(Float32Array, 2, vertexChunkSize);
    var linesCount = 0;
    return {
        addVertex: function (x, y, z) {
            return util["a" /* ChunkedArray */].add3(vertices, x, y, z);
        },
        addNormal: function () { return mol_util["k" /* noop */]; },
        addGroup: function (group) {
            util["a" /* ChunkedArray */].add(groups, group);
        },
        addTriangle: function (vertList, a, b, c, edgeFilter) {
            var i = vertList[a], j = vertList[b], k = vertList[c];
            // vertex indices <0 mean that the vertex was ignored and is not available
            // and hence we don't add a triangle when this occurs
            if (i >= 0 && j >= 0 && k >= 0) {
                if (tables["a" /* AllowedContours */][a][b] & edgeFilter) {
                    ++linesCount;
                    util["a" /* ChunkedArray */].add2(indices, vertList[a], vertList[b]);
                }
                if (tables["a" /* AllowedContours */][b][c] & edgeFilter) {
                    ++linesCount;
                    util["a" /* ChunkedArray */].add2(indices, vertList[b], vertList[c]);
                }
                if (tables["a" /* AllowedContours */][a][c] & edgeFilter) {
                    ++linesCount;
                    util["a" /* ChunkedArray */].add2(indices, vertList[a], vertList[c]);
                }
            }
        },
        get: function () {
            var vb = util["a" /* ChunkedArray */].compact(vertices, true);
            var ib = util["a" /* ChunkedArray */].compact(indices, true);
            var gb = util["a" /* ChunkedArray */].compact(groups, true);
            var builder = lines_builder["a" /* LinesBuilder */].create(linesCount, linesCount / 10, lines);
            for (var i = 0; i < linesCount; ++i) {
                var la = ib[i * 2], lb = ib[i * 2 + 1];
                builder.add(vb[la * 3], vb[la * 3 + 1], vb[la * 3 + 2], vb[lb * 3], vb[lb * 3 + 1], vb[lb * 3 + 2], gb[la]);
            }
            return builder.getLines();
        }
    };
}
//# sourceMappingURL=builder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/util/marching-cubes/algorithm.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function getInputParams(params) {
    return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { bottomLeft: Object(mol_util["i" /* defaults */])(params.bottomLeft, [0, 0, 0]), topRight: Object(mol_util["i" /* defaults */])(params.topRight, params.scalarField.space.dimensions) });
}
function getExtent(inputParams) {
    return {
        dX: inputParams.topRight[0] - inputParams.bottomLeft[0],
        dY: inputParams.topRight[1] - inputParams.bottomLeft[1],
        dZ: inputParams.topRight[2] - inputParams.bottomLeft[2]
    };
}
function computeMarchingCubesMesh(params, mesh) {
    var _this = this;
    return mol_task["b" /* Task */].create('Marching Cubes Mesh', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var inputParams, _a, dX, dY, dZ, vertexChunkSize, builder;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    inputParams = getInputParams(params);
                    _a = getExtent(inputParams), dX = _a.dX, dY = _a.dY, dZ = _a.dZ;
                    vertexChunkSize = Math.min(262144, Math.max(dX * dY * dZ / 32, 1024));
                    builder = MarchinCubesMeshBuilder(vertexChunkSize, mesh);
                    return [4 /*yield*/, (new algorithm_MarchingCubesComputation(ctx, builder, inputParams)).run()];
                case 1:
                    _b.sent();
                    return [2 /*return*/, builder.get()];
            }
        });
    }); });
}
function computeMarchingCubesLines(params, lines) {
    var _this = this;
    return mol_task["b" /* Task */].create('Marching Cubes Lines', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var inputParams, _a, dX, dY, dZ, vertexChunkSize, builder;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    inputParams = getInputParams(params);
                    _a = getExtent(inputParams), dX = _a.dX, dY = _a.dY, dZ = _a.dZ;
                    vertexChunkSize = Math.min(262144, Math.max(dX * dY * dZ / 32, 1024));
                    builder = MarchinCubesLinesBuilder(vertexChunkSize, lines);
                    return [4 /*yield*/, (new algorithm_MarchingCubesComputation(ctx, builder, inputParams)).run()];
                case 1:
                    _b.sent();
                    return [2 /*return*/, builder.get()];
            }
        });
    }); });
}
var algorithm_MarchingCubesComputation = /** @class */ (function () {
    function MarchingCubesComputation(ctx, builder, params) {
        this.ctx = ctx;
        this.minX = 0;
        this.minY = 0;
        this.minZ = 0;
        this.maxX = 0;
        this.maxY = 0;
        this.maxZ = 0;
        this.state = new algorithm_MarchingCubesState(builder, params);
        this.minX = params.bottomLeft[0];
        this.minY = params.bottomLeft[1];
        this.minZ = params.bottomLeft[2];
        this.maxX = params.topRight[0] - 1;
        this.maxY = params.topRight[1] - 1;
        this.maxZ = params.topRight[2] - 1;
        this.size = (this.maxX - this.minX) * (this.maxY - this.minY) * (this.maxZ - this.minZ);
        this.sliceSize = (this.maxX - this.minX) * (this.maxY - this.minY);
    }
    MarchingCubesComputation.prototype.doSlices = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var done, k;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        done = 0;
                        this.edgeFilter = 15;
                        k = this.minZ;
                        _a.label = 1;
                    case 1:
                        if (!(k < this.maxZ)) return [3 /*break*/, 4];
                        this.slice(k);
                        done += this.sliceSize;
                        if (!this.ctx.shouldUpdate) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.ctx.update({ message: 'Computing surface...', current: done, max: this.size })];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        k++, this.edgeFilter &= ~4;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    MarchingCubesComputation.prototype.slice = function (k) {
        this.edgeFilter |= 2;
        for (var j = this.minY; j < this.maxY; j++, this.edgeFilter &= ~2) {
            this.edgeFilter |= 1;
            for (var i = this.minX; i < this.maxX; i++, this.edgeFilter &= ~1) {
                this.state.processCell(i, j, k, this.edgeFilter);
            }
        }
        this.state.clearEdgeVertexIndexSlice(k);
    };
    MarchingCubesComputation.prototype.run = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.doSlices()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    return MarchingCubesComputation;
}());
var algorithm_MarchingCubesState = /** @class */ (function () {
    function MarchingCubesState(builder, params) {
        this.builder = builder;
        this.vertList = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
        this.i = 0;
        this.j = 0;
        this.k = 0;
        var dims = params.scalarField.space.dimensions;
        this.nX = dims[0];
        this.nY = dims[1];
        this.nZ = dims[2];
        this.isoLevel = params.isoLevel;
        this.scalarFieldGet = params.scalarField.space.get;
        this.scalarField = params.scalarField.data;
        if (params.idField) {
            this.idField = params.idField.data;
            this.idFieldGet = params.idField.space.get;
        }
        // two layers of vertex indices. Each vertex has 3 edges associated.
        this.verticesOnEdges = new Int32Array(3 * this.nX * this.nY * 2);
    }
    MarchingCubesState.prototype.get3dOffsetFromEdgeInfo = function (index) {
        return (this.nX * (((this.k + index.k) % 2) * this.nY + this.j + index.j) + this.i + index.i);
    };
    /**
     * This clears the "vertex index buffer" for the slice that will not be accessed anymore.
     */
    MarchingCubesState.prototype.clearEdgeVertexIndexSlice = function (k) {
        // clear either the top or bottom half of the buffer...
        var start = k % 2 === 0 ? 0 : 3 * this.nX * this.nY;
        var end = k % 2 === 0 ? 3 * this.nX * this.nY : this.verticesOnEdges.length;
        for (var i = start; i < end; i++)
            this.verticesOnEdges[i] = 0;
    };
    MarchingCubesState.prototype.interpolate = function (edgeNum) {
        var info = tables["c" /* EdgeIdInfo */][edgeNum];
        var edgeId = 3 * this.get3dOffsetFromEdgeInfo(info) + info.e;
        var ret = this.verticesOnEdges[edgeId];
        if (ret > 0)
            return ret - 1;
        var sf = this.scalarField;
        var sfg = this.scalarFieldGet;
        var edge = tables["b" /* CubeEdges */][edgeNum];
        var a = edge.a, b = edge.b;
        var li = a.i + this.i, lj = a.j + this.j, lk = a.k + this.k;
        var hi = b.i + this.i, hj = b.j + this.j, hk = b.k + this.k;
        var v0 = sfg(sf, li, lj, lk);
        var v1 = sfg(sf, hi, hj, hk);
        var t = (this.isoLevel - v0) / (v0 - v1);
        if (this.idField) {
            var u = this.idFieldGet(this.idField, li, lj, lk);
            var v = this.idFieldGet(this.idField, hi, hj, hk);
            var a_1 = t < 0.5 ? u : v;
            // -1 means 'no id', check if the other cell has an id
            if (a_1 === -1)
                a_1 = t < 0.5 ? v : u;
            // -2 means 'ignore this cell'
            if (a_1 === -2)
                return -1;
            this.builder.addGroup(a_1);
        }
        else {
            this.builder.addGroup(0);
        }
        var id = this.builder.addVertex(li + t * (li - hi), lj + t * (lj - hj), lk + t * (lk - hk));
        this.verticesOnEdges[edgeId] = id + 1;
        // TODO cache scalarField differences for slices
        // TODO make calculation optional
        var n0x = sfg(sf, Math.max(0, li - 1), lj, lk) - sfg(sf, Math.min(this.nX - 1, li + 1), lj, lk);
        var n0y = sfg(sf, li, Math.max(0, lj - 1), lk) - sfg(sf, li, Math.min(this.nY - 1, lj + 1), lk);
        var n0z = sfg(sf, li, lj, Math.max(0, lk - 1)) - sfg(sf, li, lj, Math.min(this.nZ, lk + 1));
        var n1x = sfg(sf, Math.max(0, hi - 1), hj, hk) - sfg(sf, Math.min(this.nX - 1, hi + 1), hj, hk);
        var n1y = sfg(sf, hi, Math.max(0, hj - 1), hk) - sfg(sf, hi, Math.min(this.nY - 1, hj + 1), hk);
        var n1z = sfg(sf, hi, hj, Math.max(0, hk - 1)) - sfg(sf, hi, hj, Math.min(this.nZ - 1, hk + 1));
        var nx = n0x + t * (n0x - n1x);
        var ny = n0y + t * (n0y - n1y);
        var nz = n0z + t * (n0z - n1z);
        // ensure normal-direction is the same for negative and positive iso-levels
        if (this.isoLevel >= 0) {
            this.builder.addNormal(nx, ny, nz);
        }
        else {
            this.builder.addNormal(-nx, -ny, -nz);
        }
        return id;
    };
    MarchingCubesState.prototype.get = function (i, j, k) {
        return this.scalarFieldGet(this.scalarField, i, j, k);
    };
    MarchingCubesState.prototype.processCell = function (i, j, k, edgeFilter) {
        var tableIndex = 0;
        if (this.get(i, j, k) < this.isoLevel)
            tableIndex |= 1;
        if (this.get(i + 1, j, k) < this.isoLevel)
            tableIndex |= 2;
        if (this.get(i + 1, j + 1, k) < this.isoLevel)
            tableIndex |= 4;
        if (this.get(i, j + 1, k) < this.isoLevel)
            tableIndex |= 8;
        if (this.get(i, j, k + 1) < this.isoLevel)
            tableIndex |= 16;
        if (this.get(i + 1, j, k + 1) < this.isoLevel)
            tableIndex |= 32;
        if (this.get(i + 1, j + 1, k + 1) < this.isoLevel)
            tableIndex |= 64;
        if (this.get(i, j + 1, k + 1) < this.isoLevel)
            tableIndex |= 128;
        if (tableIndex === 0 || tableIndex === 255)
            return;
        this.i = i;
        this.j = j;
        this.k = k;
        var edgeInfo = tables["d" /* EdgeTable */][tableIndex];
        if ((edgeInfo & 1) > 0)
            this.vertList[0] = this.interpolate(0); // 0 1
        if ((edgeInfo & 2) > 0)
            this.vertList[1] = this.interpolate(1); // 1 2
        if ((edgeInfo & 4) > 0)
            this.vertList[2] = this.interpolate(2); // 2 3
        if ((edgeInfo & 8) > 0)
            this.vertList[3] = this.interpolate(3); // 0 3
        if ((edgeInfo & 16) > 0)
            this.vertList[4] = this.interpolate(4); // 4 5
        if ((edgeInfo & 32) > 0)
            this.vertList[5] = this.interpolate(5); // 5 6
        if ((edgeInfo & 64) > 0)
            this.vertList[6] = this.interpolate(6); // 6 7
        if ((edgeInfo & 128) > 0)
            this.vertList[7] = this.interpolate(7); // 4 7
        if ((edgeInfo & 256) > 0)
            this.vertList[8] = this.interpolate(8); // 0 4
        if ((edgeInfo & 512) > 0)
            this.vertList[9] = this.interpolate(9); // 1 5
        if ((edgeInfo & 1024) > 0)
            this.vertList[10] = this.interpolate(10); // 2 6
        if ((edgeInfo & 2048) > 0)
            this.vertList[11] = this.interpolate(11); // 3 7
        var triInfo = tables["e" /* TriTable */][tableIndex];
        for (var t = 0; t < triInfo.length; t += 3) {
            var l = triInfo[t], m = triInfo[t + 1], n = triInfo[t + 2];
            // ensure winding-order is the same for negative and positive iso-levels
            if (this.isoLevel >= 0) {
                this.builder.addTriangle(this.vertList, l, m, n, edgeFilter);
            }
            else {
                this.builder.addTriangle(this.vertList, n, m, l, edgeFilter);
            }
        }
    };
    return MarchingCubesState;
}());
//# sourceMappingURL=algorithm.js.map

/***/ }),
/* 211 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AtomSiteAnisotrop; });
/* harmony import */ var _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57);
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(62);
/* harmony import */ var _common_property__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(188);
/* harmony import */ var _mmcif__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(71);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var Anisotrop = {
    U: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].atom_site_anisotrop.U,
    U_esd: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].atom_site_anisotrop.U_esd
};
var AtomSiteAnisotrop;
(function (AtomSiteAnisotrop) {
    AtomSiteAnisotrop.Schema = Anisotrop;
    AtomSiteAnisotrop.Descriptor = {
        name: 'atom_site_anisotrop',
        cifExport: {
            prefix: '',
            categories: [{
                    name: 'atom_site_anisotrop',
                    instance: function (ctx) {
                        var p = AtomSiteAnisotrop.Provider.get(ctx.firstModel);
                        if (!p)
                            return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.Empty;
                        if (!_mmcif__WEBPACK_IMPORTED_MODULE_3__["MmcifFormat"].is(ctx.firstModel.sourceData))
                            return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.Empty;
                        // TODO filter to write only data for elements that exist in model
                        return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.ofTable(ctx.firstModel.sourceData.data.db.atom_site_anisotrop);
                    }
                }]
        }
    };
    AtomSiteAnisotrop.Provider = _common_property__WEBPACK_IMPORTED_MODULE_2__[/* FormatPropertyProvider */ "a"].create(AtomSiteAnisotrop.Descriptor);
    function getElementToAnsiotrop(atomId, ansioId) {
        var atomIdToElement = new Int32Array(atomId.rowCount);
        atomIdToElement.fill(-1);
        for (var i = 0, il = atomId.rowCount; i < il; i++) {
            atomIdToElement[atomId.value(i)] = i;
        }
        var elementToAnsiotrop = new Int32Array(atomId.rowCount);
        elementToAnsiotrop.fill(-1);
        for (var i = 0, il = ansioId.rowCount; i < il; ++i) {
            var ei = atomIdToElement[ansioId.value(i)];
            if (ei !== -1)
                elementToAnsiotrop[ei] = i;
        }
        return elementToAnsiotrop;
    }
    AtomSiteAnisotrop.getElementToAnsiotrop = getElementToAnsiotrop;
    function getElementToAnsiotropFromLabel(atomLabel, ansioLabel) {
        var atomLabelToElement = {};
        for (var i = 0, il = atomLabel.rowCount; i < il; i++) {
            atomLabelToElement[atomLabel.value(i)] = i;
        }
        var elementToAnsiotrop = new Int32Array(atomLabel.rowCount);
        elementToAnsiotrop.fill(-1);
        for (var i = 0, il = ansioLabel.rowCount; i < il; ++i) {
            var ei = atomLabelToElement[ansioLabel.value(i)];
            if (ei !== undefined)
                elementToAnsiotrop[ei] = i;
        }
        return elementToAnsiotrop;
    }
    AtomSiteAnisotrop.getElementToAnsiotropFromLabel = getElementToAnsiotropFromLabel;
})(AtomSiteAnisotrop || (AtomSiteAnisotrop = {}));
//# sourceMappingURL=anisotropic.js.map

/***/ }),
/* 212 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructureQualityReport; });
/* unused harmony export StructureQualityReportParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StructureQualityReportProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(7);
/* harmony import */ var _mol_io_reader_cif_schema__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(135);
/* harmony import */ var _mol_io_reader_cif_schema_mmcif_extras__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(359);
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(62);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(4);
/* harmony import */ var _mol_model_structure_export_categories_atom_site__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(251);
/* harmony import */ var _mol_script_language_symbol__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(18);
/* harmony import */ var _mol_script_language_type__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(15);
/* harmony import */ var _mol_script_runtime_query_compiler__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(163);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(2);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(29);
/* harmony import */ var _mol_model_formats_structure_mmcif__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(71);
/* harmony import */ var _mol_model_props_common_wrapper__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(236);
/* harmony import */ var _mol_model_props_common_custom_model_property__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(276);
/* harmony import */ var _mol_util_assets__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(114);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(65);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















var StructureQualityReport;
(function (StructureQualityReport) {
    StructureQualityReport.DefaultServerUrl = 'https://www.ebi.ac.uk/pdbe/api/validation/residuewise_outlier_summary/entry/';
    function getEntryUrl(pdbId, serverUrl) {
        return serverUrl + "/" + pdbId.toLowerCase();
    }
    StructureQualityReport.getEntryUrl = getEntryUrl;
    function isApplicable(model) {
        return !!model && _mol_model_structure__WEBPACK_IMPORTED_MODULE_5__["Model"].isFromPdbArchive(model);
    }
    StructureQualityReport.isApplicable = isApplicable;
    StructureQualityReport.Schema = {
        pdbe_structure_quality_report: {
            updated_datetime_utc: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.str
        },
        pdbe_structure_quality_report_issues: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ id: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.int }, _mol_io_reader_cif_schema_mmcif_extras__WEBPACK_IMPORTED_MODULE_3__[/* mmCIF_residueId_schema */ "b"]), { pdbx_PDB_model_num: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.int, issue_type_group_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.int }),
        pdbe_structure_quality_report_issue_types: {
            group_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.int,
            issue_type: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Column"].Schema.str
        }
    };
    function fromJson(model, data) {
        var info = _mol_model_props_common_wrapper__WEBPACK_IMPORTED_MODULE_13__["PropertyWrapper"].createInfo();
        var issueMap = createIssueMapFromJson(model, data);
        return { info: info, data: issueMap };
    }
    StructureQualityReport.fromJson = fromJson;
    function fromServer(ctx, model, props) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var url, json, data;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = _mol_util_assets__WEBPACK_IMPORTED_MODULE_15__["Asset"].getUrlAsset(ctx.assetManager, getEntryUrl(model.entryId, props.serverUrl));
                        return [4 /*yield*/, ctx.assetManager.resolve(url, 'json').runInContext(ctx.runtime)];
                    case 1:
                        json = _a.sent();
                        data = json.data[model.entryId.toLowerCase()];
                        if (!data)
                            throw new Error('missing data');
                        return [2 /*return*/, { value: fromJson(model, data), assets: [json] }];
                }
            });
        });
    }
    StructureQualityReport.fromServer = fromServer;
    function fromCif(ctx, model, props) {
        var info = _mol_model_props_common_wrapper__WEBPACK_IMPORTED_MODULE_13__["PropertyWrapper"].tryGetInfoFromCif('pdbe_structure_quality_report', model);
        if (!info)
            return;
        var data = getCifData(model);
        var issueMap = createIssueMapFromCif(model, data.residues, data.groups);
        return { info: info, data: issueMap };
    }
    StructureQualityReport.fromCif = fromCif;
    function fromCifOrServer(ctx, model, props) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cif;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                cif = fromCif(ctx, model, props);
                return [2 /*return*/, cif ? { value: cif } : fromServer(ctx, model, props)];
            });
        });
    }
    StructureQualityReport.fromCifOrServer = fromCifOrServer;
    var _emptyArray = [];
    function getIssues(e) {
        if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_5__["Unit"].isAtomic(e.unit))
            return _emptyArray;
        var prop = StructureQualityReportProvider.get(e.unit.model).value;
        if (!prop || !prop.data)
            return _emptyArray;
        var rI = e.unit.residueIndex[e.element];
        return prop.data.issues.has(rI) ? prop.data.issues.get(rI) : _emptyArray;
    }
    StructureQualityReport.getIssues = getIssues;
    function getIssueTypes(structure) {
        if (!structure)
            return _emptyArray;
        var prop = StructureQualityReportProvider.get(structure.models[0]).value;
        if (!prop || !prop.data)
            return _emptyArray;
        return prop.data.issueTypes;
    }
    StructureQualityReport.getIssueTypes = getIssueTypes;
    function getCifData(model) {
        if (!_mol_model_formats_structure_mmcif__WEBPACK_IMPORTED_MODULE_12__["MmcifFormat"].is(model.sourceData))
            throw new Error('Data format must be mmCIF.');
        return {
            residues: Object(_mol_io_reader_cif_schema__WEBPACK_IMPORTED_MODULE_2__["toTable"])(StructureQualityReport.Schema.pdbe_structure_quality_report_issues, model.sourceData.data.frame.categories.pdbe_structure_quality_report_issues),
            groups: Object(_mol_io_reader_cif_schema__WEBPACK_IMPORTED_MODULE_2__["toTable"])(StructureQualityReport.Schema.pdbe_structure_quality_report_issue_types, model.sourceData.data.frame.categories.pdbe_structure_quality_report_issue_types),
        };
    }
})(StructureQualityReport || (StructureQualityReport = {}));
var StructureQualityReportParams = {
    serverUrl: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Text(StructureQualityReport.DefaultServerUrl, { description: 'JSON API Server URL' })
};
var StructureQualityReportProvider = _mol_model_props_common_custom_model_property__WEBPACK_IMPORTED_MODULE_14__["CustomModelProperty"].createProvider({
    label: 'Structure Quality Report',
    descriptor: Object(_mol_model_custom_property__WEBPACK_IMPORTED_MODULE_16__["CustomPropertyDescriptor"])({
        name: 'pdbe_structure_quality_report',
        cifExport: {
            prefix: 'pdbe',
            context: function (ctx) {
                return createExportContext(ctx);
            },
            categories: [
                _mol_model_props_common_wrapper__WEBPACK_IMPORTED_MODULE_13__["PropertyWrapper"].defaultInfoCategory('pdbe_structure_quality_report', function (ctx) { return ctx.info; }),
                {
                    name: 'pdbe_structure_quality_report_issues',
                    instance: function (ctx) {
                        return {
                            fields: _structure_quality_report_issues_fields,
                            source: ctx.models.map(function (data) { return ({ data: data, rowCount: data.elements.length }); })
                        };
                    }
                }, {
                    name: 'pdbe_structure_quality_report_issue_types',
                    instance: function (ctx) {
                        return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_4__[/* CifWriter */ "a"].Category.ofTable(ctx.issueTypes);
                    }
                }
            ]
        },
        symbols: {
            issueCount: _mol_script_runtime_query_compiler__WEBPACK_IMPORTED_MODULE_9__["QuerySymbolRuntime"].Dynamic(Object(_mol_script_language_symbol__WEBPACK_IMPORTED_MODULE_7__[/* CustomPropSymbol */ "c"])('pdbe', 'structure-quality.issue-count', _mol_script_language_type__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].Num), function (ctx) { return StructureQualityReport.getIssues(ctx.element).length; }),
        }
    }),
    type: 'static',
    defaultParams: StructureQualityReportParams,
    getParams: function (data) { return StructureQualityReportParams; },
    isApplicable: function (data) { return StructureQualityReport.isApplicable(data); },
    obtain: function (ctx, data, props) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(void 0, void 0, void 0, function () {
        var p;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].getDefaultValues(StructureQualityReportParams)), props);
                    return [4 /*yield*/, StructureQualityReport.fromCifOrServer(ctx, data, p)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); }
});
var _structure_quality_report_issues_fields = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_4__[/* CifWriter */ "a"].fields()
    .index('id')
    .many(Object(_mol_model_structure_export_categories_atom_site__WEBPACK_IMPORTED_MODULE_6__[/* residueIdFields */ "b"])(function (i, d) { return d.elements[i]; }, { includeModelNum: true }))
    .int('issue_type_group_id', function (i, d) { return d.groupId[i]; })
    .getFields();
function createExportContext(ctx) {
    var groupMap = new Map();
    var models = [];
    var group_id = [], issue_type = [];
    var info = _mol_model_props_common_wrapper__WEBPACK_IMPORTED_MODULE_13__["PropertyWrapper"].createInfo();
    for (var _i = 0, _a = ctx.structures; _i < _a.length; _i++) {
        var s = _a[_i];
        var prop = StructureQualityReportProvider.get(s.model).value;
        if (prop)
            info = prop.info;
        if (!prop || !prop.data)
            continue;
        var _b = prop.data.issues.getElements(s), elements = _b.elements, property = _b.property;
        if (elements.length === 0)
            continue;
        var elementGroupId = [];
        for (var i = 0; i < elements.length; i++) {
            var issues = property(i);
            var key = issues.join(',');
            if (!groupMap.has(key)) {
                var idx = groupMap.size + 1;
                groupMap.set(key, idx);
                for (var _c = 0, issues_1 = issues; _c < issues_1.length; _c++) {
                    var issue = issues_1[_c];
                    group_id.push(idx);
                    issue_type.push(issue);
                }
            }
            elementGroupId[i] = groupMap.get(key);
        }
        models.push({ elements: elements, groupId: elementGroupId });
    }
    return {
        info: info,
        models: models,
        issueTypes: _mol_data_db__WEBPACK_IMPORTED_MODULE_1__["Table"].ofArrays(StructureQualityReport.Schema.pdbe_structure_quality_report_issue_types, { group_id: group_id, issue_type: issue_type })
    };
}
function createIssueMapFromJson(modelData, data) {
    var ret = new Map();
    if (!data.molecules)
        return;
    var issueTypes = [];
    for (var _i = 0, _a = data.molecules; _i < _a.length; _i++) {
        var entity = _a[_i];
        var entity_id = entity.entity_id.toString();
        for (var _b = 0, _c = entity.chains; _b < _c.length; _b++) {
            var chain = _c[_b];
            var asym_id = chain.struct_asym_id.toString();
            for (var _d = 0, _e = chain.models; _d < _e.length; _d++) {
                var model = _e[_d];
                var model_id = model.model_id.toString();
                if (+model_id !== modelData.modelNum)
                    continue;
                for (var _f = 0, _g = model.residues; _f < _g.length; _f++) {
                    var residue = _g[_f];
                    var auth_seq_id = residue.author_residue_number, ins_code = residue.author_insertion_code || '';
                    var idx = modelData.atomicHierarchy.index.findResidue(entity_id, asym_id, auth_seq_id, ins_code);
                    ret.set(idx, residue.outlier_types);
                    for (var _h = 0, _j = residue.outlier_types; _h < _j.length; _h++) {
                        var t = _j[_h];
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_11__["arraySetAdd"])(issueTypes, t);
                    }
                }
            }
        }
    }
    return {
        issues: _mol_model_structure__WEBPACK_IMPORTED_MODULE_5__["IndexedCustomProperty"].fromResidueMap(ret),
        issueTypes: issueTypes
    };
}
function createIssueMapFromCif(modelData, residueData, groupData) {
    var ret = new Map();
    var label_entity_id = residueData.label_entity_id, label_asym_id = residueData.label_asym_id, auth_seq_id = residueData.auth_seq_id, pdbx_PDB_ins_code = residueData.pdbx_PDB_ins_code, issue_type_group_id = residueData.issue_type_group_id, pdbx_PDB_model_num = residueData.pdbx_PDB_model_num, _rowCount = residueData._rowCount;
    var groups = parseIssueTypes(groupData);
    for (var i = 0; i < _rowCount; i++) {
        if (pdbx_PDB_model_num.value(i) !== modelData.modelNum)
            continue;
        var idx = modelData.atomicHierarchy.index.findResidue(label_entity_id.value(i), label_asym_id.value(i), auth_seq_id.value(i), pdbx_PDB_ins_code.value(i));
        ret.set(idx, groups.get(issue_type_group_id.value(i)));
    }
    var issueTypes = [];
    groups.forEach(function (issues) {
        for (var _i = 0, issues_2 = issues; _i < issues_2.length; _i++) {
            var t = issues_2[_i];
            Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_11__["arraySetAdd"])(issueTypes, t);
        }
    });
    return {
        issues: _mol_model_structure__WEBPACK_IMPORTED_MODULE_5__["IndexedCustomProperty"].fromResidueMap(ret),
        issueTypes: issueTypes
    };
}
function parseIssueTypes(groupData) {
    var ret = new Map();
    var group_id = groupData.group_id, issue_type = groupData.issue_type;
    for (var i = 0; i < groupData._rowCount; i++) {
        var group = void 0;
        var id = group_id.value(i);
        if (ret.has(id))
            group = ret.get(id);
        else {
            group = [];
            ret.set(id, group);
        }
        group.push(issue_type.value(i));
    }
    return ret;
}
//# sourceMappingURL=prop.js.map

/***/ }),
/* 213 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mergeMap; });
/* unused harmony export MergeMapOperator */
/* unused harmony export MergeMapSubscriber */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(50);
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(52);
/* harmony import */ var _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(167);
/* harmony import */ var _map__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(116);
/* harmony import */ var _observable_from__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(140);
/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber,_map,_observable_from PURE_IMPORTS_END */






function mergeMap(project, resultSelector, concurrent) {
    if (concurrent === void 0) {
        concurrent = Number.POSITIVE_INFINITY;
    }
    if (typeof resultSelector === 'function') {
        return function (source) { return source.pipe(mergeMap(function (a, i) { return Object(_observable_from__WEBPACK_IMPORTED_MODULE_5__[/* from */ "a"])(project(a, i)).pipe(Object(_map__WEBPACK_IMPORTED_MODULE_4__[/* map */ "a"])(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); };
    }
    else if (typeof resultSelector === 'number') {
        concurrent = resultSelector;
    }
    return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); };
}
var MergeMapOperator = /*@__PURE__*/ (function () {
    function MergeMapOperator(project, concurrent) {
        if (concurrent === void 0) {
            concurrent = Number.POSITIVE_INFINITY;
        }
        this.project = project;
        this.concurrent = concurrent;
    }
    MergeMapOperator.prototype.call = function (observer, source) {
        return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent));
    };
    return MergeMapOperator;
}());

var MergeMapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](MergeMapSubscriber, _super);
    function MergeMapSubscriber(destination, project, concurrent) {
        if (concurrent === void 0) {
            concurrent = Number.POSITIVE_INFINITY;
        }
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.concurrent = concurrent;
        _this.hasCompleted = false;
        _this.buffer = [];
        _this.active = 0;
        _this.index = 0;
        return _this;
    }
    MergeMapSubscriber.prototype._next = function (value) {
        if (this.active < this.concurrent) {
            this._tryNext(value);
        }
        else {
            this.buffer.push(value);
        }
    };
    MergeMapSubscriber.prototype._tryNext = function (value) {
        var result;
        var index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.active++;
        this._innerSub(result, value, index);
    };
    MergeMapSubscriber.prototype._innerSub = function (ish, value, index) {
        var innerSubscriber = new _InnerSubscriber__WEBPACK_IMPORTED_MODULE_3__[/* InnerSubscriber */ "a"](this, value, index);
        var destination = this.destination;
        destination.add(innerSubscriber);
        var innerSubscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_1__[/* subscribeToResult */ "a"])(this, ish, undefined, undefined, innerSubscriber);
        if (innerSubscription !== innerSubscriber) {
            destination.add(innerSubscription);
        }
    };
    MergeMapSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (this.active === 0 && this.buffer.length === 0) {
            this.destination.complete();
        }
        this.unsubscribe();
    };
    MergeMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(innerValue);
    };
    MergeMapSubscriber.prototype.notifyComplete = function (innerSub) {
        var buffer = this.buffer;
        this.remove(innerSub);
        this.active--;
        if (buffer.length > 0) {
            this._next(buffer.shift());
        }
        else if (this.active === 0 && this.hasCompleted) {
            this.destination.complete();
        }
    };
    return MergeMapSubscriber;
}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_2__[/* OuterSubscriber */ "a"]));

//# sourceMappingURL=mergeMap.js.map


/***/ }),
/* 214 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ArgumentOutOfRangeError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () {
    function ArgumentOutOfRangeErrorImpl() {
        Error.call(this);
        this.message = 'argument out of range';
        this.name = 'ArgumentOutOfRangeError';
        return this;
    }
    ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return ArgumentOutOfRangeErrorImpl;
})();
var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl;
//# sourceMappingURL=ArgumentOutOfRangeError.js.map


/***/ }),
/* 215 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isFunction; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isFunction(x) {
    return typeof x === 'function';
}
//# sourceMappingURL=isFunction.js.map


/***/ }),
/* 216 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "registerDefault", function() { return registerDefault; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SyncBehaviors", function() { return SyncBehaviors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SetCurrentObject", function() { return SetCurrentObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Update", function() { return Update; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ApplyAction", function() { return ApplyAction; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemoveObject", function() { return RemoveObject; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleExpanded", function() { return ToggleExpanded; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ToggleVisibility", function() { return ToggleVisibility; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setSubtreeVisibility", function() { return setSubtreeVisibility; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Highlight", function() { return Highlight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ClearHighlights", function() { return ClearHighlights; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Snapshots", function() { return Snapshots; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_plugin_state_manager_snapshots__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(364);
/* harmony import */ var _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(8);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(13);
/* harmony import */ var _mol_util_date__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(308);
/* harmony import */ var _mol_util_download__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(329);
/* harmony import */ var _mol_util_url__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(262);
/* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(26);
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(101);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










function registerDefault(ctx) {
    SyncBehaviors(ctx);
    SetCurrentObject(ctx);
    Update(ctx);
    ApplyAction(ctx);
    RemoveObject(ctx);
    ToggleExpanded(ctx);
    ToggleVisibility(ctx);
    Highlight(ctx);
    ClearHighlights(ctx);
    Snapshots(ctx);
}
function SyncBehaviors(ctx) {
    ctx.state.events.object.created.subscribe(function (o) {
        if (!_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].isBehavior(o.obj))
            return;
        o.obj.data.register(o.ref);
    });
    ctx.state.events.object.removed.subscribe(function (o) {
        if (!_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].isBehavior(o.obj))
            return;
        o.obj.data.unregister();
    });
    ctx.state.events.object.updated.subscribe(function (o) {
        if (o.action === 'recreate') {
            if (o.oldObj && _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].isBehavior(o.oldObj))
                o.oldObj.data.unregister();
            if (o.obj && _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].isBehavior(o.obj))
                o.obj.data.register(o.ref);
        }
    });
}
function SetCurrentObject(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.SetCurrentObject.subscribe(ctx, function (_a) {
        var state = _a.state, ref = _a.ref;
        return state.setCurrent(ref);
    });
}
function Update(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Update.subscribe(ctx, function (_a) {
        var state = _a.state, tree = _a.tree, options = _a.options;
        return ctx.runTask(state.updateTree(tree, options));
    });
}
function ApplyAction(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.ApplyAction.subscribe(ctx, function (_a) {
        var state = _a.state, action = _a.action, ref = _a.ref;
        return ctx.runTask(state.applyAction(action.action, action.params, ref));
    });
}
function RemoveObject(ctx) {
    function remove(state, ref) {
        var tree = state.build().delete(ref);
        return ctx.runTask(state.updateTree(tree));
    }
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.RemoveObject.subscribe(ctx, function (_a) {
        var state = _a.state, ref = _a.ref, removeParentGhosts = _a.removeParentGhosts;
        if (removeParentGhosts) {
            var tree = state.tree;
            var curr = tree.transforms.get(ref);
            if (curr.parent === ref)
                return remove(state, ref);
            while (true) {
                var children = tree.children.get(curr.parent);
                if (curr.parent === curr.ref || children.size > 1)
                    return remove(state, curr.ref);
                var parent_1 = tree.transforms.get(curr.parent);
                // TODO: should this use "cell state" instead?
                if (!parent_1.state.isGhost)
                    return remove(state, curr.ref);
                curr = parent_1;
            }
        }
        else {
            return remove(state, ref);
        }
    });
}
function ToggleExpanded(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.ToggleExpanded.subscribe(ctx, function (_a) {
        var state = _a.state, ref = _a.ref;
        return state.updateCellState(ref, function (_a) {
            var isCollapsed = _a.isCollapsed;
            return ({ isCollapsed: !isCollapsed });
        });
    });
}
function ToggleVisibility(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.ToggleVisibility.subscribe(ctx, function (_a) {
        var state = _a.state, ref = _a.ref;
        return setSubtreeVisibility(state, ref, !state.cells.get(ref).state.isHidden);
    });
}
function setSubtreeVisibility(state, root, value) {
    _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateTree"].doPreOrder(state.tree, state.transforms.get(root), { state: state, value: value }, setVisibilityVisitor);
}
function setVisibilityVisitor(t, tree, ctx) {
    ctx.state.updateCellState(t.ref, { isHidden: ctx.value });
}
function Highlight(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].Interactivity.Object.Highlight.subscribe(ctx, function (_a) {
        var state = _a.state, ref = _a.ref;
        ctx.managers.interactivity.lociHighlights.clearHighlights();
        var refs = typeof ref === 'string' ? [ref] : ref;
        for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
            var r = refs_1[_i];
            var cell = state.cells.get(r);
            if (!cell)
                continue;
            if (_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].Molecule.Structure.is(cell.obj)) {
                ctx.managers.interactivity.lociHighlights.highlight({ loci: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].Loci(cell.obj.data) }, false);
            }
            else if (cell && _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].isRepresentation3D(cell.obj)) {
                var repr = cell.obj.data.repr;
                ctx.managers.interactivity.lociHighlights.highlight({ loci: repr.getLoci(), repr: repr }, false);
            }
            else if (_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_3__[/* PluginStateObject */ "a"].Molecule.Structure.Selections.is(cell.obj)) {
                for (var _b = 0, _c = cell.obj.data; _b < _c.length; _b++) {
                    var entry = _c[_b];
                    ctx.managers.interactivity.lociHighlights.highlight({ loci: entry.loci }, false);
                }
            }
        }
        // TODO: highlight volumes?
        // TODO: select structures of subtree?
    });
}
function ClearHighlights(ctx) {
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].Interactivity.ClearHighlights.subscribe(ctx, function () {
        ctx.managers.interactivity.lociHighlights.clearHighlights();
    });
}
function Snapshots(ctx) {
    var _this = this;
    ctx.config.set(_config__WEBPACK_IMPORTED_MODULE_9__["PluginConfig"].State.CurrentServer, ctx.config.get(_config__WEBPACK_IMPORTED_MODULE_9__["PluginConfig"].State.DefaultServer));
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Clear.subscribe(ctx, function () {
        ctx.managers.snapshot.clear();
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Remove.subscribe(ctx, function (_a) {
        var id = _a.id;
        ctx.managers.snapshot.remove(id);
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Add.subscribe(ctx, function (_a) {
        var name = _a.name, description = _a.description, params = _a.params;
        var entry = _mol_plugin_state_manager_snapshots__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateSnapshotManager */ "a"].Entry(ctx.state.getSnapshot(params), { name: name, description: description });
        ctx.managers.snapshot.add(entry);
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Replace.subscribe(ctx, function (_a) {
        var id = _a.id, params = _a.params;
        ctx.managers.snapshot.replace(id, ctx.state.getSnapshot(params));
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Move.subscribe(ctx, function (_a) {
        var id = _a.id, dir = _a.dir;
        ctx.managers.snapshot.move(id, dir);
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Apply.subscribe(ctx, function (_a) {
        var id = _a.id;
        var snapshot = ctx.managers.snapshot.setCurrent(id);
        if (!snapshot)
            return;
        return ctx.state.setSnapshot(snapshot);
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Upload.subscribe(ctx, function (_a) {
        var name = _a.name, description = _a.description, playOnLoad = _a.playOnLoad, serverUrl = _a.serverUrl, params = _a.params;
        return fetch(Object(_mol_util_url__WEBPACK_IMPORTED_MODULE_7__[/* urlCombine */ "a"])(serverUrl, "set?name=" + encodeURIComponent(name || '') + "&description=" + encodeURIComponent(description || '')), {
            method: 'POST',
            mode: 'cors',
            referrer: 'no-referrer',
            headers: { 'Content-Type': 'application/json; charset=utf-8' },
            body: JSON.stringify(ctx.managers.snapshot.getStateSnapshot({ name: name, description: description, playOnLoad: playOnLoad }))
        });
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.Fetch.subscribe(ctx, function (_a) {
        var url = _a.url;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var json;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, ctx.runTask(ctx.fetch({ url: url, type: 'json' }))];
                    case 1:
                        json = _b.sent();
                        return [4 /*yield*/, ctx.managers.snapshot.setStateSnapshot(json.data)];
                    case 2:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.DownloadToFile.subscribe(ctx, function (_a) {
        var name = _a.name, type = _a.type, params = _a.params;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var filename, data;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        filename = "mol-star_state_" + (name || Object(_mol_util_date__WEBPACK_IMPORTED_MODULE_5__["getFormattedTime"])()) + "." + (type === 'json' ? 'molj' : 'molx');
                        return [4 /*yield*/, ctx.managers.snapshot.serialize({ type: type, params: params })];
                    case 1:
                        data = _b.sent();
                        Object(_mol_util_download__WEBPACK_IMPORTED_MODULE_6__[/* download */ "a"])(data, "" + filename);
                        return [2 /*return*/];
                }
            });
        });
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.OpenFile.subscribe(ctx, function (_a) {
        var file = _a.file;
        return ctx.managers.snapshot.open(file);
    });
    _commands__WEBPACK_IMPORTED_MODULE_8__["PluginCommands"].State.Snapshots.OpenUrl.subscribe(ctx, function (_a) {
        var url = _a.url, type = _a.type;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var data;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, ctx.runTask(ctx.fetch({ url: url, type: 'binary' }))];
                    case 1:
                        data = _b.sent();
                        return [2 /*return*/, ctx.managers.snapshot.open(new File([data], "state." + type))];
                }
            });
        });
    });
}
//# sourceMappingURL=state.js.map

/***/ }),
/* 217 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return encodeFloatLog; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return decodeFloatLog; });
/* unused harmony export encodeFloatRGB */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return decodeFloatRGB; });
/* harmony import */ var _mol_math_interpolate__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(78);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var maxFloat = 10000.0; // NOTE same constant is set in shaders
var floatLogFactor = Math.log(maxFloat + 1.0);
/** encode float logarithmically */
function encodeFloatLog(value) { return Math.log(value + 1.0) / floatLogFactor; }
/** decode logarithmically encoded float */
function decodeFloatLog(value) { return Math.exp(value * floatLogFactor) - 1.0; }
/** encode float as normalized rgb triplet */
function encodeFloatRGB(value) {
    value = Object(_mol_math_interpolate__WEBPACK_IMPORTED_MODULE_0__[/* clamp */ "a"])(value, 0.0, 16777216.0 - 1.0) + 1.0;
    var b = (value % 256) / 255.0;
    value = Math.floor(value / 256.0);
    var g = (value % 256) / 255.0;
    value = Math.floor(value / 256.0);
    var r = (value % 256) / 255.0;
    return [r, g, b];
}
/** decode float encoded as rgb triplet */
function decodeFloatRGB(r, g, b) {
    return (Math.floor(r) * 256 * 256 + Math.floor(g) * 256 + Math.floor(b)) - 1;
}
//# sourceMappingURL=float-packing.js.map

/***/ }),
/* 218 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export InterpolationTypes */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return InterpolationTypeNames; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Image; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(9);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(53);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(5);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(33);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(117);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(125);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(142);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(29);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(143);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














var QuadIndices = new Uint32Array([
    0, 1, 2,
    1, 3, 2
]);
var QuadUvs = new Float32Array([
    0, 1,
    0, 0,
    1, 1,
    1, 0
]);
var InterpolationTypes = {
    'nearest': 'Nearest',
    'catmulrom': 'Catmulrom (Cubic)',
    'mitchell': 'Mitchell (Cubic)',
    'bspline': 'B-Spline (Cubic)'
};
var InterpolationTypeNames = Object.keys(InterpolationTypes);

var Image;
(function (Image) {
    function create(imageTexture, corners, groupTexture, image) {
        return image ?
            update(imageTexture, corners, groupTexture, image) :
            fromData(imageTexture, corners, groupTexture);
    }
    Image.create = create;
    function hashCode(image) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_1__[/* hashFnv32a */ "l"])([
            image.cornerBuffer.ref.version
        ]);
    }
    function fromData(imageTexture, corners, groupTexture) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"])();
        var currentHash = -1;
        var width = imageTexture.width;
        var height = imageTexture.height;
        var image = {
            kind: 'image',
            imageTexture: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(imageTexture),
            imageTextureDim: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec2"].create(width, height)),
            cornerBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(corners),
            groupTexture: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(groupTexture),
            get boundingSphere() {
                var newHash = hashCode(image);
                if (newHash !== currentHash) {
                    var b = getBoundingSphere(image.cornerBuffer.ref.value);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
        };
        return image;
    }
    function update(imageTexture, corners, groupTexture, image) {
        var width = imageTexture.width;
        var height = imageTexture.height;
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(image.imageTexture, imageTexture);
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(image.imageTextureDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec2"].set(image.imageTextureDim.ref.value, width, height));
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(image.cornerBuffer, corners);
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(image.groupTexture, groupTexture);
        return image;
    }
    function createEmpty(image) {
        return {}; // TODO
    }
    Image.createEmpty = createEmpty;
    Image.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].Params), { interpolation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].Select('bspline', _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].objectToOptions(InterpolationTypes)) });
    Image.Utils = {
        Params: Image.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: createRenderableState,
        updateRenderableState: updateRenderableState
    };
    function createValues(image, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_8__[/* createColors */ "a"])(locationIt, theme.color);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_9__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_10__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_11__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_13__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: QuadIndices.length, groupCount: groupCount, instanceCount: instanceCount };
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].clone(image.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, color), marker), overpaint), transparency), clipping), transform), _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].createValues(props, counts)), { aPosition: image.cornerBuffer, aUv: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(QuadUvs), elements: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(QuadIndices),
            // aGroup is used as a vertex index here, group id is in tGroupTex
            aGroup: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_12__["fillSerial"])(new Float32Array(4))), boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec4"].ofSphere(invariantBoundingSphere)), dInterpolation: _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].create(props.interpolation), uImageTexDim: image.imageTextureDim, tImageTex: image.imageTexture, tGroupTex: image.groupTexture });
    }
    function createValuesSimple(image, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].getDefaultValues(Image.Params)), props);
        return createValues(image, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].updateIfChanged(values.dInterpolation, props.interpolation);
    }
    function updateBoundingSphere(values, image) {
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].clone(image.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_5__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
    function createRenderableState(props) {
        var state = _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].createRenderableState(props);
        state.opaque = false;
        return state;
    }
    function updateRenderableState(state, props) {
        _base__WEBPACK_IMPORTED_MODULE_7__[/* BaseGeometry */ "a"].updateRenderableState(state, props);
        state.opaque = false;
    }
})(Image || (Image = {}));
//
function getBoundingSphere(corners) {
    return Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_2__[/* calculateInvariantBoundingSphere */ "a"])(corners, corners.length / 3, 1);
}
//# sourceMappingURL=image.js.map

/***/ }),
/* 219 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Types; });
/* harmony import */ var _type__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(15);
/* harmony import */ var _core__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(202);
/* harmony import */ var _symbol__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(18);
/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(42);
/**
 * Copyright (c) 2018-2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var Types;
(function (Types) {
    Types.ElementSymbol = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'ElementSymbol');
    Types.AtomName = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'AtomName');
    Types.BondFlag = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].OneOf('Structure', 'BondFlag', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, ['covalent', 'metallic', 'ion', 'hydrogen', 'sulfide', 'computed', 'aromatic']);
    Types.BondFlags = _core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].Flags(Types.BondFlag, 'BondFlags');
    Types.SecondaryStructureFlag = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].OneOf('Structure', 'SecondaryStructureFlag', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, ['alpha', 'beta', '3-10', 'pi', 'sheet', 'strand', 'helix', 'turn', 'none']);
    Types.SecondaryStructureFlags = _core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].Flags(Types.SecondaryStructureFlag, 'SecondaryStructureFlag');
    Types.RingFingerprint = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'RingFingerprint');
    Types.EntityType = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].OneOf('Structure', 'EntityType', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, ['polymer', 'non-polymer', 'water', 'branched']);
    Types.EntitySubtype = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].OneOf('Structure', 'EntitySubtype', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, ['other', 'polypeptide(D)', 'polypeptide(L)', 'polydeoxyribonucleotide', 'polyribonucleotide', 'polydeoxyribonucleotide/polyribonucleotide hybrid', 'cyclic-pseudo-peptide', 'peptide nucleic acid', 'oligosaccharide']);
    Types.ObjectPrimitive = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].OneOf('Structure', 'ObjectPrimitive', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, ['atomistic', 'sphere', 'gaussian', 'other']);
    Types.ResidueId = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'ResidueId');
    Types.ElementSet = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'ElementSet');
    Types.ElementSelection = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'ElementSelection');
    Types.ElementReference = _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Value('Structure', 'ElementReference');
    Types.ElementSelectionQuery = _core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].Fn(Types.ElementSelection, 'ElementSelectionQuery');
})(Types || (Types = {}));
var type = {
    '@header': 'Types',
    elementSymbol: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str) }), Types.ElementSymbol, 'Create element symbol representation from a string value.'),
    atomName: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue) }), Types.AtomName, 'Convert a value to an atom name.'),
    entityType: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.EntityType) }), Types.EntityType, "Create normalized representation of entity type: " + _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].oneOfValues(Types.EntityType).join(', ') + "."),
    bondFlags: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].List(Types.BondFlag), Types.BondFlags, "Create bond flags representation from a list of strings. Allowed flags: " + _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].oneOfValues(Types.BondFlag).join(', ') + "."),
    ringFingerprint: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].List(Types.ElementSymbol, { nonEmpty: true }), Types.RingFingerprint, 'Create ring fingerprint from the supplied atom element list.'),
    secondaryStructureFlags: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].List(Types.SecondaryStructureFlag), Types.SecondaryStructureFlags, "Create secondary structure flags representation from a list of strings. Allowed flags: " + _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].oneOfValues(Types.SecondaryStructureFlag).join(', ') + "."),
    authResidueId: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'auth_asym_id' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'auth_seq_id' }),
        2: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'pdbx_PDB_ins_code', isOptional: true })
    }), Types.ResidueId, "Residue identifier based on \"auth_\" annotation."),
    labelResidueId: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'label_entity_id' }),
        1: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'label_asym_id' }),
        2: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'label_seq_id' }),
        3: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, { description: 'pdbx_PDB_ins_code', isOptional: true })
    }), Types.ResidueId, "Residue identifier based on mmCIF's \"label_\" annotation.")
};
var slot = {
    '@header': 'Iteration Slots',
    element: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, Types.ElementReference, 'A reference to the current element.'),
    elementSetReduce: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), 'Current value of the element set reducer.')
};
var generator = {
    '@header': 'Generators',
    all: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, Types.ElementSelectionQuery, 'The entire structure.'),
    atomGroups: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        'entity-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: true, description: 'Test for the 1st atom of every entity' }),
        'chain-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: true, description: 'Test for the 1st atom of every chain' }),
        'residue-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: true, description: 'Test for the 1st atom every residue' }),
        'atom-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: true }),
        'group-by': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any, { isOptional: true, defaultValue: "atom-key", description: 'Group atoms to sets based on this property. Default: each atom has its own set' }),
    }), Types.ElementSelectionQuery, 'Return all atoms for which the tests are satisfied, grouped into sets.'),
    bondedAtomicPairs: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: 'true for covalent bonds', description: 'Test each bond with this predicate. Each bond is visited twice with swapped atom order.' }),
    }), Types.ElementSelectionQuery, 'Return all pairs of atoms for which the test is satisfied.'),
    rings: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        'fingerprint': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.RingFingerprint, { isOptional: true }),
        'only-aromatic': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: false }),
    }), Types.ElementSelectionQuery, 'Return all rings or those with the specified fingerprint and/or only aromatic rings.'),
    queryInSelection: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        query: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        'in-complement': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: false })
    }), Types.ElementSelectionQuery, 'Executes query only on atoms that are in the source selection.'),
    empty: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, Types.ElementSelectionQuery, 'Nada.'),
};
var modifier = {
    '@header': 'Selection Modifications',
    queryEach: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        query: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'Query every atom set in the input selection separately.'),
    intersectBy: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        by: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'Intersect each atom set from the first sequence from atoms in the second one.'),
    exceptBy: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        by: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, "Remove all atoms from 'selection' that occur in 'by'."),
    unionBy: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        by: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'For each atom set A in the orginal sequence, combine all atoms sets in the target selection that intersect with A.'),
    union: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'Collects all atom sets in the sequence into a single atom set.'),
    cluster: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        'min-distance': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { isOptional: true, defaultValue: 0 }),
        'max-distance': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        'min-size': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'Minimal number of sets to merge, must be at least 2', isOptional: true, defaultValue: 2 }),
        'max-size': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { description: 'Maximal number of sets to merge, if not set, no limit', isOptional: true }),
    }), Types.ElementSelectionQuery, 'Combines atom sets that have mutual distance in the interval [min-radius, max-radius]. Minimum/maximum size determines how many atom sets can be combined.'),
    includeSurroundings: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        radius: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        'atom-radius': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { isOptional: true, defaultValue: 0, description: 'Value added to each atom before the distance check, for example VDW radius. Using this argument is computationally demanding.' }),
        'as-whole-residues': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true })
    }), Types.ElementSelectionQuery, 'For each atom set in the selection, include all surrouding atoms/residues that are within the specified radius.'),
    includeConnected: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        'bond-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: 'true for covalent bonds' }),
        'layer-count': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { isOptional: true, defaultValue: 1, description: 'Number of bonded layers to include.' }),
        'as-whole-residues': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true })
    }), Types.ElementSelectionQuery, 'Pick all atom sets that are connected to the target.'),
    wholeResidues: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
    }), Types.ElementSelectionQuery, 'Expand the selection to whole residues.'),
    expandProperty: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        property: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue)
    }), Types.ElementSelectionQuery, 'To each atom set in the selection, add all atoms that have the same property value that was already present in the set.')
};
var filter = {
    '@header': 'Selection Filters',
    pick: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        test: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool)
    }), Types.ElementSelectionQuery, 'Pick all atom sets that satisfy the test.'),
    first: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'Take the 1st atom set in the sequence.'),
    withSameAtomProperties: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        source: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        property: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Any)
    }), Types.ElementSelectionQuery, 'Pick all atom sets for which the set of given atom properties is a subset of the source properties.'),
    intersectedBy: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        by: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), Types.ElementSelectionQuery, 'Pick all atom sets that have non-zero intersection with the target.'),
    within: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        target: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        'min-radius': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { isOptional: true, defaultValue: 0 }),
        'max-radius': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        'atom-radius': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, { isOptional: true, defaultValue: 0, description: 'Value added to each atom before the distance check, for example VDW radius. Using this argument is computationally demanding.' }),
        invert: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: false, description: 'If true, pick only atom sets that are further than the specified radius.' }),
    }), Types.ElementSelectionQuery, 'Pick all atom sets from selection that have any atom within the radius of any atom from target.'),
    isConnectedTo: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        target: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery),
        'bond-test': Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: 'true for covalent bonds' }),
        disjunct: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: true, description: 'If true, there must exist a bond to an atom that lies outside the given atom set to pass test.' }),
        invert: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, { isOptional: true, defaultValue: false, description: 'If true, return atom sets that are not connected.' })
    }), Types.ElementSelectionQuery, 'Pick all atom sets that are connected to the target.'),
};
var combinator = {
    '@header': 'Selection Combinators',
    intersect: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].List(Types.ElementSelectionQuery), Types.ElementSelectionQuery, 'Return all unique atom sets that appear in all of the source selections.'),
    merge: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].List(Types.ElementSelectionQuery), Types.ElementSelectionQuery, 'Merges multiple selections into a single one. Only unique atom sets are kept.'),
    distanceCluster: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        matrix: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].List(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].List(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num)), { description: 'Distance matrix, represented as list of rows (num[][])). Lower triangle is min distance, upper triangle is max distance.' }),
        selections: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].List(Types.ElementSelectionQuery), { description: 'A list of held selections.' })
    }), Types.ElementSelectionQuery, 'Pick combinations of atom sets from the source sequences that are mutually within distances specified by a matrix.')
};
var atomSet = {
    '@header': 'Atom Sets',
    atomCount: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    countQuery: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementSelectionQuery)
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Counts the number of occurences of a specific query inside the current atom set.'),
    reduce: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        initial: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), { description: 'Initial value assigned to slot.atom-set-reduce. Current atom is set to the 1st atom of the current set for this.' }),
        value: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), { description: 'Expression executed for each atom in the set' })
    }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Variable('a', _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, true), 'Execute the value expression for each atom in the current atom set and return the result. Works the same way as Array.reduce in JavaScript (``result = value(value(...value(initial)))``)'),
    propertySet: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
        0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].ConstrainedVar),
    }), _core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].Set(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].ConstrainedVar), 'Returns a set with all values of the given property in the current atom set.'),
};
var atomProperty = {
    '@header': 'Atom Properties',
    core: {
        '@header': 'Core Properties',
        elementSymbol: atomProp(Types.ElementSymbol),
        vdw: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Van der Waals radius'),
        mass: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Atomic weight'),
        atomicNumber: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Atomic number'),
        x: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Cartesian X coordinate'),
        y: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Cartesian Y coordinate'),
        z: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Cartesian Z coordinate'),
        atomKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each atom. Main use case is grouping of atoms.'),
        bondCount: Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({
            0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementReference, { isOptional: true, defaultValue: 'slot.current-atom' }),
            flags: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.BondFlags, { isOptional: true, defaultValue: 'covalent' }),
        }), _type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Number of bonds (by default only covalent bonds are counted).'),
        sourceIndex: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Index of the atom/element in the input file.'),
        operatorName: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, 'Name of the symmetry operator applied to this element.'),
        modelIndex: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, 'Index of the model in the input file.'),
        modelLabel: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, 'Label/header of the model in the input file.')
    },
    topology: {
        connectedComponentKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each connected component.')
    },
    macromolecular: {
        '@header': 'Macromolecular Properties (derived from the mmCIF format)',
        authResidueId: atomProp(Types.ResidueId, "type.auth-residue-id symbol executed on current atom's residue"),
        labelResidueId: atomProp(Types.ResidueId, "type.label-residue-id symbol executed on current atom's residue"),
        residueKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each tuple ``(label_entity_id,auth_asym_id, auth_seq_id, pdbx_PDB_ins_code)``, main use case is grouping of atoms'),
        chainKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each tuple ``(label_entity_id, auth_asym_id)``, main use case is grouping of atoms'),
        entityKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each tuple ``label_entity_id``, main use case is grouping of atoms'),
        isHet: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'Equivalent to atom_site.group_PDB !== ATOM'),
        id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num, '_atom_site.id'),
        label_atom_id: atomProp(Types.AtomName),
        label_alt_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        label_comp_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        label_asym_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        label_entity_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        label_seq_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        auth_atom_id: atomProp(Types.AtomName),
        auth_comp_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        auth_asym_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        auth_seq_id: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        pdbx_PDB_ins_code: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str),
        pdbx_formal_charge: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        occupancy: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        B_iso_or_equiv: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
        entityType: atomProp(Types.EntityType, 'Type of the entity as defined in mmCIF (polymer, non-polymer, branched, water)'),
        entitySubtype: atomProp(Types.EntitySubtype, 'Subtype of the entity as defined in mmCIF _entity_poly.type and _pdbx_entity_branch.type (other, polypeptide(D), polypeptide(L), polydeoxyribonucleotide, polyribonucleotide, polydeoxyribonucleotide/polyribonucleotide hybrid, cyclic-pseudo-peptide, peptide nucleic acid, oligosaccharide)'),
        entityPrdId: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, "The PRD ID of the entity."),
        entityDescription: atomProp(_core__WEBPACK_IMPORTED_MODULE_1__[/* Types */ "a"].List(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str)),
        objectPrimitive: atomProp(Types.ObjectPrimitive, 'Type of the primitive object used to model this segment as defined in mmCIF/IHM (atomistic, sphere, gaussian, other)'),
        secondaryStructureKey: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].AnyValue, 'Unique value for each secondary structure element.'),
        secondaryStructureFlags: atomProp(Types.SecondaryStructureFlags),
        isModified: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'True if the atom belongs to modification of a standard residue.'),
        modifiedParentName: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, "'3-letter' code of the modifed parent residue."),
        isNonStandard: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Bool, 'True if this is a non-standard residue.'),
        chemCompType: atomProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Str, "Type of the chemical component as defined in mmCIF."),
    }
};
var bondProperty = {
    '@header': 'Bond Properties',
    flags: bondProp(Types.BondFlags),
    order: bondProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    length: bondProp(_type__WEBPACK_IMPORTED_MODULE_0__[/* default */ "a"].Num),
    atomA: bondProp(Types.ElementReference),
    atomB: bondProp(Types.ElementReference)
};
function atomProp(type, description) {
    return Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].Dictionary({ 0: Object(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Argument */ "a"])(Types.ElementReference, { isOptional: true, defaultValue: 'slot.current-atom' }) }), type, description);
}
function bondProp(type, description) {
    return Object(_helpers__WEBPACK_IMPORTED_MODULE_3__[/* symbol */ "b"])(_symbol__WEBPACK_IMPORTED_MODULE_2__[/* Arguments */ "b"].None, type, description);
}
/* harmony default export */ __webpack_exports__["b"] = ({
    '@header': 'Structure Queries',
    type: type,
    slot: slot,
    generator: generator,
    modifier: modifier,
    filter: filter,
    combinator: combinator,
    atomSet: atomSet,
    atomProperty: atomProperty,
    bondProperty: bondProperty
});
//# sourceMappingURL=structure-query.js.map

/***/ }),
/* 220 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return EmptyError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var EmptyErrorImpl = /*@__PURE__*/ (function () {
    function EmptyErrorImpl() {
        Error.call(this);
        this.message = 'no elements in sequence';
        this.name = 'EmptyError';
        return this;
    }
    EmptyErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return EmptyErrorImpl;
})();
var EmptyError = EmptyErrorImpl;
//# sourceMappingURL=EmptyError.js.map


/***/ }),
/* 221 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return MeasurementRepresentationCommonTextParams; });
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(47);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var MeasurementRepresentationCommonTextParams = {
    customText: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__["ParamDefinition"].Text('', { label: 'Text', description: 'Override the label with custom value.' }),
    textColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_1__[/* ColorNames */ "a"].black, { isEssential: true }),
    textSize: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__["ParamDefinition"].Numeric(0.5, { min: 0.1, max: 5, step: 0.1 }, { isEssential: true }),
};
//# sourceMappingURL=common.js.map

/***/ }),
/* 222 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ComplexRepresentation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(54);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(115);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(89);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(16);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(23);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(45);
/* harmony import */ var _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(130);
/* harmony import */ var _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(77);
/* harmony import */ var _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(131);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */













function ComplexRepresentation(label, ctx, getParams, visualCtor) {
    var version = 0;
    var updated = new rxjs__WEBPACK_IMPORTED_MODULE_4__[/* Subject */ "a"]();
    var materialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_5__[/* getNextMaterialId */ "c"])();
    var renderObjects = [];
    var _state = _representation__WEBPACK_IMPORTED_MODULE_2__[/* StructureRepresentationStateBuilder */ "c"].create();
    var visual;
    var _structure;
    var _params;
    var _props;
    var _theme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_6__[/* Theme */ "a"].createEmpty();
    function createOrUpdate(props, structure) {
        var _this = this;
        if (props === void 0) { props = {}; }
        if (structure && structure !== _structure) {
            _params = getParams(ctx, structure);
            _structure = structure;
            if (!_props)
                _props = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(_params);
        }
        _props = Object.assign({}, _props, props);
        return _mol_task__WEBPACK_IMPORTED_MODULE_7__[/* Task */ "b"].create('Creating or updating ComplexRepresentation', function (runtime) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var newVisual, promise;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        newVisual = false;
                        if (!visual) {
                            visual = visualCtor(materialId);
                            newVisual = true;
                        }
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, structure);
                        if (!promise) return [3 /*break*/, 2];
                        return [4 /*yield*/, promise];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (newVisual) {
                            // ensure state is current for new visual
                            setState(_state);
                        }
                        // update list of renderObjects
                        renderObjects.length = 0;
                        if (visual && visual.renderObject)
                            renderObjects.push(visual.renderObject);
                        // increment version
                        updated.next(version++);
                        return [2 /*return*/];
                }
            });
        }); });
    }
    function getLoci(pickingId) {
        if (pickingId === undefined)
            return _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Loci(_structure);
        return visual ? visual.getLoci(pickingId) : _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["EmptyLoci"];
    }
    function mark(loci, action) {
        if (!_structure)
            return false;
        if (!_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_9__[/* MarkerActions */ "b"].is(_state.markerActions, action))
            return false;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].isLoci(loci) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Loci.is(loci) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Bond"].isLoci(loci)) {
            if (!_mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].areRootsEquivalent(loci.structure, _structure))
                return false;
            // Remap `loci` from equivalent structure to the current `_structure`
            loci = _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["Loci"].remap(loci, _structure);
        }
        else if (!Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isEveryLoci"])(loci) && !Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isDataLoci"])(loci)) {
            return false;
        }
        if (_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["Loci"].isEmpty(loci))
            return false;
        return visual ? visual.mark(loci, action) : false;
    }
    function setState(state) {
        _representation__WEBPACK_IMPORTED_MODULE_2__[/* StructureRepresentationStateBuilder */ "c"].update(_state, state);
        if (state.visible !== undefined && visual) {
            // hide visual when _unitTransforms is set and not the identity
            visual.setVisibility(state.visible && (_state.unitTransforms === null || _state.unitTransforms.isIdentity));
        }
        if (state.alphaFactor !== undefined && visual)
            visual.setAlphaFactor(state.alphaFactor);
        if (state.pickable !== undefined && visual)
            visual.setPickable(state.pickable);
        if (state.overpaint !== undefined && visual) {
            // Remap loci from equivalent structure to the current structure
            var remappedOverpaint = _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_10__[/* Overpaint */ "a"].remap(state.overpaint, _structure);
            visual.setOverpaint(remappedOverpaint);
        }
        if (state.transparency !== undefined && visual) {
            // Remap loci from equivalent structure to the current structure
            var remappedTransparency = _mol_theme_transparency__WEBPACK_IMPORTED_MODULE_12__[/* Transparency */ "a"].remap(state.transparency, _structure);
            visual.setTransparency(remappedTransparency);
        }
        if (state.clipping !== undefined && visual) {
            // Remap loci from equivalent structure to the current structure
            var remappedClipping = _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_11__[/* Clipping */ "a"].remap(state.clipping, _structure);
            visual.setClipping(remappedClipping);
        }
        if (state.transform !== undefined && visual)
            visual.setTransform(state.transform);
        if (state.unitTransforms !== undefined && visual) {
            // Since ComplexVisuals always renders geometries between units, the application
            // of `unitTransforms` does not make sense. When given here and not the identity,
            // it is ignored and sets the visual's visibility to `false`.
            visual.setVisibility(_state.visible && (state.unitTransforms === null || state.unitTransforms.isIdentity));
        }
    }
    function setTheme(theme) {
        _theme = theme;
    }
    function destroy() {
        if (visual)
            visual.destroy();
    }
    return {
        label: label,
        get groupCount() {
            return visual ? visual.groupCount : 0;
        },
        get props() { return _props; },
        get params() { return _params; },
        get state() { return _state; },
        get theme() { return _theme; },
        renderObjects: renderObjects,
        updated: updated,
        createOrUpdate: createOrUpdate,
        setState: setState,
        setTheme: setTheme,
        getLoci: getLoci,
        mark: mark,
        destroy: destroy
    };
}
//# sourceMappingURL=complex-representation.js.map

/***/ }),
/* 223 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "HighlightLoci", function() { return HighlightLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SelectLoci", function() { return SelectLoci; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "DefaultLociLabelProvider", function() { return DefaultLociLabelProvider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "FocusLoci", function() { return FocusLoci; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(45);
/* harmony import */ var _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _mol_theme_label__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(72);
/* harmony import */ var _behavior__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(68);
/* harmony import */ var _mol_state_tree_spine__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(303);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(13);
/* harmony import */ var _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(84);
/* harmony import */ var _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(59);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(2);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(23);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(4);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(29);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var B = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_7__[/* ButtonsType */ "a"];
var M = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_7__[/* ModifiersKeys */ "b"];
var Trigger = _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].Trigger;
//
var DefaultHighlightLociBindings = {
    hoverHighlightOnly: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([Trigger(0 /* None */)], 'Highlight', 'Hover element using ${triggers}'),
    hoverHighlightOnlyExtend: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([Trigger(0 /* None */, M.create({ shift: true }))], 'Extend highlight', 'From selected to hovered element along polymer using ${triggers}'),
};
var HighlightLociParams = {
    bindings: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Value(DefaultHighlightLociBindings, { isHidden: true }),
};
var HighlightLoci = _behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].create({
    name: 'representation-highlight-loci',
    category: 'interaction',
    ctor: /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.lociMarkProvider = function (interactionLoci, action) {
                if (!_this.ctx.canvas3d)
                    return;
                _this.ctx.canvas3d.mark({ loci: interactionLoci.loci }, action);
            };
            return _this;
        }
        class_1.prototype.register = function () {
            var _this = this;
            this.subscribeObservable(this.ctx.behaviors.interaction.hover, function (_a) {
                var current = _a.current, buttons = _a.buttons, modifiers = _a.modifiers;
                if (!_this.ctx.canvas3d || _this.ctx.isBusy)
                    return;
                var matched = false;
                if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].match(_this.params.bindings.hoverHighlightOnly, buttons, modifiers)) {
                    _this.ctx.managers.interactivity.lociHighlights.highlightOnly(current);
                    matched = true;
                }
                if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].match(_this.params.bindings.hoverHighlightOnlyExtend, buttons, modifiers)) {
                    _this.ctx.managers.interactivity.lociHighlights.highlightOnlyExtend(current);
                    matched = true;
                }
                if (!matched) {
                    _this.ctx.managers.interactivity.lociHighlights.highlightOnly({ repr: current.repr, loci: _mol_model_loci__WEBPACK_IMPORTED_MODULE_10__["EmptyLoci"] });
                }
            });
            this.ctx.managers.interactivity.lociHighlights.addProvider(this.lociMarkProvider);
        };
        class_1.prototype.unregister = function () {
            this.ctx.managers.interactivity.lociHighlights.removeProvider(this.lociMarkProvider);
        };
        return class_1;
    }(_behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].Handler)),
    params: function () { return HighlightLociParams; },
    display: { name: 'Highlight Loci on Canvas' }
});
//
var DefaultSelectLociBindings = {
    clickSelect: _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].Empty,
    clickToggleExtend: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([Trigger(1 /* Primary */, M.create({ shift: true }))], 'Toggle extended selection', '${triggers} to extend selection along polymer'),
    clickSelectOnly: _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].Empty,
    clickToggle: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([Trigger(1 /* Primary */, M.create())], 'Toggle selection', '${triggers} on element'),
    clickDeselect: _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].Empty,
    clickDeselectAllOnEmpty: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([Trigger(1 /* Primary */, M.create())], 'Deselect all', 'Click on nothing using ${triggers}'),
};
var SelectLociParams = {
    bindings: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Value(DefaultSelectLociBindings, { isHidden: true }),
};
var SelectLoci = _behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].create({
    name: 'representation-select-loci',
    category: 'interaction',
    ctor: /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(class_2, _super);
        function class_2(ctx, params) {
            var _this = _super.call(this, ctx, params) || this;
            _this.lociMarkProvider = function (reprLoci, action) {
                if (!_this.ctx.canvas3d)
                    return;
                _this.ctx.canvas3d.mark({ loci: reprLoci.loci }, action);
            };
            _this.spine = new _mol_state_tree_spine__WEBPACK_IMPORTED_MODULE_5__[/* StateTreeSpine */ "a"].Impl(ctx.state.data.cells);
            return _this;
        }
        class_2.prototype.applySelectMark = function (ref, clear) {
            var cell = this.ctx.state.data.cells.get(ref);
            if (cell && _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateObject */ "a"].isRepresentation3D(cell.obj)) {
                this.spine.current = cell;
                var so = this.spine.getRootOfType(_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateObject */ "a"].Molecule.Structure);
                if (so) {
                    if (clear) {
                        this.lociMarkProvider({ loci: _mol_model_structure__WEBPACK_IMPORTED_MODULE_11__["Structure"].Loci(so.data) }, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__[/* MarkerAction */ "a"].Deselect);
                    }
                    var loci = this.ctx.managers.structure.selection.getLoci(so.data);
                    this.lociMarkProvider({ loci: loci }, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_1__[/* MarkerAction */ "a"].Select);
                }
            }
        };
        class_2.prototype.register = function () {
            var _this = this;
            var lociIsEmpty = function (current) { return _mol_model_loci__WEBPACK_IMPORTED_MODULE_10__["Loci"].isEmpty(current.loci); };
            var lociIsNotEmpty = function (current) { return !_mol_model_loci__WEBPACK_IMPORTED_MODULE_10__["Loci"].isEmpty(current.loci); };
            var actions = [
                ['clickSelect', function (current) { return _this.ctx.managers.interactivity.lociSelects.select(current); }, lociIsNotEmpty],
                ['clickToggle', function (current) { return _this.ctx.managers.interactivity.lociSelects.toggle(current); }, lociIsNotEmpty],
                ['clickToggleExtend', function (current) { return _this.ctx.managers.interactivity.lociSelects.toggleExtend(current); }, lociIsNotEmpty],
                ['clickSelectOnly', function (current) { return _this.ctx.managers.interactivity.lociSelects.selectOnly(current); }, lociIsNotEmpty],
                ['clickDeselect', function (current) { return _this.ctx.managers.interactivity.lociSelects.deselect(current); }, lociIsNotEmpty],
                ['clickDeselectAllOnEmpty', function () { return _this.ctx.managers.interactivity.lociSelects.deselectAll(); }, lociIsEmpty],
            ];
            // sort the action so that the ones with more modifiers trigger sooner.
            actions.sort(function (a, b) {
                var x = _this.params.bindings[a[0]], y = _this.params.bindings[b[0]];
                var k = x.triggers.length === 0 ? 0 : Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_12__["arrayMax"])(x.triggers.map(function (t) { return M.size(t.modifiers); }));
                var l = y.triggers.length === 0 ? 0 : Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_12__["arrayMax"])(y.triggers.map(function (t) { return M.size(t.modifiers); }));
                return l - k;
            });
            this.subscribeObservable(this.ctx.behaviors.interaction.click, function (_a) {
                var current = _a.current, button = _a.button, modifiers = _a.modifiers;
                if (!_this.ctx.canvas3d || _this.ctx.isBusy || !_this.ctx.selectionMode)
                    return;
                // only trigger the 1st action that matches
                for (var _i = 0, actions_1 = actions; _i < actions_1.length; _i++) {
                    var _b = actions_1[_i], binding = _b[0], action = _b[1], condition = _b[2];
                    if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].match(_this.params.bindings[binding], button, modifiers) && (!condition || condition(current))) {
                        action(current);
                        break;
                    }
                }
            });
            this.ctx.managers.interactivity.lociSelects.addProvider(this.lociMarkProvider);
            this.subscribeObservable(this.ctx.state.events.object.created, function (_a) {
                var ref = _a.ref;
                return _this.applySelectMark(ref);
            });
            // re-apply select-mark to all representation of an updated structure
            this.subscribeObservable(this.ctx.state.events.object.updated, function (_a) {
                var ref = _a.ref;
                var cell = _this.ctx.state.data.cells.get(ref);
                if (cell && _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateObject */ "a"].Molecule.Structure.is(cell.obj)) {
                    var reprs = _this.ctx.state.data.select(_mol_state__WEBPACK_IMPORTED_MODULE_6__["StateSelection"].Generators.ofType(_mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateObject */ "a"].Molecule.Structure.Representation3D, ref));
                    for (var _i = 0, reprs_1 = reprs; _i < reprs_1.length; _i++) {
                        var repr = reprs_1[_i];
                        _this.applySelectMark(repr.transform.ref, true);
                    }
                }
            });
        };
        class_2.prototype.unregister = function () {
            this.ctx.managers.interactivity.lociSelects.removeProvider(this.lociMarkProvider);
        };
        return class_2;
    }(_behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].Handler)),
    params: function () { return SelectLociParams; },
    display: { name: 'Select Loci on Canvas' }
});
//
var DefaultLociLabelProvider = _behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].create({
    name: 'default-loci-label-provider',
    category: 'interaction',
    ctor: /** @class */ (function () {
        function class_3(ctx) {
            this.ctx = ctx;
            this.f = {
                label: function (loci) {
                    var label = [];
                    if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_11__["StructureElement"].Loci.is(loci) && loci.elements.length === 1) {
                        var u = loci.elements[0].unit;
                        var l = _mol_model_structure__WEBPACK_IMPORTED_MODULE_11__["StructureElement"].Location.create(loci.structure, u, u.elements[0]);
                        var name_1 = _mol_model_structure__WEBPACK_IMPORTED_MODULE_11__["StructureProperties"].entity.pdbx_description(l).join(', ');
                        label.push(name_1);
                    }
                    label.push(Object(_mol_theme_label__WEBPACK_IMPORTED_MODULE_3__["lociLabel"])(loci));
                    return label.filter(function (l) { return !!l; }).join('</br>');
                },
                group: function (label) { return label.toString().replace(/Model [0-9]+/g, 'Models'); },
                priority: 100
            };
        }
        class_3.prototype.register = function () { this.ctx.managers.lociLabels.addProvider(this.f); };
        class_3.prototype.unregister = function () { this.ctx.managers.lociLabels.removeProvider(this.f); };
        return class_3;
    }()),
    display: { name: 'Provide Default Loci Label' }
});
//
var DefaultFocusLociBindings = {
    clickFocus: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([
        Trigger(1 /* Primary */, M.create()),
    ], 'Representation Focus', 'Click element using ${triggers}'),
    clickFocusAdd: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([
        Trigger(1 /* Primary */, M.create({ shift: true })),
    ], 'Representation Focus Add', 'Click element using ${triggers}'),
    clickFocusSelectMode: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([
    // default is empty
    ], 'Representation Focus', 'Click element using ${triggers}'),
    clickFocusAddSelectMode: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"])([
    // default is empty
    ], 'Representation Focus Add', 'Click element using ${triggers}'),
};
var FocusLociParams = {
    bindings: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_9__["ParamDefinition"].Value(DefaultFocusLociBindings, { isHidden: true }),
};
var FocusLoci = _behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].create({
    name: 'representation-focus-loci',
    category: 'interaction',
    ctor: /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(class_4, _super);
        function class_4() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        class_4.prototype.register = function () {
            var _this = this;
            this.subscribeObservable(this.ctx.behaviors.interaction.click, function (_a) {
                var _b;
                var current = _a.current, button = _a.button, modifiers = _a.modifiers;
                var _c = _this.params.bindings, clickFocus = _c.clickFocus, clickFocusAdd = _c.clickFocusAdd, clickFocusSelectMode = _c.clickFocusSelectMode, clickFocusAddSelectMode = _c.clickFocusAddSelectMode;
                // only apply structure focus for appropriate granularity
                var granularity = _this.ctx.managers.interactivity.props.granularity;
                if (granularity !== 'residue' && granularity !== 'element')
                    return;
                var binding = _this.ctx.selectionMode ? clickFocusSelectMode : clickFocus;
                var matched = _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].match(binding, button, modifiers);
                var bindingAdd = _this.ctx.selectionMode ? clickFocusAddSelectMode : clickFocusAdd;
                var matchedAdd = _mol_util_binding__WEBPACK_IMPORTED_MODULE_8__[/* Binding */ "a"].match(bindingAdd, button, modifiers);
                if (!matched && !matchedAdd)
                    return;
                var loci = _mol_model_loci__WEBPACK_IMPORTED_MODULE_10__["Loci"].normalize(current.loci, 'residue');
                var entry = _this.ctx.managers.structure.focus.current;
                if (entry && _mol_model_loci__WEBPACK_IMPORTED_MODULE_10__["Loci"].areEqual(entry.loci, loci)) {
                    _this.ctx.managers.structure.focus.clear();
                }
                else {
                    if (matched) {
                        _this.ctx.managers.structure.focus.setFromLoci(loci);
                    }
                    else {
                        _this.ctx.managers.structure.focus.addFromLoci(loci);
                        // focus-add is not handled in camera behavior, doing it here
                        var current_1 = (_b = _this.ctx.managers.structure.focus.current) === null || _b === void 0 ? void 0 : _b.loci;
                        if (current_1)
                            _this.ctx.managers.camera.focusLoci(current_1);
                    }
                }
            });
        };
        return class_4;
    }(_behavior__WEBPACK_IMPORTED_MODULE_4__["PluginBehavior"].Handler)),
    params: function () { return FocusLociParams; },
    display: { name: 'Representation Focus Loci on Canvas' }
});
//# sourceMappingURL=representation.js.map

/***/ }),
/* 224 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return fromArray; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(374);
/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(311);
/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */



function fromArray(input, scheduler) {
    if (!scheduler) {
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](Object(_util_subscribeToArray__WEBPACK_IMPORTED_MODULE_1__[/* subscribeToArray */ "a"])(input));
    }
    else {
        return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__[/* scheduleArray */ "a"])(input, scheduler);
    }
}
//# sourceMappingURL=fromArray.js.map


/***/ }),
/* 225 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AsyncScheduler; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Scheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(321);
/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */


var AsyncScheduler = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](AsyncScheduler, _super);
    function AsyncScheduler(SchedulerAction, now) {
        if (now === void 0) {
            now = _Scheduler__WEBPACK_IMPORTED_MODULE_1__[/* Scheduler */ "a"].now;
        }
        var _this = _super.call(this, SchedulerAction, function () {
            if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) {
                return AsyncScheduler.delegate.now();
            }
            else {
                return now();
            }
        }) || this;
        _this.actions = [];
        _this.active = false;
        _this.scheduled = undefined;
        return _this;
    }
    AsyncScheduler.prototype.schedule = function (work, delay, state) {
        if (delay === void 0) {
            delay = 0;
        }
        if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) {
            return AsyncScheduler.delegate.schedule(work, delay, state);
        }
        else {
            return _super.prototype.schedule.call(this, work, delay, state);
        }
    };
    AsyncScheduler.prototype.flush = function (action) {
        var actions = this.actions;
        if (this.active) {
            actions.push(action);
            return;
        }
        var error;
        this.active = true;
        do {
            if (error = action.execute(action.state, action.delay)) {
                break;
            }
        } while (action = actions.shift());
        this.active = false;
        if (error) {
            while (action = actions.shift()) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AsyncScheduler;
}(_Scheduler__WEBPACK_IMPORTED_MODULE_1__[/* Scheduler */ "a"]));

//# sourceMappingURL=AsyncScheduler.js.map


/***/ }),
/* 226 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AsyncSubject; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(60);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70);
/** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */



var AsyncSubject = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](AsyncSubject, _super);
    function AsyncSubject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.value = null;
        _this.hasNext = false;
        _this.hasCompleted = false;
        return _this;
    }
    AsyncSubject.prototype._subscribe = function (subscriber) {
        if (this.hasError) {
            subscriber.error(this.thrownError);
            return _Subscription__WEBPACK_IMPORTED_MODULE_2__[/* Subscription */ "a"].EMPTY;
        }
        else if (this.hasCompleted && this.hasNext) {
            subscriber.next(this.value);
            subscriber.complete();
            return _Subscription__WEBPACK_IMPORTED_MODULE_2__[/* Subscription */ "a"].EMPTY;
        }
        return _super.prototype._subscribe.call(this, subscriber);
    };
    AsyncSubject.prototype.next = function (value) {
        if (!this.hasCompleted) {
            this.value = value;
            this.hasNext = true;
        }
    };
    AsyncSubject.prototype.error = function (error) {
        if (!this.hasCompleted) {
            _super.prototype.error.call(this, error);
        }
    };
    AsyncSubject.prototype.complete = function () {
        this.hasCompleted = true;
        if (this.hasNext) {
            _super.prototype.next.call(this, this.value);
        }
        _super.prototype.complete.call(this);
    };
    return AsyncSubject;
}(_Subject__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"]));

//# sourceMappingURL=AsyncSubject.js.map


/***/ }),
/* 227 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ principal_axes_PrincipalAxes; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/matrix.js
var matrix = __webpack_require__(64);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d.js + 4 modules
var _3d = __webpack_require__(25);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/svd.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

// svd method adapted from http://inspirit.github.io/jsfeat/ MIT Eugene Zatepyakin
function swap(A, i0, i1, t) {
    t = A[i0];
    A[i0] = A[i1];
    A[i1] = t;
}
function hypot(a, b) {
    a = Math.abs(a);
    b = Math.abs(b);
    if (a > b) {
        b /= a;
        return a * Math.sqrt(1.0 + b * b);
    }
    if (b > 0) {
        a /= b;
        return b * Math.sqrt(1.0 + a * a);
    }
    return 0.0;
}
var EPSILON = 0.0000001192092896;
var FLT_MIN = 1E-37;
function JacobiSVDImpl(At, astep, _W, Vt, vstep, m, n, n1) {
    var eps = EPSILON * 2.0;
    var minval = FLT_MIN;
    var i = 0;
    var j = 0;
    var k = 0;
    var iter = 0;
    var maxIter = Math.max(m, 30);
    var Ai = 0;
    var Aj = 0;
    var Vi = 0;
    var Vj = 0;
    var changed = 0;
    var c = 0.0;
    var s = 0.0;
    var t = 0.0;
    var t0 = 0.0;
    var t1 = 0.0;
    var sd = 0.0;
    var beta = 0.0;
    var gamma = 0.0;
    var delta = 0.0;
    var a = 0.0;
    var p = 0.0;
    var b = 0.0;
    var seed = 0x1234;
    var val = 0.0;
    var val0 = 0.0;
    var asum = 0.0;
    var W = new Float64Array(n << 3);
    for (; i < n; i++) {
        for (k = 0, sd = 0; k < m; k++) {
            t = At[i * astep + k];
            sd += t * t;
        }
        W[i] = sd;
        if (Vt) {
            for (k = 0; k < n; k++) {
                Vt[i * vstep + k] = 0;
            }
            Vt[i * vstep + i] = 1;
        }
    }
    for (; iter < maxIter; iter++) {
        changed = 0;
        for (i = 0; i < n - 1; i++) {
            for (j = i + 1; j < n; j++) {
                Ai = (i * astep) | 0;
                Aj = (j * astep) | 0;
                a = W[i];
                p = 0;
                b = W[j];
                k = 2;
                p += At[Ai] * At[Aj];
                p += At[Ai + 1] * At[Aj + 1];
                for (; k < m; k++) {
                    p += At[Ai + k] * At[Aj + k];
                }
                if (Math.abs(p) <= eps * Math.sqrt(a * b))
                    continue;
                p *= 2.0;
                beta = a - b;
                gamma = hypot(p, beta);
                if (beta < 0) {
                    delta = (gamma - beta) * 0.5;
                    s = Math.sqrt(delta / gamma);
                    c = (p / (gamma * s * 2.0));
                }
                else {
                    c = Math.sqrt((gamma + beta) / (gamma * 2.0));
                    s = (p / (gamma * c * 2.0));
                }
                a = 0.0;
                b = 0.0;
                k = 2; // unroll
                t0 = c * At[Ai] + s * At[Aj];
                t1 = -s * At[Ai] + c * At[Aj];
                At[Ai] = t0;
                At[Aj] = t1;
                a += t0 * t0;
                b += t1 * t1;
                t0 = c * At[Ai + 1] + s * At[Aj + 1];
                t1 = -s * At[Ai + 1] + c * At[Aj + 1];
                At[Ai + 1] = t0;
                At[Aj + 1] = t1;
                a += t0 * t0;
                b += t1 * t1;
                for (; k < m; k++) {
                    t0 = c * At[Ai + k] + s * At[Aj + k];
                    t1 = -s * At[Ai + k] + c * At[Aj + k];
                    At[Ai + k] = t0;
                    At[Aj + k] = t1;
                    a += t0 * t0;
                    b += t1 * t1;
                }
                W[i] = a;
                W[j] = b;
                changed = 1;
                if (Vt) {
                    Vi = (i * vstep) | 0;
                    Vj = (j * vstep) | 0;
                    k = 2;
                    t0 = c * Vt[Vi] + s * Vt[Vj];
                    t1 = -s * Vt[Vi] + c * Vt[Vj];
                    Vt[Vi] = t0;
                    Vt[Vj] = t1;
                    t0 = c * Vt[Vi + 1] + s * Vt[Vj + 1];
                    t1 = -s * Vt[Vi + 1] + c * Vt[Vj + 1];
                    Vt[Vi + 1] = t0;
                    Vt[Vj + 1] = t1;
                    for (; k < n; k++) {
                        t0 = c * Vt[Vi + k] + s * Vt[Vj + k];
                        t1 = -s * Vt[Vi + k] + c * Vt[Vj + k];
                        Vt[Vi + k] = t0;
                        Vt[Vj + k] = t1;
                    }
                }
            }
        }
        if (changed === 0)
            break;
    }
    for (i = 0; i < n; i++) {
        for (k = 0, sd = 0; k < m; k++) {
            t = At[i * astep + k];
            sd += t * t;
        }
        W[i] = Math.sqrt(sd);
    }
    for (i = 0; i < n - 1; i++) {
        j = i;
        for (k = i + 1; k < n; k++) {
            if (W[j] < W[k]) {
                j = k;
            }
        }
        if (i !== j) {
            swap(W, i, j, sd);
            if (Vt) {
                for (k = 0; k < m; k++) {
                    swap(At, i * astep + k, j * astep + k, t);
                }
                for (k = 0; k < n; k++) {
                    swap(Vt, i * vstep + k, j * vstep + k, t);
                }
            }
        }
    }
    for (i = 0; i < n; i++) {
        _W[i] = W[i];
    }
    if (!Vt) {
        return;
    }
    for (i = 0; i < n1; i++) {
        sd = i < n ? W[i] : 0;
        while (sd <= minval) {
            // if we got a zero singular value, then in order to get the corresponding left singular vector
            // we generate a random vector, project it to the previously computed left singular vectors,
            // subtract the projection and normalize the difference.
            val0 = (1.0 / m);
            for (k = 0; k < m; k++) {
                seed = (seed * 214013 + 2531011);
                val = (((seed >> 16) & 0x7fff) & 256) !== 0 ? val0 : -val0;
                At[i * astep + k] = val;
            }
            for (iter = 0; iter < 2; iter++) {
                for (j = 0; j < i; j++) {
                    sd = 0;
                    for (k = 0; k < m; k++) {
                        sd += At[i * astep + k] * At[j * astep + k];
                    }
                    asum = 0.0;
                    for (k = 0; k < m; k++) {
                        t = (At[i * astep + k] - sd * At[j * astep + k]);
                        At[i * astep + k] = t;
                        asum += Math.abs(t);
                    }
                    asum = asum ? 1.0 / asum : 0;
                    for (k = 0; k < m; k++) {
                        At[i * astep + k] *= asum;
                    }
                }
            }
            sd = 0;
            for (k = 0; k < m; k++) {
                t = At[i * astep + k];
                sd += t * t;
            }
            sd = Math.sqrt(sd);
        }
        s = (1.0 / sd);
        for (k = 0; k < m; k++) {
            At[i * astep + k] *= s;
        }
    }
}
function svd(A, W, U, V) {
    var at = 0;
    var i = 0;
    var _m = A.rows;
    var _n = A.cols;
    var m = _m;
    var n = _n;
    if (m < n) {
        at = 1;
        i = m;
        m = n;
        n = i;
    }
    var amt = matrix["a" /* default */].create(m, m);
    var wmt = matrix["a" /* default */].create(1, n);
    var vmt = matrix["a" /* default */].create(n, n);
    if (at === 0) {
        matrix["a" /* default */].transpose(amt, A);
    }
    else {
        for (i = 0; i < _n * _m; i++) {
            amt.data[i] = A.data[i];
        }
        for (; i < n * m; i++) {
            amt.data[i] = 0;
        }
    }
    JacobiSVDImpl(amt.data, m, wmt.data, vmt.data, n, m, n, m);
    if (W) {
        for (i = 0; i < n; i++) {
            W.data[i] = wmt.data[i];
        }
        for (; i < _n; i++) {
            W.data[i] = 0;
        }
    }
    if (at === 0) {
        if (U)
            matrix["a" /* default */].transpose(U, amt);
        if (V)
            matrix["a" /* default */].transpose(V, vmt);
    }
    else {
        if (U)
            matrix["a" /* default */].transpose(U, vmt);
        if (V)
            matrix["a" /* default */].transpose(V, amt);
    }
}
//# sourceMappingURL=svd.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/principal-axes.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var principal_axes_PrincipalAxes;
(function (PrincipalAxes) {
    function ofPositions(positions) {
        var momentsAxes = calculateMomentsAxes(positions);
        var boxAxes = calculateBoxAxes(positions, momentsAxes);
        return { momentsAxes: momentsAxes, boxAxes: boxAxes };
    }
    PrincipalAxes.ofPositions = ofPositions;
    function calculateMomentsAxes(positions) {
        if (positions.length === 3) {
            return geometry["a" /* Axes3D */].create(_3d["f" /* Vec3 */].fromArray(Object(_3d["f" /* Vec3 */])(), positions, 0), _3d["f" /* Vec3 */].create(1, 0, 0), _3d["f" /* Vec3 */].create(0, 1, 0), _3d["f" /* Vec3 */].create(0, 1, 0));
        }
        var points = matrix["a" /* default */].fromArray(positions, 3, positions.length / 3);
        var n = points.rows;
        var n3 = n / 3;
        var A = matrix["a" /* default */].create(3, 3);
        var W = matrix["a" /* default */].create(1, 3);
        var U = matrix["a" /* default */].create(3, 3);
        var V = matrix["a" /* default */].create(3, 3);
        // calculate
        var mean = matrix["a" /* default */].meanRows(points);
        var pointsM = matrix["a" /* default */].subRows(matrix["a" /* default */].clone(points), mean);
        var pointsT = matrix["a" /* default */].transpose(matrix["a" /* default */].create(n, 3), pointsM);
        matrix["a" /* default */].multiplyABt(A, pointsT, pointsT);
        svd(A, W, U, V);
        // origin
        var origin = _3d["f" /* Vec3 */].create(mean[0], mean[1], mean[2]);
        // directions
        var dirA = _3d["f" /* Vec3 */].create(U.data[0], U.data[3], U.data[6]);
        var dirB = _3d["f" /* Vec3 */].create(U.data[1], U.data[4], U.data[7]);
        var dirC = _3d["f" /* Vec3 */].create(U.data[2], U.data[5], U.data[8]);
        _3d["f" /* Vec3 */].scale(dirA, dirA, Math.sqrt(W.data[0] / n3));
        _3d["f" /* Vec3 */].scale(dirB, dirB, Math.sqrt(W.data[1] / n3));
        _3d["f" /* Vec3 */].scale(dirC, dirC, Math.sqrt(W.data[2] / n3));
        return geometry["a" /* Axes3D */].create(origin, dirA, dirB, dirC);
    }
    PrincipalAxes.calculateMomentsAxes = calculateMomentsAxes;
    var tmpBoxVec = Object(_3d["f" /* Vec3 */])();
    var tmpBoxVecA = Object(_3d["f" /* Vec3 */])();
    var tmpBoxVecB = Object(_3d["f" /* Vec3 */])();
    var tmpBoxVecC = Object(_3d["f" /* Vec3 */])();
    /**
     * Get the scale/length for each dimension for a box around the axes
     * to enclose the given positions
     */
    function calculateBoxAxes(positions, momentsAxes) {
        if (positions.length === 3) {
            return geometry["a" /* Axes3D */].clone(momentsAxes);
        }
        var d1a = -Infinity;
        var d1b = -Infinity;
        var d2a = -Infinity;
        var d2b = -Infinity;
        var d3a = -Infinity;
        var d3b = -Infinity;
        var p = Object(_3d["f" /* Vec3 */])();
        var t = Object(_3d["f" /* Vec3 */])();
        var center = momentsAxes.origin;
        var normVecA = _3d["f" /* Vec3 */].normalize(tmpBoxVecA, momentsAxes.dirA);
        var normVecB = _3d["f" /* Vec3 */].normalize(tmpBoxVecB, momentsAxes.dirB);
        var normVecC = _3d["f" /* Vec3 */].normalize(tmpBoxVecC, momentsAxes.dirC);
        for (var i = 0, il = positions.length; i < il; i += 3) {
            _3d["f" /* Vec3 */].projectPointOnVector(p, _3d["f" /* Vec3 */].fromArray(p, positions, i), normVecA, center);
            var dp1 = _3d["f" /* Vec3 */].dot(normVecA, _3d["f" /* Vec3 */].normalize(t, _3d["f" /* Vec3 */].sub(t, p, center)));
            var dt1 = _3d["f" /* Vec3 */].distance(p, center);
            if (dp1 > 0) {
                if (dt1 > d1a)
                    d1a = dt1;
            }
            else {
                if (dt1 > d1b)
                    d1b = dt1;
            }
            _3d["f" /* Vec3 */].projectPointOnVector(p, _3d["f" /* Vec3 */].fromArray(p, positions, i), normVecB, center);
            var dp2 = _3d["f" /* Vec3 */].dot(normVecB, _3d["f" /* Vec3 */].normalize(t, _3d["f" /* Vec3 */].sub(t, p, center)));
            var dt2 = _3d["f" /* Vec3 */].distance(p, center);
            if (dp2 > 0) {
                if (dt2 > d2a)
                    d2a = dt2;
            }
            else {
                if (dt2 > d2b)
                    d2b = dt2;
            }
            _3d["f" /* Vec3 */].projectPointOnVector(p, _3d["f" /* Vec3 */].fromArray(p, positions, i), normVecC, center);
            var dp3 = _3d["f" /* Vec3 */].dot(normVecC, _3d["f" /* Vec3 */].normalize(t, _3d["f" /* Vec3 */].sub(t, p, center)));
            var dt3 = _3d["f" /* Vec3 */].distance(p, center);
            if (dp3 > 0) {
                if (dt3 > d3a)
                    d3a = dt3;
            }
            else {
                if (dt3 > d3b)
                    d3b = dt3;
            }
        }
        var dirA = _3d["f" /* Vec3 */].setMagnitude(Object(_3d["f" /* Vec3 */])(), normVecA, (d1a + d1b) / 2);
        var dirB = _3d["f" /* Vec3 */].setMagnitude(Object(_3d["f" /* Vec3 */])(), normVecB, (d2a + d2b) / 2);
        var dirC = _3d["f" /* Vec3 */].setMagnitude(Object(_3d["f" /* Vec3 */])(), normVecC, (d3a + d3b) / 2);
        var origin = Object(_3d["f" /* Vec3 */])();
        var addCornerHelper = function (d1, d2, d3) {
            _3d["f" /* Vec3 */].copy(tmpBoxVec, center);
            _3d["f" /* Vec3 */].scaleAndAdd(tmpBoxVec, tmpBoxVec, normVecA, d1);
            _3d["f" /* Vec3 */].scaleAndAdd(tmpBoxVec, tmpBoxVec, normVecB, d2);
            _3d["f" /* Vec3 */].scaleAndAdd(tmpBoxVec, tmpBoxVec, normVecC, d3);
            _3d["f" /* Vec3 */].add(origin, origin, tmpBoxVec);
        };
        addCornerHelper(d1a, d2a, d3a);
        addCornerHelper(d1a, d2a, -d3b);
        addCornerHelper(d1a, -d2b, -d3b);
        addCornerHelper(d1a, -d2b, d3a);
        addCornerHelper(-d1b, -d2b, -d3b);
        addCornerHelper(-d1b, -d2b, d3a);
        addCornerHelper(-d1b, d2a, d3a);
        addCornerHelper(-d1b, d2a, -d3b);
        _3d["f" /* Vec3 */].scale(origin, origin, 1 / 8);
        return geometry["a" /* Axes3D */].create(origin, dirA, dirB, dirC);
    }
    PrincipalAxes.calculateBoxAxes = calculateBoxAxes;
})(principal_axes_PrincipalAxes || (principal_axes_PrincipalAxes = {}));
//# sourceMappingURL=principal-axes.js.map

/***/ }),
/* 228 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ ValenceModelProvider; });

// UNUSED EXPORTS: ValenceModelParams

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/properties/atomic/types.js
var types = __webpack_require__(245);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/geometry.js
var geometry = __webpack_require__(153);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/util.js
var util = __webpack_require__(30);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var model_types = __webpack_require__(22);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/chemistry/valence-model.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Fred Ludlow <Fred.Ludlow@astx.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









/**
 * TODO:
 *   Ensure proper treatment of disorder/models. e.g. V257 N in 5vim
 *   Formal charge of 255 for SO4 anion (e.g. 5ghl)
 *   Have removed a lot of explicit features (as I think they're more
 *   generally captured by better VM).
 *     Could we instead have a "delocalised negative/positive" charge
 *     feature and flag these up?
 *
 */
var tmpConjBondItA = new mol_model_structure["Bond"].ElementBondIterator();
var tmpConjBondItB = new mol_model_structure["Bond"].ElementBondIterator();
/**
 * Are we involved in some kind of pi system. Either explicitly forming
 * double bond or N, O next to a double bond, except:
 *
 *   N,O with degree 4 cannot be conjugated.
 *   N,O adjacent to P=O or S=O do not qualify (keeps sulfonamide N sp3 geom)
 */
function isConjugated(structure, unit, index) {
    var element = Object(util["i" /* typeSymbol */])(unit, index);
    var hetero = element === "O" /* O */ || element === "N" /* N */;
    if (hetero && Object(util["c" /* bondCount */])(structure, unit, index) === 4)
        return false;
    tmpConjBondItA.setElement(structure, unit, index);
    while (tmpConjBondItA.hasNext) {
        var bA = tmpConjBondItA.move();
        if (bA.order > 1)
            return true;
        if (hetero) {
            var elementB = Object(util["i" /* typeSymbol */])(bA.otherUnit, bA.otherIndex);
            tmpConjBondItB.setElement(structure, bA.otherUnit, bA.otherIndex);
            while (tmpConjBondItB.hasNext) {
                var bB = tmpConjBondItB.move();
                if (bB.order > 1) {
                    if ((elementB === "P" /* P */ || elementB === "S" /* S */) &&
                        Object(util["i" /* typeSymbol */])(bB.otherUnit, bB.otherIndex) === "O" /* O */) {
                        continue;
                    }
                    return true;
                }
            }
        }
    }
    return false;
}
function explicitValence(structure, unit, index) {
    var v = 0;
    // intra-unit bonds
    var _a = unit.bonds, offset = _a.offset, _b = _a.edgeProps, flags = _b.flags, order = _b.order;
    for (var i = offset[index], il = offset[index + 1]; i < il; ++i) {
        if (model_types["BondType"].isCovalent(flags[i]))
            v += order[i];
    }
    // inter-unit bonds
    structure.interUnitBonds.getEdgeIndices(index, unit).forEach(function (i) {
        var b = structure.interUnitBonds.edges[i];
        if (model_types["BondType"].isCovalent(b.props.flag))
            v += b.props.order;
    });
    return v;
}
var tmpChargeBondItA = new mol_model_structure["Bond"].ElementBondIterator();
var tmpChargeBondItB = new mol_model_structure["Bond"].ElementBondIterator();
/**
 * Attempts to produce a consistent charge and implicit
 * H-count for an atom.
 *
 * If both props.assignCharge and props.assignH, this
 * approximately follows the rules described in
 * https://docs.eyesopen.com/toolkits/python/oechemtk/valence.html#openeye-hydrogen-count-model
 *
 * If only charge or hydrogens are to be assigned it takes
 * a much simpler view and deduces one from the other
 */
function calculateHydrogensCharge(structure, unit, index, props) {
    var hydrogenCount = Object(util["d" /* bondToElementCount */])(structure, unit, index, "H" /* H */);
    var element = Object(util["i" /* typeSymbol */])(unit, index);
    var charge = Object(util["h" /* formalCharge */])(unit, index);
    var assignCharge = (props.assignCharge === 'always' || (props.assignCharge === 'auto' && charge === 0));
    var assignH = (props.assignH === 'always' || (props.assignH === 'auto' && hydrogenCount === 0));
    var degree = Object(util["c" /* bondCount */])(structure, unit, index);
    var valence = explicitValence(structure, unit, index);
    var conjugated = isConjugated(structure, unit, index);
    var multiBond = (valence - degree > 0);
    var implicitHCount = 0;
    var geom = 8 /* Unknown */;
    switch (element) {
        case "H" /* H */:
            if (assignCharge) {
                if (degree === 0) {
                    charge = 1;
                    geom = 0 /* Spherical */;
                }
                else if (degree === 1) {
                    charge = 0;
                    geom = 1 /* Terminal */;
                }
            }
            break;
        case "C" /* C */:
            // TODO: Isocyanide?
            if (assignCharge) {
                charge = 0; // Assume carbon always neutral
            }
            if (assignH) {
                // Carbocation/carbanion are 3-valent
                implicitHCount = Math.max(0, 4 - valence - Math.abs(charge));
            }
            // Carbocation is planar, carbanion is tetrahedral
            geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount + Math.max(0, -charge));
            break;
        case "N" /* N */:
            if (assignCharge) {
                if (!assignH) { // Trust input H explicitly:
                    charge = valence - 3;
                }
                else if (conjugated && valence < 4) {
                    // Neutral unless amidine/guanidine double-bonded N:
                    if (degree - hydrogenCount === 1 && valence - hydrogenCount === 2) {
                        charge = 1;
                    }
                    else {
                        charge = 0;
                    }
                }
                else {
                    // Sulfonamide nitrogen and classed as sp3 in conjugation model but
                    // they won't be charged
                    // Don't assign charge to nitrogens bound to metals
                    tmpChargeBondItA.setElement(structure, unit, index);
                    while (tmpChargeBondItA.hasNext) {
                        var b = tmpChargeBondItA.move();
                        var elementB = Object(util["i" /* typeSymbol */])(b.otherUnit, b.otherIndex);
                        if (elementB === "S" /* S */ || Object(types["c" /* isMetal */])(elementB)) {
                            charge = 0;
                            break;
                        }
                        else {
                            charge = 1;
                        }
                    }
                    // TODO: Planarity sanity check?
                }
            }
            if (assignH) {
                // NH4+ -> 4, 1' amide -> 2, nitro N/N+ depiction -> 0
                implicitHCount = Math.max(0, 3 - valence + charge);
            }
            if (conjugated && !multiBond) {
                // Amide, anilinic N etc. cannot consider lone-pair for geometry purposes
                // Anilinic N geometry is depenent on ring electronics, for our purposes we
                // assume it's trigonal!
                geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount - charge);
            }
            else {
                // Everything else, pyridine, amine, nitrile, lp plays normal role:
                geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount + 1 - charge);
            }
            break;
        case "O" /* O */:
            if (assignCharge) {
                if (!assignH) {
                    charge = valence - 2;
                }
                if (valence === 1) {
                    tmpChargeBondItA.setElement(structure, unit, index);
                    b1: while (tmpChargeBondItA.hasNext) {
                        var bA = tmpChargeBondItA.move();
                        tmpChargeBondItB.setElement(structure, bA.otherUnit, bA.otherIndex);
                        while (tmpChargeBondItB.hasNext) {
                            var bB = tmpChargeBondItB.move();
                            if (!(bB.otherUnit === unit && bB.otherIndex === index) &&
                                Object(util["i" /* typeSymbol */])(bB.otherUnit, bB.otherIndex) === "O" /* O */ &&
                                bB.order === 2) {
                                charge = -1;
                                break b1;
                            }
                        }
                    }
                }
            }
            if (assignH) {
                // ethanol -> 1, carboxylate -> -1
                implicitHCount = Math.max(0, 2 - valence + charge);
            }
            if (conjugated && !multiBond) {
                // carboxylate OH, phenol OH, one lone-pair taken up with conjugation
                geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount - charge + 1);
            }
            else {
                // Carbonyl (trigonal)
                geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount - charge + 2);
            }
            break;
        // Only handles thiols/thiolates/thioether/sulfonium. Sulfoxides and higher
        // oxidiation states are assumed neutral S (charge carried on O if required)
        case "S" /* S */:
            if (assignCharge) {
                if (!assignH) {
                    if (valence <= 3 && Object(util["d" /* bondToElementCount */])(structure, unit, index, "O" /* O */) === 0) {
                        charge = valence - 2; // e.g. explicitly deprotonated thiol
                    }
                    else {
                        charge = 0;
                    }
                }
            }
            if (assignH) {
                if (valence < 2) {
                    implicitHCount = Math.max(0, 2 - valence + charge);
                }
            }
            if (valence <= 3) {
                // Thiol, thiolate, tioether -> tetrahedral
                geom = Object(geometry["b" /* assignGeometry */])(degree + implicitHCount - charge + 2);
            }
            break;
        case "F" /* F */:
        case "CL" /* CL */:
        case "BR" /* BR */:
        case "I" /* I */:
        case "AT" /* AT */:
            // Never implicitly protonate halides
            if (assignCharge) {
                charge = valence - 1;
            }
            break;
        case "LI" /* LI */:
        case "NA" /* NA */:
        case "K" /* K */:
        case "RB" /* RB */:
        case "CS" /* CS */:
        case "FR" /* FR */:
            if (assignCharge) {
                charge = 1 - valence;
            }
            break;
        case "BE" /* BE */:
        case "MG" /* MG */:
        case "CA" /* CA */:
        case "SR" /* SR */:
        case "BA" /* BA */:
        case "RA" /* RA */:
            if (assignCharge) {
                charge = 2 - valence;
            }
            break;
        default:
            if (debug["a" /* isDebugMode */]) {
                console.warn('Requested charge, protonation for an unhandled element', element);
            }
    }
    return [charge, implicitHCount, implicitHCount + hydrogenCount, geom];
}
function calcUnitValenceModel(structure, unit, props) {
    var n = unit.elements.length;
    var charge = new Int8Array(n);
    var implicitH = new Int8Array(n);
    var totalH = new Int8Array(n);
    var idealGeometry = new Int8Array(n);
    // always use root UnitIndex to take the topology of the whole structure in account
    var hasParent = !!structure.parent;
    var mapping;
    if (hasParent) {
        var rootUnit = structure.root.unitMap.get(unit.id);
        mapping = mol_data_int["SortedArray"].indicesOf(rootUnit.elements, unit.elements);
        if (mapping.length !== unit.elements.length) {
            throw new Error('expected to find an index for every element');
        }
        unit = rootUnit;
        structure = structure.root;
    }
    for (var i = 0; i < n; ++i) {
        var j = (hasParent ? mapping[i] : i);
        var _a = calculateHydrogensCharge(structure, unit, j, props), chg = _a[0], implH = _a[1], totH = _a[2], geom = _a[3];
        charge[i] = chg;
        implicitH[i] = implH;
        totalH[i] = totH;
        idealGeometry[i] = geom;
    }
    return { charge: charge, implicitH: implicitH, totalH: totalH, idealGeometry: idealGeometry };
}
var ValenceModelParams = {
    assignCharge: param_definition["ParamDefinition"].Select('auto', [['always', 'always'], ['auto', 'auto'], ['never', 'never']]),
    assignH: param_definition["ParamDefinition"].Select('auto', [['always', 'always'], ['auto', 'auto'], ['never', 'never']]),
};
function calcValenceModel(ctx, structure, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var p, map, i, il, u, valenceModel;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(ValenceModelParams)), props);
            map = new Map();
            for (i = 0, il = structure.units.length; i < il; ++i) {
                u = structure.units[i];
                if (mol_model_structure["Unit"].isAtomic(u)) {
                    valenceModel = calcUnitValenceModel(structure, u, p);
                    map.set(u.id, valenceModel);
                }
            }
            return [2 /*return*/, map];
        });
    });
}
//# sourceMappingURL=valence-model.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-structure-property.js
var custom_structure_property = __webpack_require__(204);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/valence-model.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var valence_model_ValenceModelParams = Object(tslib_es6["__assign"])({}, ValenceModelParams);
var ValenceModelProvider = custom_structure_property["a" /* CustomStructureProperty */].createProvider({
    label: 'Valence Model',
    descriptor: Object(custom_property["CustomPropertyDescriptor"])({
        name: 'molstar_computed_valence_model',
    }),
    type: 'local',
    defaultParams: valence_model_ValenceModelParams,
    getParams: function (data) { return valence_model_ValenceModelParams; },
    isApplicable: function (data) { return true; },
    obtain: function (ctx, data, props) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var p, _a;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(valence_model_ValenceModelParams)), props);
                    _a = {};
                    return [4 /*yield*/, calcValenceModel(ctx.runtime, data, p)];
                case 1: return [2 /*return*/, (_a.value = _b.sent(), _a)];
            }
        });
    }); }
});
//# sourceMappingURL=valence-model.js.map

/***/ }),
/* 229 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ AsyncAction_AsyncAction; });

// EXTERNAL MODULE: ./node_modules/rxjs/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(21);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscription.js
var Subscription = __webpack_require__(70);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/Action.js
/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */


var Action_Action = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](Action, _super);
    function Action(scheduler, work) {
        return _super.call(this) || this;
    }
    Action.prototype.schedule = function (state, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        return this;
    };
    return Action;
}(Subscription["a" /* Subscription */]));

//# sourceMappingURL=Action.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js
/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */


var AsyncAction_AsyncAction = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AsyncAction, _super);
    function AsyncAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        _this.pending = false;
        return _this;
    }
    AsyncAction.prototype.schedule = function (state, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (this.closed) {
            return this;
        }
        this.state = state;
        var id = this.id;
        var scheduler = this.scheduler;
        if (id != null) {
            this.id = this.recycleAsyncId(scheduler, id, delay);
        }
        this.pending = true;
        this.delay = delay;
        this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
        return this;
    };
    AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        return setInterval(scheduler.flush.bind(scheduler, this), delay);
    };
    AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (delay !== null && this.delay === delay && this.pending === false) {
            return id;
        }
        clearInterval(id);
        return undefined;
    };
    AsyncAction.prototype.execute = function (state, delay) {
        if (this.closed) {
            return new Error('executing a cancelled action');
        }
        this.pending = false;
        var error = this._execute(state, delay);
        if (error) {
            return error;
        }
        else if (this.pending === false && this.id != null) {
            this.id = this.recycleAsyncId(this.scheduler, this.id, null);
        }
    };
    AsyncAction.prototype._execute = function (state, delay) {
        var errored = false;
        var errorValue = undefined;
        try {
            this.work(state);
        }
        catch (e) {
            errored = true;
            errorValue = !!e && e || new Error(e);
        }
        if (errored) {
            this.unsubscribe();
            return errorValue;
        }
    };
    AsyncAction.prototype._unsubscribe = function () {
        var id = this.id;
        var scheduler = this.scheduler;
        var actions = scheduler.actions;
        var index = actions.indexOf(this);
        this.work = null;
        this.state = null;
        this.pending = false;
        this.scheduler = null;
        if (index !== -1) {
            actions.splice(index, 1);
        }
        if (id != null) {
            this.id = this.recycleAsyncId(scheduler, id, null);
        }
        this.delay = null;
    };
    return AsyncAction;
}(Action_Action));

//# sourceMappingURL=AsyncAction.js.map


/***/ }),
/* 230 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Box3D; });
/* harmony import */ var _linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function Box3D() {
    return Box3D.empty();
}
(function (Box3D) {
    function create(min, max) { return { min: min, max: max }; }
    Box3D.create = create;
    function empty() { return { min: Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])(), max: Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])() }; }
    Box3D.empty = empty;
    function copy(out, a) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].copy(out.min, a.min);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].copy(out.max, a.max);
        return out;
    }
    Box3D.copy = copy;
    function clone(a) {
        return copy(empty(), a);
    }
    Box3D.clone = clone;
    function fromSphere3D(out, sphere) {
        var r = _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].create(sphere.radius, sphere.radius, sphere.radius);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(out.min, sphere.center, r);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(out.max, sphere.center, r);
        return out;
    }
    Box3D.fromSphere3D = fromSphere3D;
    function computeBounding(data) {
        var min = _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
        var max = _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
        var x = data.x, y = data.y, z = data.z, indices = data.indices;
        for (var t = 0, _t = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); t < _t; t++) {
            var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, t);
            min[0] = Math.min(x[i], min[0]);
            min[1] = Math.min(y[i], min[1]);
            min[2] = Math.min(z[i], min[2]);
            max[0] = Math.max(x[i], max[0]);
            max[1] = Math.max(y[i], max[1]);
            max[2] = Math.max(z[i], max[2]);
        }
        return { min: min, max: max };
    }
    Box3D.computeBounding = computeBounding;
    /** Get size/extent of the box */
    function size(size, box) {
        return _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(size, box.max, box.min);
    }
    Box3D.size = size;
    var tmpSizeV = Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    /** Get volume of the box */
    function volume(box) {
        size(tmpSizeV, box);
        return tmpSizeV[0] * tmpSizeV[1] * tmpSizeV[2];
    }
    Box3D.volume = volume;
    function setEmpty(box) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(box.min, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(box.max, -Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
        return box;
    }
    Box3D.setEmpty = setEmpty;
    /** Add point to box */
    function add(box, point) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].min(box.min, box.min, point);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].max(box.max, box.max, point);
        return box;
    }
    Box3D.add = add;
    /** Expand box by delta */
    function expand(out, box, delta) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].sub(out.min, box.min, delta);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(out.max, box.max, delta);
        return out;
    }
    Box3D.expand = expand;
    function scale(out, box, scale) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(out.min, box.min, scale);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].scale(out.max, box.max, scale);
        return out;
    }
    Box3D.scale = scale;
    var tmpTransformV = Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
    /** Transform box with a Mat4 */
    function transform(out, box, m) {
        var _a = box.min, minX = _a[0], minY = _a[1], minZ = _a[2];
        var _b = box.max, maxX = _b[0], maxY = _b[1], maxZ = _b[2];
        setEmpty(out);
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, minX, minY, minZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, minX, minY, maxZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, minX, maxY, minZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, minX, maxY, maxZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, maxX, minY, minZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, maxX, minY, maxZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, maxX, maxY, minZ), m));
        add(out, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].transformMat4(tmpTransformV, _linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(tmpTransformV, maxX, maxY, maxZ), m));
        return out;
    }
    Box3D.transform = transform;
})(Box3D || (Box3D = {}));

//# sourceMappingURL=box3d.js.map

/***/ }),
/* 231 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isNumeric; });
/* harmony import */ var _isArray__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(100);
/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */

function isNumeric(val) {
    return !Object(_isArray__WEBPACK_IMPORTED_MODULE_0__[/* isArray */ "a"])(val) && (val - parseFloat(val) + 1) >= 0;
}
//# sourceMappingURL=isNumeric.js.map


/***/ }),
/* 232 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ camera_Camera; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/camera/util.js
var util = __webpack_require__(176);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/interpolate.js
var interpolate = __webpack_require__(78);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-canvas3d/camera/transition.js
/**
 * Copyright (c) 2018-2019 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var transition_CameraTransitionManager = /** @class */ (function () {
    function CameraTransitionManager(camera) {
        this.camera = camera;
        this.t = 0;
        this.func = CameraTransitionManager.defaultTransition;
        this.start = 0;
        this.inTransition = false;
        this.durationMs = 0;
        this._source = camera_Camera.createDefaultSnapshot();
        this._target = camera_Camera.createDefaultSnapshot();
        this._current = camera_Camera.createDefaultSnapshot();
    }
    Object.defineProperty(CameraTransitionManager.prototype, "source", {
        get: function () { return this._source; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(CameraTransitionManager.prototype, "target", {
        get: function () { return this._target; },
        enumerable: false,
        configurable: true
    });
    CameraTransitionManager.prototype.apply = function (to, durationMs, transition) {
        if (durationMs === void 0) { durationMs = 0; }
        if (!this.inTransition || durationMs > 0) {
            camera_Camera.copySnapshot(this._source, this.camera.state);
        }
        if (!this.inTransition) {
            camera_Camera.copySnapshot(this._target, this.camera.state);
        }
        camera_Camera.copySnapshot(this._target, to);
        if (this._target.radius > this._target.radiusMax) {
            this._target.radius = this._target.radiusMax;
        }
        if (!this.inTransition && durationMs <= 0 || (typeof to.mode !== 'undefined' && to.mode !== this.camera.state.mode)) {
            this.finish(this._target);
            return;
        }
        this.inTransition = true;
        this.func = transition || CameraTransitionManager.defaultTransition;
        if (!this.inTransition || durationMs > 0) {
            this.start = this.t;
            this.durationMs = durationMs;
        }
    };
    CameraTransitionManager.prototype.tick = function (t) {
        this.t = t;
        this.update();
    };
    CameraTransitionManager.prototype.finish = function (to) {
        camera_Camera.copySnapshot(this.camera.state, to);
        this.inTransition = false;
    };
    CameraTransitionManager.prototype.update = function () {
        if (!this.inTransition)
            return;
        var normalized = Math.min((this.t - this.start) / this.durationMs, 1);
        if (normalized === 1) {
            this.finish(this._target);
            return;
        }
        this.func(this._current, normalized, this._source, this._target);
        camera_Camera.copySnapshot(this.camera.state, this._current);
    };
    return CameraTransitionManager;
}());
(function (CameraTransitionManager) {
    var _rot = linear_algebra["Quat"].identity();
    function defaultTransition(out, t, source, target) {
        camera_Camera.copySnapshot(out, target);
        // Rotate up
        linear_algebra["Quat"].slerp(_rot, linear_algebra["Quat"].Identity, linear_algebra["Quat"].rotationTo(_rot, source.up, target.up), t);
        linear_algebra["Vec3"].transformQuat(out.up, source.up, _rot);
        // Lerp target, position & radius
        linear_algebra["Vec3"].lerp(out.target, source.target, target.target, t);
        linear_algebra["Vec3"].lerp(out.position, source.position, target.position, t);
        out.radius = Object(interpolate["b" /* lerp */])(source.radius, target.radius, t);
        // TODO take change of `clipFar` into account
        out.radiusMax = Object(interpolate["b" /* lerp */])(source.radiusMax, target.radiusMax, t);
        // Lerp fov & fog
        out.fov = Object(interpolate["b" /* lerp */])(source.fov, target.fov, t);
        out.fog = Object(interpolate["b" /* lerp */])(source.fog, target.fog, t);
    }
    CameraTransitionManager.defaultTransition = defaultTransition;
})(transition_CameraTransitionManager || (transition_CameraTransitionManager = {}));
//# sourceMappingURL=transition.js.map
// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/BehaviorSubject.js
var BehaviorSubject = __webpack_require__(279);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-canvas3d/camera.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var camera_Camera = /** @class */ (function () {
    function Camera(state, viewport) {
        if (viewport === void 0) { viewport = util["a" /* Viewport */].create(-1, -1, 1, 1); }
        this.view = linear_algebra["Mat4"].identity();
        this.projection = linear_algebra["Mat4"].identity();
        this.projectionView = linear_algebra["Mat4"].identity();
        this.inverseProjectionView = linear_algebra["Mat4"].identity();
        this.state = Camera.createDefaultSnapshot();
        this.viewOffset = {
            enabled: false,
            fullWidth: 1, fullHeight: 1,
            offsetX: 0, offsetY: 0,
            width: 1, height: 1
        };
        this.near = 1;
        this.far = 10000;
        this.fogNear = 5000;
        this.fogFar = 10000;
        this.zoom = 1;
        this.transition = new transition_CameraTransitionManager(this);
        this.stateChanged = new BehaviorSubject["a" /* BehaviorSubject */](this.state);
        this.prevProjection = linear_algebra["Mat4"].identity();
        this.prevView = linear_algebra["Mat4"].identity();
        this.deltaDirection = Object(linear_algebra["Vec3"])();
        this.newPosition = Object(linear_algebra["Vec3"])();
        this.viewport = viewport;
        Camera.copySnapshot(this.state, state);
    }
    Object.defineProperty(Camera.prototype, "position", {
        get: function () { return this.state.position; },
        set: function (v) { linear_algebra["Vec3"].copy(this.state.position, v); },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Camera.prototype, "up", {
        get: function () { return this.state.up; },
        set: function (v) { linear_algebra["Vec3"].copy(this.state.up, v); },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Camera.prototype, "target", {
        get: function () { return this.state.target; },
        set: function (v) { linear_algebra["Vec3"].copy(this.state.target, v); },
        enumerable: false,
        configurable: true
    });
    Camera.prototype.update = function () {
        var snapshot = this.state;
        var height = 2 * Math.tan(snapshot.fov / 2) * linear_algebra["Vec3"].distance(snapshot.position, snapshot.target);
        this.zoom = this.viewport.height / height;
        updateClip(this);
        switch (this.state.mode) {
            case 'orthographic':
                updateOrtho(this);
                break;
            case 'perspective':
                updatePers(this);
                break;
            default: throw new Error('unknown camera mode');
        }
        var changed = !linear_algebra["Mat4"].areEqual(this.projection, this.prevProjection, linear_algebra["EPSILON"]) || !linear_algebra["Mat4"].areEqual(this.view, this.prevView, linear_algebra["EPSILON"]);
        if (changed) {
            linear_algebra["Mat4"].mul(this.projectionView, this.projection, this.view);
            linear_algebra["Mat4"].invert(this.inverseProjectionView, this.projectionView);
            linear_algebra["Mat4"].copy(this.prevView, this.view);
            linear_algebra["Mat4"].copy(this.prevProjection, this.projection);
        }
        return changed;
    };
    Camera.prototype.setState = function (snapshot, durationMs) {
        this.transition.apply(snapshot, durationMs);
        this.stateChanged.next(snapshot);
    };
    Camera.prototype.getSnapshot = function () {
        return Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
    };
    Camera.prototype.getTargetDistance = function (radius) {
        var r = Math.max(radius, 0.01);
        var fov = this.state.fov;
        var _a = this.viewport, width = _a.width, height = _a.height;
        var aspect = width / height;
        var aspectFactor = (height < width ? 1 : aspect);
        return Math.abs((r / aspectFactor) / Math.sin(fov / 2));
    };
    Camera.prototype.getFocus = function (target, radius, up, dir) {
        var r = Math.max(radius, 0.01);
        var targetDistance = this.getTargetDistance(r);
        linear_algebra["Vec3"].sub(this.deltaDirection, this.target, this.position);
        if (dir)
            linear_algebra["Vec3"].matchDirection(this.deltaDirection, dir, this.deltaDirection);
        linear_algebra["Vec3"].setMagnitude(this.deltaDirection, this.deltaDirection, targetDistance);
        linear_algebra["Vec3"].sub(this.newPosition, target, this.deltaDirection);
        var state = Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
        state.target = linear_algebra["Vec3"].clone(target);
        state.radius = r;
        state.position = linear_algebra["Vec3"].clone(this.newPosition);
        if (up)
            linear_algebra["Vec3"].matchDirection(state.up, up, state.up);
        return state;
    };
    Camera.prototype.focus = function (target, radius, durationMs, up, dir) {
        if (radius > 0) {
            this.setState(this.getFocus(target, radius, up, dir), durationMs);
        }
    };
    Camera.prototype.project = function (out, point) {
        return Object(util["b" /* cameraProject */])(out, point, this.viewport, this.projectionView);
    };
    Camera.prototype.unproject = function (out, point) {
        return Object(util["c" /* cameraUnproject */])(out, point, this.viewport, this.inverseProjectionView);
    };
    return Camera;
}());
(function (Camera) {
    function setViewOffset(out, fullWidth, fullHeight, offsetX, offsetY, width, height) {
        out.fullWidth = fullWidth;
        out.fullHeight = fullHeight;
        out.offsetX = offsetX;
        out.offsetY = offsetY;
        out.width = width;
        out.height = height;
    }
    Camera.setViewOffset = setViewOffset;
    function createDefaultSnapshot() {
        return {
            mode: 'perspective',
            fov: Math.PI / 4,
            position: linear_algebra["Vec3"].create(0, 0, 100),
            up: linear_algebra["Vec3"].create(0, 1, 0),
            target: linear_algebra["Vec3"].create(0, 0, 0),
            radius: 10,
            radiusMax: 10,
            fog: 50,
            clipFar: true
        };
    }
    Camera.createDefaultSnapshot = createDefaultSnapshot;
    function copySnapshot(out, source) {
        if (!source)
            return out;
        if (typeof source.mode !== 'undefined')
            out.mode = source.mode;
        if (typeof source.fov !== 'undefined')
            out.fov = source.fov;
        if (typeof source.position !== 'undefined')
            linear_algebra["Vec3"].copy(out.position, source.position);
        if (typeof source.up !== 'undefined')
            linear_algebra["Vec3"].copy(out.up, source.up);
        if (typeof source.target !== 'undefined')
            linear_algebra["Vec3"].copy(out.target, source.target);
        if (typeof source.radius !== 'undefined')
            out.radius = source.radius;
        if (typeof source.radiusMax !== 'undefined')
            out.radiusMax = source.radiusMax;
        if (typeof source.fog !== 'undefined')
            out.fog = source.fog;
        if (typeof source.clipFar !== 'undefined')
            out.clipFar = source.clipFar;
        return out;
    }
    Camera.copySnapshot = copySnapshot;
})(camera_Camera || (camera_Camera = {}));
function updateOrtho(camera) {
    var viewport = camera.viewport, zoom = camera.zoom, near = camera.near, far = camera.far, viewOffset = camera.viewOffset;
    var fullLeft = -(viewport.width - viewport.x) / 2;
    var fullRight = (viewport.width - viewport.x) / 2;
    var fullTop = (viewport.height - viewport.y) / 2;
    var fullBottom = -(viewport.height - viewport.y) / 2;
    var dx = (fullRight - fullLeft) / (2 * zoom);
    var dy = (fullTop - fullBottom) / (2 * zoom);
    var cx = (fullRight + fullLeft) / 2;
    var cy = (fullTop + fullBottom) / 2;
    var left = cx - dx;
    var right = cx + dx;
    var top = cy + dy;
    var bottom = cy - dy;
    if (viewOffset.enabled) {
        var zoomW = zoom / (viewOffset.width / viewOffset.fullWidth);
        var zoomH = zoom / (viewOffset.height / viewOffset.fullHeight);
        var scaleW = (fullRight - fullLeft) / viewOffset.width;
        var scaleH = (fullTop - fullBottom) / viewOffset.height;
        left += scaleW * (viewOffset.offsetX / zoomW);
        right = left + scaleW * (viewOffset.width / zoomW);
        top -= scaleH * (viewOffset.offsetY / zoomH);
        bottom = top - scaleH * (viewOffset.height / zoomH);
    }
    // build projection matrix
    linear_algebra["Mat4"].ortho(camera.projection, left, right, top, bottom, near, far);
    // build view matrix
    linear_algebra["Mat4"].lookAt(camera.view, camera.position, camera.target, camera.up);
}
function updatePers(camera) {
    var aspect = camera.viewport.width / camera.viewport.height;
    var near = camera.near, far = camera.far, viewOffset = camera.viewOffset;
    var top = near * Math.tan(0.5 * camera.state.fov);
    var height = 2 * top;
    var width = aspect * height;
    var left = -0.5 * width;
    if (viewOffset.enabled) {
        left += viewOffset.offsetX * width / viewOffset.fullWidth;
        top -= viewOffset.offsetY * height / viewOffset.fullHeight;
        width *= viewOffset.width / viewOffset.fullWidth;
        height *= viewOffset.height / viewOffset.fullHeight;
    }
    // build projection matrix
    linear_algebra["Mat4"].perspective(camera.projection, left, left + width, top, top - height, near, far);
    // build view matrix
    linear_algebra["Mat4"].lookAt(camera.view, camera.position, camera.target, camera.up);
}
function updateClip(camera) {
    var _a = camera.state, radius = _a.radius, radiusMax = _a.radiusMax, mode = _a.mode, fog = _a.fog, clipFar = _a.clipFar;
    if (radius < 0.01)
        radius = 0.01;
    var normalizedFar = clipFar ? radius : radiusMax;
    var cameraDistance = linear_algebra["Vec3"].distance(camera.position, camera.target);
    var near = cameraDistance - radius;
    var far = cameraDistance + normalizedFar;
    var fogNearFactor = -(50 - fog) / 50;
    var fogNear = cameraDistance - (normalizedFar * fogNearFactor);
    var fogFar = far;
    if (mode === 'perspective') {
        // set at least to 5 to avoid slow sphere impostor rendering
        near = Math.max(5, near);
        far = Math.max(5, far);
    }
    else {
        near = Math.max(0, near);
        far = Math.max(0, far);
    }
    if (near === far) {
        // make sure near and far are not identical to avoid Infinity in the projection matrix
        far = near + 0.01;
    }
    camera.near = near;
    camera.far = far;
    camera.fogNear = fogNear;
    camera.fogFar = fogFar;
}
//# sourceMappingURL=camera.js.map

/***/ }),
/* 233 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Hcl; });
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(46);
/* harmony import */ var _lab__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(161);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * Color conversion code adapted from chroma.js (https://github.com/gka/chroma.js)
 * Copyright (c) 2011-2018, Gregor Aisch, BSD license
 */



/**
 * CIE HCL (Hue-Chroma-Luminance) color
 *
 * - H [0..360]
 * - C [0..100]
 * - L [0..100]
 *
 * Cylindrical representation of CIELUV (see https://en.wikipedia.org/wiki/CIELUV)
 */
function Hcl() {
    return Hcl.zero();
}
(function (Hcl) {
    function zero() {
        var out = [0.1, 0.0, 0.0];
        out[0] = 0;
        return out;
    }
    Hcl.zero = zero;
    function create(h, c, l) {
        var out = zero();
        out[0] = h;
        out[1] = c;
        out[2] = l;
        return out;
    }
    Hcl.create = create;
    var tmpFromColorLab = [0, 0, 0];
    function fromColor(out, color) {
        return _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].toHcl(out, _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].fromColor(tmpFromColorLab, color));
    }
    Hcl.fromColor = fromColor;
    function fromLab(hcl, lab) {
        return _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].toHcl(hcl, lab);
    }
    Hcl.fromLab = fromLab;
    var tmpToColorLab = [0, 0, 0];
    function toColor(hcl) {
        return _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].toColor(toLab(tmpToColorLab, hcl));
    }
    Hcl.toColor = toColor;
    /**
     * Convert from a qualitative parameter h and a quantitative parameter l to a 24-bit pixel.
     *
     * These formulas were invented by David Dalrymple to obtain maximum contrast without going
     * out of gamut if the parameters are in the range 0-1.
     * A saturation multiplier was added by Gregor Aisch
     */
    function toLab(out, hcl) {
        var h = hcl[0], c = hcl[1], l = hcl[2];
        if (isNaN(h))
            h = 0;
        h = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_0__[/* degToRad */ "c"])(h);
        out[0] = l;
        out[1] = Math.cos(h) * c;
        out[2] = Math.sin(h) * c;
        return out;
    }
    Hcl.toLab = toLab;
    function copy(out, c) {
        out[0] = c[0];
        out[1] = c[1];
        out[2] = c[2];
        return out;
    }
    Hcl.copy = copy;
    function saturate(out, c, amount) {
        out[0] = c[0];
        out[1] = Math.max(0, c[1] + Kn * amount);
        out[2] = c[2];
        return out;
    }
    Hcl.saturate = saturate;
    function desaturate(out, c, amount) {
        return saturate(out, c, -amount);
    }
    Hcl.desaturate = desaturate;
    var tmpDarkenLab = [0, 0, 0];
    function darken(out, c, amount) {
        toLab(tmpDarkenLab, c);
        return _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].toHcl(out, _lab__WEBPACK_IMPORTED_MODULE_1__[/* Lab */ "a"].darken(tmpDarkenLab, tmpDarkenLab, amount));
    }
    Hcl.darken = darken;
    function lighten(out, c, amount) {
        return darken(out, c, -amount);
    }
    Hcl.lighten = lighten;
    // Corresponds roughly to RGB brighter/darker
    var Kn = 18;
})(Hcl || (Hcl = {}));
//# sourceMappingURL=hcl.js.map

/***/ }),
/* 234 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export DefaultPrismProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return Prism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DiamondPrism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return PentagonalPrism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return HexagonalPrism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return ShiftedHexagonalPrism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return HeptagonalPrism; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return PrismCage; });
/* unused harmony export DiamondPrismCage */
/* unused harmony export PentagonalPrismCage */
/* unused harmony export HexagonalPrismCage */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _primitive__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(127);
/* harmony import */ var _polygon__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(149);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var on = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), op = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var a = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), b = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), c = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), d = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
var DefaultPrismProps = {
    height: 1,
    topCap: true,
    bottomCap: true,
};
/**
 * Create a prism with a base of 4 or more points
 */
function Prism(points, props) {
    var sideCount = points.length / 3;
    if (sideCount < 4)
        throw new Error('need at least 4 points to build a prism');
    var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultPrismProps), props), height = _a.height, topCap = _a.topCap, bottomCap = _a.bottomCap;
    var count = 4 * sideCount;
    var builder = Object(_primitive__WEBPACK_IMPORTED_MODULE_2__[/* PrimitiveBuilder */ "a"])(count);
    var halfHeight = height * 0.5;
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(on, 0, 0, -halfHeight);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(op, 0, 0, halfHeight);
    // create sides
    for (var i = 0; i < sideCount; ++i) {
        var ni = (i + 1) % sideCount;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(a, points[i * 3], points[i * 3 + 1], -halfHeight);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(b, points[ni * 3], points[ni * 3 + 1], -halfHeight);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(c, points[ni * 3], points[ni * 3 + 1], halfHeight);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(d, points[i * 3], points[i * 3 + 1], halfHeight);
        builder.add(a, b, c);
        builder.add(c, d, a);
    }
    // create bases
    for (var i = 0; i < sideCount; ++i) {
        var ni = (i + 1) % sideCount;
        if (topCap) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(a, points[i * 3], points[i * 3 + 1], -halfHeight);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(b, points[ni * 3], points[ni * 3 + 1], -halfHeight);
            builder.add(on, b, a);
        }
        if (bottomCap) {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(a, points[i * 3], points[i * 3 + 1], halfHeight);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(b, points[ni * 3], points[ni * 3 + 1], halfHeight);
            builder.add(a, b, op);
        }
    }
    return builder.getPrimitive();
}
var diamond;
function DiamondPrism() {
    if (!diamond)
        diamond = Prism(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(4, false));
    return diamond;
}
var pentagonalPrism;
function PentagonalPrism() {
    if (!pentagonalPrism)
        pentagonalPrism = Prism(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(5, false));
    return pentagonalPrism;
}
var hexagonalPrism;
function HexagonalPrism() {
    if (!hexagonalPrism)
        hexagonalPrism = Prism(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(6, false));
    return hexagonalPrism;
}
var shiftedHexagonalPrism;
function ShiftedHexagonalPrism() {
    if (!shiftedHexagonalPrism)
        shiftedHexagonalPrism = Prism(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(6, true));
    return shiftedHexagonalPrism;
}
var heptagonalPrism;
function HeptagonalPrism() {
    if (!heptagonalPrism)
        heptagonalPrism = Prism(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(7, false));
    return heptagonalPrism;
}
//
/**
 * Create a prism cage
 */
function PrismCage(points, height) {
    if (height === void 0) { height = 1; }
    var sideCount = points.length / 3;
    var vertices = [];
    var edges = [];
    var halfHeight = height * 0.5;
    var offset = 0;
    // vertices and side edges
    for (var i = 0; i < sideCount; ++i) {
        vertices.push(points[i * 3], points[i * 3 + 1], -halfHeight, points[i * 3], points[i * 3 + 1], halfHeight);
        edges.push(offset, offset + 1);
        offset += 2;
    }
    // bases edges
    for (var i = 0; i < sideCount; ++i) {
        var ni = (i + 1) % sideCount;
        edges.push(i * 2, ni * 2, i * 2 + 1, ni * 2 + 1);
    }
    return { vertices: vertices, edges: edges };
}
var diamondCage;
function DiamondPrismCage() {
    if (!diamondCage)
        diamondCage = PrismCage(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(4, false));
    return diamondCage;
}
var pentagonalPrismCage;
function PentagonalPrismCage() {
    if (!pentagonalPrismCage)
        pentagonalPrismCage = PrismCage(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(5, false));
    return pentagonalPrismCage;
}
var hexagonalPrismCage;
function HexagonalPrismCage() {
    if (!hexagonalPrismCage)
        hexagonalPrismCage = PrismCage(Object(_polygon__WEBPACK_IMPORTED_MODULE_3__[/* polygon */ "a"])(6, false));
    return hexagonalPrismCage;
}
//# sourceMappingURL=prism.js.map

/***/ }),
/* 235 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return merge; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(122);
/* harmony import */ var _operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(292);
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(224);
/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */




function merge() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    var concurrent = Number.POSITIVE_INFINITY;
    var scheduler = null;
    var last = observables[observables.length - 1];
    if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__[/* isScheduler */ "a"])(last)) {
        scheduler = observables.pop();
        if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') {
            concurrent = observables.pop();
        }
    }
    else if (typeof last === 'number') {
        concurrent = observables.pop();
    }
    if (scheduler === null && observables.length === 1 && observables[0] instanceof _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"]) {
        return observables[0];
    }
    return Object(_operators_mergeAll__WEBPACK_IMPORTED_MODULE_2__[/* mergeAll */ "a"])(concurrent)(Object(_fromArray__WEBPACK_IMPORTED_MODULE_3__[/* fromArray */ "a"])(observables, scheduler));
}
//# sourceMappingURL=merge.js.map


/***/ }),
/* 236 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PropertyWrapper", function() { return PropertyWrapper; });
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62);
/* harmony import */ var _mol_util_date__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(308);
/* harmony import */ var _mol_model_formats_structure_mmcif__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(71);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var PropertyWrapper;
(function (PropertyWrapper) {
    function createInfo() {
        return { timestamp_utc: Object(_mol_util_date__WEBPACK_IMPORTED_MODULE_1__["dateToUtcString"])(new Date()) };
    }
    PropertyWrapper.createInfo = createInfo;
    function defaultInfoCategory(name, getter) {
        return {
            name: name,
            instance: function (ctx) {
                var info = getter(ctx);
                return {
                    fields: _info_fields,
                    source: [{ data: info, rowCount: 1 }]
                };
            }
        };
    }
    PropertyWrapper.defaultInfoCategory = defaultInfoCategory;
    var _info_fields = [
        _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].Field.str('updated_datetime_utc', function (_, date) { return date.timestamp_utc; })
    ];
    function tryGetInfoFromCif(categoryName, model) {
        if (!_mol_model_formats_structure_mmcif__WEBPACK_IMPORTED_MODULE_2__["MmcifFormat"].is(model.sourceData) || !model.sourceData.data.frame.categoryNames.includes(categoryName)) {
            return;
        }
        var timestampField = model.sourceData.data.frame.categories[categoryName].getField('updated_datetime_utc');
        if (!timestampField || timestampField.rowCount === 0)
            return;
        return { timestamp_utc: timestampField.str(0) || Object(_mol_util_date__WEBPACK_IMPORTED_MODULE_1__["dateToUtcString"])(new Date()) };
    }
    PropertyWrapper.tryGetInfoFromCif = tryGetInfoFromCif;
})(PropertyWrapper || (PropertyWrapper = {}));

//# sourceMappingURL=wrapper.js.map

/***/ }),
/* 237 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return VolumeVisual; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return VolumeRepresentationProvider; });
/* unused harmony export VolumeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return VolumeRepresentation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _visual__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(69);
/* harmony import */ var _mol_model_volume__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(36);
/* harmony import */ var _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(145);
/* harmony import */ var _mol_theme_theme__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(89);
/* harmony import */ var _mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(182);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(115);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(23);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(6);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(164);
/* harmony import */ var _mol_theme_color__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(196);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(5);
/* harmony import */ var _mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(146);
/* harmony import */ var _mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(117);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(40);
/* harmony import */ var _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(33);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_17__ = __webpack_require__(60);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_18__ = __webpack_require__(16);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



















function createVolumeRenderObject(volume, geometry, locationIt, theme, props, materialId) {
    var _a = _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_4__[/* Geometry */ "a"].getUtils(geometry), createValues = _a.createValues, createRenderableState = _a.createRenderableState;
    var transform = Object(_mol_geo_geometry_transform_data__WEBPACK_IMPORTED_MODULE_6__[/* createIdentityTransform */ "a"])();
    var values = createValues(geometry, transform, locationIt, theme, props);
    var state = createRenderableState(props);
    return Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_7__[/* createRenderObject */ "a"])(geometry.kind, values, state, materialId);
}
function VolumeVisual(builder, materialId) {
    var defaultProps = builder.defaultProps, createGeometry = builder.createGeometry, createLocationIterator = builder.createLocationIterator, getLoci = builder.getLoci, eachLocation = builder.eachLocation, setUpdateState = builder.setUpdateState;
    var _a = builder.geometryUtils, updateValues = _a.updateValues, updateBoundingSphere = _a.updateBoundingSphere, updateRenderableState = _a.updateRenderableState;
    var updateState = _util__WEBPACK_IMPORTED_MODULE_10__[/* VisualUpdateState */ "a"].create();
    var renderObject;
    var newProps;
    var newTheme;
    var newVolume;
    var currentProps = Object.assign({}, defaultProps);
    var currentTheme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_5__[/* Theme */ "a"].createEmpty();
    var currentVolume;
    var geometry;
    var locationIt;
    function prepareUpdate(theme, props, volume) {
        if (!volume && !currentVolume) {
            throw new Error('missing volume');
        }
        newProps = Object.assign({}, currentProps, props);
        newTheme = theme;
        newVolume = volume;
        _util__WEBPACK_IMPORTED_MODULE_10__[/* VisualUpdateState */ "a"].reset(updateState);
        if (!renderObject) {
            updateState.createNew = true;
        }
        else if (!currentVolume || !_mol_model_volume__WEBPACK_IMPORTED_MODULE_3__[/* Volume */ "b"].areEquivalent(newVolume, currentVolume)) {
            updateState.createNew = true;
        }
        if (updateState.createNew) {
            updateState.createGeometry = true;
            return;
        }
        setUpdateState(updateState, volume, newProps, currentProps, newTheme, currentTheme);
        if (!_mol_theme_color__WEBPACK_IMPORTED_MODULE_11__[/* ColorTheme */ "a"].areEqual(theme.color, currentTheme.color))
            updateState.updateColor = true;
        if (updateState.createGeometry) {
            updateState.updateColor = true;
        }
    }
    function update(newGeometry) {
        if (updateState.createNew) {
            locationIt = createLocationIterator(newVolume);
            if (newGeometry) {
                renderObject = createVolumeRenderObject(newVolume, newGeometry, locationIt, newTheme, newProps, materialId);
            }
            else {
                throw new Error('expected geometry to be given');
            }
        }
        else {
            if (!renderObject) {
                throw new Error('expected renderObject to be available');
            }
            locationIt.reset();
            if (updateState.createGeometry) {
                if (newGeometry) {
                    _mol_util__WEBPACK_IMPORTED_MODULE_12__[/* ValueCell */ "e"].update(renderObject.values.drawCount, _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_4__[/* Geometry */ "a"].getDrawCount(newGeometry));
                    updateBoundingSphere(renderObject.values, newGeometry);
                }
                else {
                    throw new Error('expected geometry to be given');
                }
            }
            if (updateState.updateSize) {
                // not all geometries have size data, so check here
                if ('uSize' in renderObject.values) {
                    Object(_mol_geo_geometry_size_data__WEBPACK_IMPORTED_MODULE_13__[/* createSizes */ "a"])(locationIt, newTheme.size, renderObject.values);
                }
            }
            if (updateState.updateColor) {
                Object(_mol_geo_geometry_color_data__WEBPACK_IMPORTED_MODULE_14__[/* createColors */ "a"])(locationIt, newTheme.color, renderObject.values);
            }
            updateValues(renderObject.values, newProps);
            updateRenderableState(renderObject.state, newProps);
        }
        currentProps = newProps;
        currentTheme = newTheme;
        currentVolume = newVolume;
        if (newGeometry)
            geometry = newGeometry;
    }
    function lociApply(loci, apply) {
        if (Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["isEveryLoci"])(loci)) {
            return apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_9__["Interval"].ofBounds(0, locationIt.groupCount * locationIt.instanceCount));
        }
        else {
            return eachLocation(loci, currentVolume, currentProps, apply);
        }
    }
    return {
        get groupCount() { return locationIt ? locationIt.count : 0; },
        get renderObject() { return renderObject; },
        createOrUpdate: function (ctx, theme, props, volume) {
            if (props === void 0) { props = {}; }
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
                var newGeometry;
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                    prepareUpdate(theme, props, volume || currentVolume);
                    if (updateState.createGeometry) {
                        newGeometry = createGeometry(ctx, newVolume, newTheme, newProps, geometry);
                        return [2 /*return*/, newGeometry instanceof Promise ? newGeometry.then(update) : update(newGeometry)];
                    }
                    else {
                        update();
                    }
                    return [2 /*return*/];
                });
            });
        },
        getLoci: function (pickingId) {
            return renderObject ? getLoci(pickingId, currentVolume, currentProps, renderObject.id) : _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["EmptyLoci"];
        },
        mark: function (loci, action) {
            return _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].mark(renderObject, loci, action, lociApply);
        },
        setVisibility: function (visible) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setVisibility(renderObject, visible);
        },
        setAlphaFactor: function (alphaFactor) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setAlphaFactor(renderObject, alphaFactor);
        },
        setPickable: function (pickable) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setPickable(renderObject, pickable);
        },
        setTransform: function (matrix, instanceMatrices) {
            _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setTransform(renderObject, matrix, instanceMatrices);
        },
        setOverpaint: function (overpaint) {
            return _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setOverpaint(renderObject, overpaint, lociApply, true);
        },
        setTransparency: function (transparency) {
            return _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setTransparency(renderObject, transparency, lociApply, true);
        },
        setClipping: function (clipping) {
            return _visual__WEBPACK_IMPORTED_MODULE_2__[/* Visual */ "a"].setClipping(renderObject, clipping, lociApply, true);
        },
        destroy: function () {
            // TODO
            renderObject = undefined;
        }
    };
}
function VolumeRepresentationProvider(p) { return p; }
//
var VolumeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_16__[/* BaseGeometry */ "a"].Params);
function VolumeRepresentation(label, ctx, getParams, visualCtor, getLoci) {
    var version = 0;
    var updated = new rxjs__WEBPACK_IMPORTED_MODULE_17__[/* Subject */ "a"]();
    var materialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_7__[/* getNextMaterialId */ "c"])();
    var renderObjects = [];
    var _state = _representation__WEBPACK_IMPORTED_MODULE_15__[/* Representation */ "a"].createState();
    var visual;
    var _volume;
    var _params;
    var _props;
    var _theme = _mol_theme_theme__WEBPACK_IMPORTED_MODULE_5__[/* Theme */ "a"].createEmpty();
    function createOrUpdate(props, volume) {
        var _this = this;
        if (props === void 0) { props = {}; }
        if (volume && volume !== _volume) {
            _params = getParams(ctx, volume);
            _volume = volume;
            if (!_props)
                _props = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(_params);
        }
        _props = Object.assign({}, _props, props);
        return _mol_task__WEBPACK_IMPORTED_MODULE_18__[/* Task */ "b"].create('Creating or updating VolumeRepresentation', function (runtime) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var promise;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!visual)
                            visual = visualCtor(materialId);
                        promise = visual.createOrUpdate({ webgl: ctx.webgl, runtime: runtime }, _theme, _props, volume);
                        if (!promise) return [3 /*break*/, 2];
                        return [4 /*yield*/, promise];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        // update list of renderObjects
                        renderObjects.length = 0;
                        if (visual && visual.renderObject)
                            renderObjects.push(visual.renderObject);
                        // increment version
                        updated.next(version++);
                        return [2 /*return*/];
                }
            });
        }); });
    }
    function mark(loci, action) {
        return visual ? visual.mark(loci, action) : false;
    }
    function setState(state) {
        if (state.visible !== undefined && visual)
            visual.setVisibility(state.visible);
        if (state.alphaFactor !== undefined && visual)
            visual.setAlphaFactor(state.alphaFactor);
        if (state.pickable !== undefined && visual)
            visual.setPickable(state.pickable);
        if (state.overpaint !== undefined && visual)
            visual.setOverpaint(state.overpaint);
        if (state.transparency !== undefined && visual)
            visual.setTransparency(state.transparency);
        if (state.transform !== undefined && visual)
            visual.setTransform(state.transform);
        _representation__WEBPACK_IMPORTED_MODULE_15__[/* Representation */ "a"].updateState(_state, state);
    }
    function setTheme(theme) {
        _theme = theme;
    }
    function destroy() {
        if (visual)
            visual.destroy();
    }
    return {
        label: label,
        get groupCount() {
            return visual ? visual.groupCount : 0;
        },
        get props() { return _props; },
        get params() { return _params; },
        get state() { return _state; },
        get theme() { return _theme; },
        renderObjects: renderObjects,
        updated: updated,
        createOrUpdate: createOrUpdate,
        setState: setState,
        setTheme: setTheme,
        getLoci: function (pickingId) {
            if (pickingId === undefined)
                return getLoci(_volume, _props);
            return visual ? visual.getLoci(pickingId) : _mol_model_loci__WEBPACK_IMPORTED_MODULE_8__["EmptyLoci"];
        },
        mark: mark,
        destroy: destroy
    };
}
//# sourceMappingURL=representation.js.map

/***/ }),
/* 238 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "audit", function() { return /* reexport */ audit; });
__webpack_require__.d(__webpack_exports__, "auditTime", function() { return /* reexport */ auditTime; });
__webpack_require__.d(__webpack_exports__, "buffer", function() { return /* reexport */ buffer_buffer; });
__webpack_require__.d(__webpack_exports__, "bufferCount", function() { return /* reexport */ bufferCount; });
__webpack_require__.d(__webpack_exports__, "bufferTime", function() { return /* reexport */ bufferTime; });
__webpack_require__.d(__webpack_exports__, "bufferToggle", function() { return /* reexport */ bufferToggle; });
__webpack_require__.d(__webpack_exports__, "bufferWhen", function() { return /* reexport */ bufferWhen; });
__webpack_require__.d(__webpack_exports__, "catchError", function() { return /* reexport */ catchError; });
__webpack_require__.d(__webpack_exports__, "combineAll", function() { return /* reexport */ combineAll; });
__webpack_require__.d(__webpack_exports__, "combineLatest", function() { return /* reexport */ combineLatest_combineLatest; });
__webpack_require__.d(__webpack_exports__, "concat", function() { return /* reexport */ concat_concat; });
__webpack_require__.d(__webpack_exports__, "concatAll", function() { return /* reexport */ concatAll["a" /* concatAll */]; });
__webpack_require__.d(__webpack_exports__, "concatMap", function() { return /* reexport */ concatMap; });
__webpack_require__.d(__webpack_exports__, "concatMapTo", function() { return /* reexport */ concatMapTo; });
__webpack_require__.d(__webpack_exports__, "count", function() { return /* reexport */ count_count; });
__webpack_require__.d(__webpack_exports__, "debounce", function() { return /* reexport */ debounce; });
__webpack_require__.d(__webpack_exports__, "debounceTime", function() { return /* reexport */ debounceTime["a" /* debounceTime */]; });
__webpack_require__.d(__webpack_exports__, "defaultIfEmpty", function() { return /* reexport */ defaultIfEmpty; });
__webpack_require__.d(__webpack_exports__, "delay", function() { return /* reexport */ delay_delay; });
__webpack_require__.d(__webpack_exports__, "delayWhen", function() { return /* reexport */ delayWhen; });
__webpack_require__.d(__webpack_exports__, "dematerialize", function() { return /* reexport */ dematerialize; });
__webpack_require__.d(__webpack_exports__, "distinct", function() { return /* reexport */ distinct; });
__webpack_require__.d(__webpack_exports__, "distinctUntilChanged", function() { return /* reexport */ distinctUntilChanged; });
__webpack_require__.d(__webpack_exports__, "distinctUntilKeyChanged", function() { return /* reexport */ distinctUntilKeyChanged; });
__webpack_require__.d(__webpack_exports__, "elementAt", function() { return /* reexport */ elementAt; });
__webpack_require__.d(__webpack_exports__, "endWith", function() { return /* reexport */ endWith; });
__webpack_require__.d(__webpack_exports__, "every", function() { return /* reexport */ every; });
__webpack_require__.d(__webpack_exports__, "exhaust", function() { return /* reexport */ exhaust; });
__webpack_require__.d(__webpack_exports__, "exhaustMap", function() { return /* reexport */ exhaustMap; });
__webpack_require__.d(__webpack_exports__, "expand", function() { return /* reexport */ expand; });
__webpack_require__.d(__webpack_exports__, "filter", function() { return /* reexport */ filter["a" /* filter */]; });
__webpack_require__.d(__webpack_exports__, "finalize", function() { return /* reexport */ finalize; });
__webpack_require__.d(__webpack_exports__, "find", function() { return /* reexport */ find; });
__webpack_require__.d(__webpack_exports__, "findIndex", function() { return /* reexport */ findIndex; });
__webpack_require__.d(__webpack_exports__, "first", function() { return /* reexport */ first; });
__webpack_require__.d(__webpack_exports__, "groupBy", function() { return /* reexport */ groupBy["b" /* groupBy */]; });
__webpack_require__.d(__webpack_exports__, "ignoreElements", function() { return /* reexport */ ignoreElements; });
__webpack_require__.d(__webpack_exports__, "isEmpty", function() { return /* reexport */ isEmpty; });
__webpack_require__.d(__webpack_exports__, "last", function() { return /* reexport */ last; });
__webpack_require__.d(__webpack_exports__, "map", function() { return /* reexport */ map["a" /* map */]; });
__webpack_require__.d(__webpack_exports__, "mapTo", function() { return /* reexport */ mapTo; });
__webpack_require__.d(__webpack_exports__, "materialize", function() { return /* reexport */ materialize; });
__webpack_require__.d(__webpack_exports__, "max", function() { return /* reexport */ max_max; });
__webpack_require__.d(__webpack_exports__, "merge", function() { return /* reexport */ merge_merge; });
__webpack_require__.d(__webpack_exports__, "mergeAll", function() { return /* reexport */ mergeAll["a" /* mergeAll */]; });
__webpack_require__.d(__webpack_exports__, "mergeMap", function() { return /* reexport */ mergeMap["a" /* mergeMap */]; });
__webpack_require__.d(__webpack_exports__, "flatMap", function() { return /* reexport */ mergeMap["a" /* mergeMap */]; });
__webpack_require__.d(__webpack_exports__, "mergeMapTo", function() { return /* reexport */ mergeMapTo; });
__webpack_require__.d(__webpack_exports__, "mergeScan", function() { return /* reexport */ mergeScan; });
__webpack_require__.d(__webpack_exports__, "min", function() { return /* reexport */ min_min; });
__webpack_require__.d(__webpack_exports__, "multicast", function() { return /* reexport */ multicast; });
__webpack_require__.d(__webpack_exports__, "observeOn", function() { return /* reexport */ observeOn["b" /* observeOn */]; });
__webpack_require__.d(__webpack_exports__, "onErrorResumeNext", function() { return /* reexport */ onErrorResumeNext; });
__webpack_require__.d(__webpack_exports__, "pairwise", function() { return /* reexport */ pairwise; });
__webpack_require__.d(__webpack_exports__, "partition", function() { return /* reexport */ partition; });
__webpack_require__.d(__webpack_exports__, "pluck", function() { return /* reexport */ pluck; });
__webpack_require__.d(__webpack_exports__, "publish", function() { return /* reexport */ publish; });
__webpack_require__.d(__webpack_exports__, "publishBehavior", function() { return /* reexport */ publishBehavior; });
__webpack_require__.d(__webpack_exports__, "publishLast", function() { return /* reexport */ publishLast; });
__webpack_require__.d(__webpack_exports__, "publishReplay", function() { return /* reexport */ publishReplay; });
__webpack_require__.d(__webpack_exports__, "race", function() { return /* reexport */ race_race; });
__webpack_require__.d(__webpack_exports__, "reduce", function() { return /* reexport */ reduce; });
__webpack_require__.d(__webpack_exports__, "repeat", function() { return /* reexport */ repeat; });
__webpack_require__.d(__webpack_exports__, "repeatWhen", function() { return /* reexport */ repeatWhen; });
__webpack_require__.d(__webpack_exports__, "retry", function() { return /* reexport */ retry; });
__webpack_require__.d(__webpack_exports__, "retryWhen", function() { return /* reexport */ retryWhen; });
__webpack_require__.d(__webpack_exports__, "refCount", function() { return /* reexport */ operators_refCount["a" /* refCount */]; });
__webpack_require__.d(__webpack_exports__, "sample", function() { return /* reexport */ sample; });
__webpack_require__.d(__webpack_exports__, "sampleTime", function() { return /* reexport */ sampleTime; });
__webpack_require__.d(__webpack_exports__, "scan", function() { return /* reexport */ scan; });
__webpack_require__.d(__webpack_exports__, "sequenceEqual", function() { return /* reexport */ sequenceEqual; });
__webpack_require__.d(__webpack_exports__, "share", function() { return /* reexport */ share; });
__webpack_require__.d(__webpack_exports__, "shareReplay", function() { return /* reexport */ shareReplay; });
__webpack_require__.d(__webpack_exports__, "single", function() { return /* reexport */ single; });
__webpack_require__.d(__webpack_exports__, "skip", function() { return /* reexport */ skip; });
__webpack_require__.d(__webpack_exports__, "skipLast", function() { return /* reexport */ skipLast; });
__webpack_require__.d(__webpack_exports__, "skipUntil", function() { return /* reexport */ skipUntil; });
__webpack_require__.d(__webpack_exports__, "skipWhile", function() { return /* reexport */ skipWhile; });
__webpack_require__.d(__webpack_exports__, "startWith", function() { return /* reexport */ startWith; });
__webpack_require__.d(__webpack_exports__, "subscribeOn", function() { return /* reexport */ subscribeOn; });
__webpack_require__.d(__webpack_exports__, "switchAll", function() { return /* reexport */ switchAll; });
__webpack_require__.d(__webpack_exports__, "switchMap", function() { return /* reexport */ switchMap; });
__webpack_require__.d(__webpack_exports__, "switchMapTo", function() { return /* reexport */ switchMapTo; });
__webpack_require__.d(__webpack_exports__, "take", function() { return /* reexport */ take["a" /* take */]; });
__webpack_require__.d(__webpack_exports__, "takeLast", function() { return /* reexport */ takeLast; });
__webpack_require__.d(__webpack_exports__, "takeUntil", function() { return /* reexport */ takeUntil; });
__webpack_require__.d(__webpack_exports__, "takeWhile", function() { return /* reexport */ takeWhile; });
__webpack_require__.d(__webpack_exports__, "tap", function() { return /* reexport */ tap; });
__webpack_require__.d(__webpack_exports__, "throttle", function() { return /* reexport */ throttle; });
__webpack_require__.d(__webpack_exports__, "throttleTime", function() { return /* reexport */ throttleTime; });
__webpack_require__.d(__webpack_exports__, "throwIfEmpty", function() { return /* reexport */ throwIfEmpty; });
__webpack_require__.d(__webpack_exports__, "timeInterval", function() { return /* reexport */ timeInterval; });
__webpack_require__.d(__webpack_exports__, "timeout", function() { return /* reexport */ timeout; });
__webpack_require__.d(__webpack_exports__, "timeoutWith", function() { return /* reexport */ timeoutWith; });
__webpack_require__.d(__webpack_exports__, "timestamp", function() { return /* reexport */ timestamp; });
__webpack_require__.d(__webpack_exports__, "toArray", function() { return /* reexport */ toArray; });
__webpack_require__.d(__webpack_exports__, "window", function() { return /* reexport */ window_window; });
__webpack_require__.d(__webpack_exports__, "windowCount", function() { return /* reexport */ windowCount; });
__webpack_require__.d(__webpack_exports__, "windowTime", function() { return /* reexport */ windowTime_windowTime; });
__webpack_require__.d(__webpack_exports__, "windowToggle", function() { return /* reexport */ windowToggle; });
__webpack_require__.d(__webpack_exports__, "windowWhen", function() { return /* reexport */ windowWhen; });
__webpack_require__.d(__webpack_exports__, "withLatestFrom", function() { return /* reexport */ withLatestFrom; });
__webpack_require__.d(__webpack_exports__, "zip", function() { return /* reexport */ zip_zip; });
__webpack_require__.d(__webpack_exports__, "zipAll", function() { return /* reexport */ zipAll; });

// EXTERNAL MODULE: ./node_modules/rxjs/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(21);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/OuterSubscriber.js
var OuterSubscriber = __webpack_require__(52);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeToResult.js
var subscribeToResult = __webpack_require__(50);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/audit.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function audit(durationSelector) {
    return function auditOperatorFunction(source) {
        return source.lift(new AuditOperator(durationSelector));
    };
}
var AuditOperator = /*@__PURE__*/ (function () {
    function AuditOperator(durationSelector) {
        this.durationSelector = durationSelector;
    }
    AuditOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new audit_AuditSubscriber(subscriber, this.durationSelector));
    };
    return AuditOperator;
}());
var audit_AuditSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AuditSubscriber, _super);
    function AuditSubscriber(destination, durationSelector) {
        var _this = _super.call(this, destination) || this;
        _this.durationSelector = durationSelector;
        _this.hasValue = false;
        return _this;
    }
    AuditSubscriber.prototype._next = function (value) {
        this.value = value;
        this.hasValue = true;
        if (!this.throttled) {
            var duration = void 0;
            try {
                var durationSelector = this.durationSelector;
                duration = durationSelector(value);
            }
            catch (err) {
                return this.destination.error(err);
            }
            var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, duration);
            if (!innerSubscription || innerSubscription.closed) {
                this.clearThrottle();
            }
            else {
                this.add(this.throttled = innerSubscription);
            }
        }
    };
    AuditSubscriber.prototype.clearThrottle = function () {
        var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled;
        if (throttled) {
            this.remove(throttled);
            this.throttled = null;
            throttled.unsubscribe();
        }
        if (hasValue) {
            this.value = null;
            this.hasValue = false;
            this.destination.next(value);
        }
    };
    AuditSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex) {
        this.clearThrottle();
    };
    AuditSubscriber.prototype.notifyComplete = function () {
        this.clearThrottle();
    };
    return AuditSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=audit.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/async.js
var scheduler_async = __webpack_require__(103);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/timer.js
var timer = __webpack_require__(344);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/auditTime.js
/** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */



function auditTime(duration, scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return audit(function () { return Object(timer["a" /* timer */])(duration, scheduler); });
}
//# sourceMappingURL=auditTime.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/buffer.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function buffer_buffer(closingNotifier) {
    return function bufferOperatorFunction(source) {
        return source.lift(new BufferOperator(closingNotifier));
    };
}
var BufferOperator = /*@__PURE__*/ (function () {
    function BufferOperator(closingNotifier) {
        this.closingNotifier = closingNotifier;
    }
    BufferOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new buffer_BufferSubscriber(subscriber, this.closingNotifier));
    };
    return BufferOperator;
}());
var buffer_BufferSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferSubscriber, _super);
    function BufferSubscriber(destination, closingNotifier) {
        var _this = _super.call(this, destination) || this;
        _this.buffer = [];
        _this.add(Object(subscribeToResult["a" /* subscribeToResult */])(_this, closingNotifier));
        return _this;
    }
    BufferSubscriber.prototype._next = function (value) {
        this.buffer.push(value);
    };
    BufferSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        var buffer = this.buffer;
        this.buffer = [];
        this.destination.next(buffer);
    };
    return BufferSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=buffer.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscriber.js
var Subscriber = __webpack_require__(35);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/bufferCount.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function bufferCount(bufferSize, startBufferEvery) {
    if (startBufferEvery === void 0) {
        startBufferEvery = null;
    }
    return function bufferCountOperatorFunction(source) {
        return source.lift(new BufferCountOperator(bufferSize, startBufferEvery));
    };
}
var BufferCountOperator = /*@__PURE__*/ (function () {
    function BufferCountOperator(bufferSize, startBufferEvery) {
        this.bufferSize = bufferSize;
        this.startBufferEvery = startBufferEvery;
        if (!startBufferEvery || bufferSize === startBufferEvery) {
            this.subscriberClass = bufferCount_BufferCountSubscriber;
        }
        else {
            this.subscriberClass = bufferCount_BufferSkipCountSubscriber;
        }
    }
    BufferCountOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery));
    };
    return BufferCountOperator;
}());
var bufferCount_BufferCountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferCountSubscriber, _super);
    function BufferCountSubscriber(destination, bufferSize) {
        var _this = _super.call(this, destination) || this;
        _this.bufferSize = bufferSize;
        _this.buffer = [];
        return _this;
    }
    BufferCountSubscriber.prototype._next = function (value) {
        var buffer = this.buffer;
        buffer.push(value);
        if (buffer.length == this.bufferSize) {
            this.destination.next(buffer);
            this.buffer = [];
        }
    };
    BufferCountSubscriber.prototype._complete = function () {
        var buffer = this.buffer;
        if (buffer.length > 0) {
            this.destination.next(buffer);
        }
        _super.prototype._complete.call(this);
    };
    return BufferCountSubscriber;
}(Subscriber["a" /* Subscriber */]));
var bufferCount_BufferSkipCountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferSkipCountSubscriber, _super);
    function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) {
        var _this = _super.call(this, destination) || this;
        _this.bufferSize = bufferSize;
        _this.startBufferEvery = startBufferEvery;
        _this.buffers = [];
        _this.count = 0;
        return _this;
    }
    BufferSkipCountSubscriber.prototype._next = function (value) {
        var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count;
        this.count++;
        if (count % startBufferEvery === 0) {
            buffers.push([]);
        }
        for (var i = buffers.length; i--;) {
            var buffer = buffers[i];
            buffer.push(value);
            if (buffer.length === bufferSize) {
                buffers.splice(i, 1);
                this.destination.next(buffer);
            }
        }
    };
    BufferSkipCountSubscriber.prototype._complete = function () {
        var _a = this, buffers = _a.buffers, destination = _a.destination;
        while (buffers.length > 0) {
            var buffer = buffers.shift();
            if (buffer.length > 0) {
                destination.next(buffer);
            }
        }
        _super.prototype._complete.call(this);
    };
    return BufferSkipCountSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=bufferCount.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isScheduler.js
var isScheduler = __webpack_require__(122);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/bufferTime.js
/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */




function bufferTime(bufferTimeSpan) {
    var length = arguments.length;
    var scheduler = scheduler_async["a" /* async */];
    if (Object(isScheduler["a" /* isScheduler */])(arguments[arguments.length - 1])) {
        scheduler = arguments[arguments.length - 1];
        length--;
    }
    var bufferCreationInterval = null;
    if (length >= 2) {
        bufferCreationInterval = arguments[1];
    }
    var maxBufferSize = Number.POSITIVE_INFINITY;
    if (length >= 3) {
        maxBufferSize = arguments[2];
    }
    return function bufferTimeOperatorFunction(source) {
        return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler));
    };
}
var BufferTimeOperator = /*@__PURE__*/ (function () {
    function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
        this.bufferTimeSpan = bufferTimeSpan;
        this.bufferCreationInterval = bufferCreationInterval;
        this.maxBufferSize = maxBufferSize;
        this.scheduler = scheduler;
    }
    BufferTimeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new bufferTime_BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler));
    };
    return BufferTimeOperator;
}());
var Context = /*@__PURE__*/ (function () {
    function Context() {
        this.buffer = [];
    }
    return Context;
}());
var bufferTime_BufferTimeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferTimeSubscriber, _super);
    function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.bufferTimeSpan = bufferTimeSpan;
        _this.bufferCreationInterval = bufferCreationInterval;
        _this.maxBufferSize = maxBufferSize;
        _this.scheduler = scheduler;
        _this.contexts = [];
        var context = _this.openContext();
        _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0;
        if (_this.timespanOnly) {
            var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan };
            _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
        }
        else {
            var closeState = { subscriber: _this, context: context };
            var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler };
            _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState));
            _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState));
        }
        return _this;
    }
    BufferTimeSubscriber.prototype._next = function (value) {
        var contexts = this.contexts;
        var len = contexts.length;
        var filledBufferContext;
        for (var i = 0; i < len; i++) {
            var context_1 = contexts[i];
            var buffer = context_1.buffer;
            buffer.push(value);
            if (buffer.length == this.maxBufferSize) {
                filledBufferContext = context_1;
            }
        }
        if (filledBufferContext) {
            this.onBufferFull(filledBufferContext);
        }
    };
    BufferTimeSubscriber.prototype._error = function (err) {
        this.contexts.length = 0;
        _super.prototype._error.call(this, err);
    };
    BufferTimeSubscriber.prototype._complete = function () {
        var _a = this, contexts = _a.contexts, destination = _a.destination;
        while (contexts.length > 0) {
            var context_2 = contexts.shift();
            destination.next(context_2.buffer);
        }
        _super.prototype._complete.call(this);
    };
    BufferTimeSubscriber.prototype._unsubscribe = function () {
        this.contexts = null;
    };
    BufferTimeSubscriber.prototype.onBufferFull = function (context) {
        this.closeContext(context);
        var closeAction = context.closeAction;
        closeAction.unsubscribe();
        this.remove(closeAction);
        if (!this.closed && this.timespanOnly) {
            context = this.openContext();
            var bufferTimeSpan = this.bufferTimeSpan;
            var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan };
            this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState));
        }
    };
    BufferTimeSubscriber.prototype.openContext = function () {
        var context = new Context();
        this.contexts.push(context);
        return context;
    };
    BufferTimeSubscriber.prototype.closeContext = function (context) {
        this.destination.next(context.buffer);
        var contexts = this.contexts;
        var spliceIndex = contexts ? contexts.indexOf(context) : -1;
        if (spliceIndex >= 0) {
            contexts.splice(contexts.indexOf(context), 1);
        }
    };
    return BufferTimeSubscriber;
}(Subscriber["a" /* Subscriber */]));
function dispatchBufferTimeSpanOnly(state) {
    var subscriber = state.subscriber;
    var prevContext = state.context;
    if (prevContext) {
        subscriber.closeContext(prevContext);
    }
    if (!subscriber.closed) {
        state.context = subscriber.openContext();
        state.context.closeAction = this.schedule(state, state.bufferTimeSpan);
    }
}
function dispatchBufferCreation(state) {
    var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler;
    var context = subscriber.openContext();
    var action = this;
    if (!subscriber.closed) {
        subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context }));
        action.schedule(state, bufferCreationInterval);
    }
}
function dispatchBufferClose(arg) {
    var subscriber = arg.subscriber, context = arg.context;
    subscriber.closeContext(context);
}
//# sourceMappingURL=bufferTime.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscription.js
var Subscription = __webpack_require__(70);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/bufferToggle.js
/** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */




function bufferToggle(openings, closingSelector) {
    return function bufferToggleOperatorFunction(source) {
        return source.lift(new BufferToggleOperator(openings, closingSelector));
    };
}
var BufferToggleOperator = /*@__PURE__*/ (function () {
    function BufferToggleOperator(openings, closingSelector) {
        this.openings = openings;
        this.closingSelector = closingSelector;
    }
    BufferToggleOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new bufferToggle_BufferToggleSubscriber(subscriber, this.openings, this.closingSelector));
    };
    return BufferToggleOperator;
}());
var bufferToggle_BufferToggleSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferToggleSubscriber, _super);
    function BufferToggleSubscriber(destination, openings, closingSelector) {
        var _this = _super.call(this, destination) || this;
        _this.openings = openings;
        _this.closingSelector = closingSelector;
        _this.contexts = [];
        _this.add(Object(subscribeToResult["a" /* subscribeToResult */])(_this, openings));
        return _this;
    }
    BufferToggleSubscriber.prototype._next = function (value) {
        var contexts = this.contexts;
        var len = contexts.length;
        for (var i = 0; i < len; i++) {
            contexts[i].buffer.push(value);
        }
    };
    BufferToggleSubscriber.prototype._error = function (err) {
        var contexts = this.contexts;
        while (contexts.length > 0) {
            var context_1 = contexts.shift();
            context_1.subscription.unsubscribe();
            context_1.buffer = null;
            context_1.subscription = null;
        }
        this.contexts = null;
        _super.prototype._error.call(this, err);
    };
    BufferToggleSubscriber.prototype._complete = function () {
        var contexts = this.contexts;
        while (contexts.length > 0) {
            var context_2 = contexts.shift();
            this.destination.next(context_2.buffer);
            context_2.subscription.unsubscribe();
            context_2.buffer = null;
            context_2.subscription = null;
        }
        this.contexts = null;
        _super.prototype._complete.call(this);
    };
    BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue);
    };
    BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) {
        this.closeBuffer(innerSub.context);
    };
    BufferToggleSubscriber.prototype.openBuffer = function (value) {
        try {
            var closingSelector = this.closingSelector;
            var closingNotifier = closingSelector.call(this, value);
            if (closingNotifier) {
                this.trySubscribe(closingNotifier);
            }
        }
        catch (err) {
            this._error(err);
        }
    };
    BufferToggleSubscriber.prototype.closeBuffer = function (context) {
        var contexts = this.contexts;
        if (contexts && context) {
            var buffer = context.buffer, subscription = context.subscription;
            this.destination.next(buffer);
            contexts.splice(contexts.indexOf(context), 1);
            this.remove(subscription);
            subscription.unsubscribe();
        }
    };
    BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) {
        var contexts = this.contexts;
        var buffer = [];
        var subscription = new Subscription["a" /* Subscription */]();
        var context = { buffer: buffer, subscription: subscription };
        contexts.push(context);
        var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, closingNotifier, context);
        if (!innerSubscription || innerSubscription.closed) {
            this.closeBuffer(context);
        }
        else {
            innerSubscription.context = context;
            this.add(innerSubscription);
            subscription.add(innerSubscription);
        }
    };
    return BufferToggleSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=bufferToggle.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/bufferWhen.js
/** PURE_IMPORTS_START tslib,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function bufferWhen(closingSelector) {
    return function (source) {
        return source.lift(new BufferWhenOperator(closingSelector));
    };
}
var BufferWhenOperator = /*@__PURE__*/ (function () {
    function BufferWhenOperator(closingSelector) {
        this.closingSelector = closingSelector;
    }
    BufferWhenOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new bufferWhen_BufferWhenSubscriber(subscriber, this.closingSelector));
    };
    return BufferWhenOperator;
}());
var bufferWhen_BufferWhenSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](BufferWhenSubscriber, _super);
    function BufferWhenSubscriber(destination, closingSelector) {
        var _this = _super.call(this, destination) || this;
        _this.closingSelector = closingSelector;
        _this.subscribing = false;
        _this.openBuffer();
        return _this;
    }
    BufferWhenSubscriber.prototype._next = function (value) {
        this.buffer.push(value);
    };
    BufferWhenSubscriber.prototype._complete = function () {
        var buffer = this.buffer;
        if (buffer) {
            this.destination.next(buffer);
        }
        _super.prototype._complete.call(this);
    };
    BufferWhenSubscriber.prototype._unsubscribe = function () {
        this.buffer = null;
        this.subscribing = false;
    };
    BufferWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.openBuffer();
    };
    BufferWhenSubscriber.prototype.notifyComplete = function () {
        if (this.subscribing) {
            this.complete();
        }
        else {
            this.openBuffer();
        }
    };
    BufferWhenSubscriber.prototype.openBuffer = function () {
        var closingSubscription = this.closingSubscription;
        if (closingSubscription) {
            this.remove(closingSubscription);
            closingSubscription.unsubscribe();
        }
        var buffer = this.buffer;
        if (this.buffer) {
            this.destination.next(buffer);
        }
        this.buffer = [];
        var closingNotifier;
        try {
            var closingSelector = this.closingSelector;
            closingNotifier = closingSelector();
        }
        catch (err) {
            return this.error(err);
        }
        closingSubscription = new Subscription["a" /* Subscription */]();
        this.closingSubscription = closingSubscription;
        this.add(closingSubscription);
        this.subscribing = true;
        closingSubscription.add(Object(subscribeToResult["a" /* subscribeToResult */])(this, closingNotifier));
        this.subscribing = false;
    };
    return BufferWhenSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=bufferWhen.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/InnerSubscriber.js
var InnerSubscriber = __webpack_require__(167);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/catchError.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function catchError(selector) {
    return function catchErrorOperatorFunction(source) {
        var operator = new CatchOperator(selector);
        var caught = source.lift(operator);
        return (operator.caught = caught);
    };
}
var CatchOperator = /*@__PURE__*/ (function () {
    function CatchOperator(selector) {
        this.selector = selector;
    }
    CatchOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new catchError_CatchSubscriber(subscriber, this.selector, this.caught));
    };
    return CatchOperator;
}());
var catchError_CatchSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](CatchSubscriber, _super);
    function CatchSubscriber(destination, selector, caught) {
        var _this = _super.call(this, destination) || this;
        _this.selector = selector;
        _this.caught = caught;
        return _this;
    }
    CatchSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var result = void 0;
            try {
                result = this.selector(err, this.caught);
            }
            catch (err2) {
                _super.prototype.error.call(this, err2);
                return;
            }
            this._unsubscribeAndRecycle();
            var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](this, undefined, undefined);
            this.add(innerSubscriber);
            var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, result, undefined, undefined, innerSubscriber);
            if (innerSubscription !== innerSubscriber) {
                this.add(innerSubscription);
            }
        }
    };
    return CatchSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=catchError.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/combineLatest.js
var combineLatest = __webpack_require__(294);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/combineAll.js
/** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */

function combineAll(project) {
    return function (source) { return source.lift(new combineLatest["a" /* CombineLatestOperator */](project)); };
}
//# sourceMappingURL=combineAll.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isArray.js
var isArray = __webpack_require__(100);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/from.js
var from = __webpack_require__(140);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/combineLatest.js
/** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */



var none = {};
function combineLatest_combineLatest() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    var project = null;
    if (typeof observables[observables.length - 1] === 'function') {
        project = observables.pop();
    }
    if (observables.length === 1 && Object(isArray["a" /* isArray */])(observables[0])) {
        observables = observables[0].slice();
    }
    return function (source) { return source.lift.call(Object(from["a" /* from */])([source].concat(observables)), new combineLatest["a" /* CombineLatestOperator */](project)); };
}
//# sourceMappingURL=combineLatest.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/concat.js
var concat = __webpack_require__(240);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/concat.js
/** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */

function concat_concat() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    return function (source) { return source.lift.call(concat["a" /* concat */].apply(void 0, [source].concat(observables))); };
}
//# sourceMappingURL=concat.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/concatAll.js
var concatAll = __webpack_require__(345);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/mergeMap.js
var mergeMap = __webpack_require__(213);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/concatMap.js
/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */

function concatMap(project, resultSelector) {
    return Object(mergeMap["a" /* mergeMap */])(project, resultSelector, 1);
}
//# sourceMappingURL=concatMap.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/concatMapTo.js
/** PURE_IMPORTS_START _concatMap PURE_IMPORTS_END */

function concatMapTo(innerObservable, resultSelector) {
    return concatMap(function () { return innerObservable; }, resultSelector);
}
//# sourceMappingURL=concatMapTo.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/count.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function count_count(predicate) {
    return function (source) { return source.lift(new CountOperator(predicate, source)); };
}
var CountOperator = /*@__PURE__*/ (function () {
    function CountOperator(predicate, source) {
        this.predicate = predicate;
        this.source = source;
    }
    CountOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new count_CountSubscriber(subscriber, this.predicate, this.source));
    };
    return CountOperator;
}());
var count_CountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](CountSubscriber, _super);
    function CountSubscriber(destination, predicate, source) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.source = source;
        _this.count = 0;
        _this.index = 0;
        return _this;
    }
    CountSubscriber.prototype._next = function (value) {
        if (this.predicate) {
            this._tryPredicate(value);
        }
        else {
            this.count++;
        }
    };
    CountSubscriber.prototype._tryPredicate = function (value) {
        var result;
        try {
            result = this.predicate(value, this.index++, this.source);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        if (result) {
            this.count++;
        }
    };
    CountSubscriber.prototype._complete = function () {
        this.destination.next(this.count);
        this.destination.complete();
    };
    return CountSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=count.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/debounce.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function debounce(durationSelector) {
    return function (source) { return source.lift(new DebounceOperator(durationSelector)); };
}
var DebounceOperator = /*@__PURE__*/ (function () {
    function DebounceOperator(durationSelector) {
        this.durationSelector = durationSelector;
    }
    DebounceOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new debounce_DebounceSubscriber(subscriber, this.durationSelector));
    };
    return DebounceOperator;
}());
var debounce_DebounceSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DebounceSubscriber, _super);
    function DebounceSubscriber(destination, durationSelector) {
        var _this = _super.call(this, destination) || this;
        _this.durationSelector = durationSelector;
        _this.hasValue = false;
        _this.durationSubscription = null;
        return _this;
    }
    DebounceSubscriber.prototype._next = function (value) {
        try {
            var result = this.durationSelector.call(this, value);
            if (result) {
                this._tryNext(value, result);
            }
        }
        catch (err) {
            this.destination.error(err);
        }
    };
    DebounceSubscriber.prototype._complete = function () {
        this.emitValue();
        this.destination.complete();
    };
    DebounceSubscriber.prototype._tryNext = function (value, duration) {
        var subscription = this.durationSubscription;
        this.value = value;
        this.hasValue = true;
        if (subscription) {
            subscription.unsubscribe();
            this.remove(subscription);
        }
        subscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, duration);
        if (subscription && !subscription.closed) {
            this.add(this.durationSubscription = subscription);
        }
    };
    DebounceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.emitValue();
    };
    DebounceSubscriber.prototype.notifyComplete = function () {
        this.emitValue();
    };
    DebounceSubscriber.prototype.emitValue = function () {
        if (this.hasValue) {
            var value = this.value;
            var subscription = this.durationSubscription;
            if (subscription) {
                this.durationSubscription = null;
                subscription.unsubscribe();
                this.remove(subscription);
            }
            this.value = null;
            this.hasValue = false;
            _super.prototype._next.call(this, value);
        }
    };
    return DebounceSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=debounce.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/debounceTime.js
var debounceTime = __webpack_require__(388);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/defaultIfEmpty.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function defaultIfEmpty(defaultValue) {
    if (defaultValue === void 0) {
        defaultValue = null;
    }
    return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); };
}
var DefaultIfEmptyOperator = /*@__PURE__*/ (function () {
    function DefaultIfEmptyOperator(defaultValue) {
        this.defaultValue = defaultValue;
    }
    DefaultIfEmptyOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new defaultIfEmpty_DefaultIfEmptySubscriber(subscriber, this.defaultValue));
    };
    return DefaultIfEmptyOperator;
}());
var defaultIfEmpty_DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DefaultIfEmptySubscriber, _super);
    function DefaultIfEmptySubscriber(destination, defaultValue) {
        var _this = _super.call(this, destination) || this;
        _this.defaultValue = defaultValue;
        _this.isEmpty = true;
        return _this;
    }
    DefaultIfEmptySubscriber.prototype._next = function (value) {
        this.isEmpty = false;
        this.destination.next(value);
    };
    DefaultIfEmptySubscriber.prototype._complete = function () {
        if (this.isEmpty) {
            this.destination.next(this.defaultValue);
        }
        this.destination.complete();
    };
    return DefaultIfEmptySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=defaultIfEmpty.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/isDate.js
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isDate(value) {
    return value instanceof Date && !isNaN(+value);
}
//# sourceMappingURL=isDate.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Notification.js
var Notification = __webpack_require__(190);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/delay.js
/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */





function delay_delay(delay, scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    var absoluteDelay = isDate(delay);
    var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay);
    return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); };
}
var DelayOperator = /*@__PURE__*/ (function () {
    function DelayOperator(delay, scheduler) {
        this.delay = delay;
        this.scheduler = scheduler;
    }
    DelayOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new delay_DelaySubscriber(subscriber, this.delay, this.scheduler));
    };
    return DelayOperator;
}());
var delay_DelaySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DelaySubscriber, _super);
    function DelaySubscriber(destination, delay, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.delay = delay;
        _this.scheduler = scheduler;
        _this.queue = [];
        _this.active = false;
        _this.errored = false;
        return _this;
    }
    DelaySubscriber.dispatch = function (state) {
        var source = state.source;
        var queue = source.queue;
        var scheduler = state.scheduler;
        var destination = state.destination;
        while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) {
            queue.shift().notification.observe(destination);
        }
        if (queue.length > 0) {
            var delay_1 = Math.max(0, queue[0].time - scheduler.now());
            this.schedule(state, delay_1);
        }
        else {
            this.unsubscribe();
            source.active = false;
        }
    };
    DelaySubscriber.prototype._schedule = function (scheduler) {
        this.active = true;
        var destination = this.destination;
        destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, {
            source: this, destination: this.destination, scheduler: scheduler
        }));
    };
    DelaySubscriber.prototype.scheduleNotification = function (notification) {
        if (this.errored === true) {
            return;
        }
        var scheduler = this.scheduler;
        var message = new DelayMessage(scheduler.now() + this.delay, notification);
        this.queue.push(message);
        if (this.active === false) {
            this._schedule(scheduler);
        }
    };
    DelaySubscriber.prototype._next = function (value) {
        this.scheduleNotification(Notification["a" /* Notification */].createNext(value));
    };
    DelaySubscriber.prototype._error = function (err) {
        this.errored = true;
        this.queue = [];
        this.destination.error(err);
        this.unsubscribe();
    };
    DelaySubscriber.prototype._complete = function () {
        this.scheduleNotification(Notification["a" /* Notification */].createComplete());
        this.unsubscribe();
    };
    return DelaySubscriber;
}(Subscriber["a" /* Subscriber */]));
var DelayMessage = /*@__PURE__*/ (function () {
    function DelayMessage(time, notification) {
        this.time = time;
        this.notification = notification;
    }
    return DelayMessage;
}());
//# sourceMappingURL=delay.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Observable.js + 1 modules
var Observable = __webpack_require__(44);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/delayWhen.js
/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */





function delayWhen(delayDurationSelector, subscriptionDelay) {
    if (subscriptionDelay) {
        return function (source) {
            return new delayWhen_SubscriptionDelayObservable(source, subscriptionDelay)
                .lift(new DelayWhenOperator(delayDurationSelector));
        };
    }
    return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); };
}
var DelayWhenOperator = /*@__PURE__*/ (function () {
    function DelayWhenOperator(delayDurationSelector) {
        this.delayDurationSelector = delayDurationSelector;
    }
    DelayWhenOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new delayWhen_DelayWhenSubscriber(subscriber, this.delayDurationSelector));
    };
    return DelayWhenOperator;
}());
var delayWhen_DelayWhenSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DelayWhenSubscriber, _super);
    function DelayWhenSubscriber(destination, delayDurationSelector) {
        var _this = _super.call(this, destination) || this;
        _this.delayDurationSelector = delayDurationSelector;
        _this.completed = false;
        _this.delayNotifierSubscriptions = [];
        _this.index = 0;
        return _this;
    }
    DelayWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(outerValue);
        this.removeSubscription(innerSub);
        this.tryComplete();
    };
    DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) {
        this._error(error);
    };
    DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) {
        var value = this.removeSubscription(innerSub);
        if (value) {
            this.destination.next(value);
        }
        this.tryComplete();
    };
    DelayWhenSubscriber.prototype._next = function (value) {
        var index = this.index++;
        try {
            var delayNotifier = this.delayDurationSelector(value, index);
            if (delayNotifier) {
                this.tryDelay(delayNotifier, value);
            }
        }
        catch (err) {
            this.destination.error(err);
        }
    };
    DelayWhenSubscriber.prototype._complete = function () {
        this.completed = true;
        this.tryComplete();
        this.unsubscribe();
    };
    DelayWhenSubscriber.prototype.removeSubscription = function (subscription) {
        subscription.unsubscribe();
        var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription);
        if (subscriptionIdx !== -1) {
            this.delayNotifierSubscriptions.splice(subscriptionIdx, 1);
        }
        return subscription.outerValue;
    };
    DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) {
        var notifierSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, delayNotifier, value);
        if (notifierSubscription && !notifierSubscription.closed) {
            var destination = this.destination;
            destination.add(notifierSubscription);
            this.delayNotifierSubscriptions.push(notifierSubscription);
        }
    };
    DelayWhenSubscriber.prototype.tryComplete = function () {
        if (this.completed && this.delayNotifierSubscriptions.length === 0) {
            this.destination.complete();
        }
    };
    return DelayWhenSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
var delayWhen_SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SubscriptionDelayObservable, _super);
    function SubscriptionDelayObservable(source, subscriptionDelay) {
        var _this = _super.call(this) || this;
        _this.source = source;
        _this.subscriptionDelay = subscriptionDelay;
        return _this;
    }
    SubscriptionDelayObservable.prototype._subscribe = function (subscriber) {
        this.subscriptionDelay.subscribe(new delayWhen_SubscriptionDelaySubscriber(subscriber, this.source));
    };
    return SubscriptionDelayObservable;
}(Observable["a" /* Observable */]));
var delayWhen_SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SubscriptionDelaySubscriber, _super);
    function SubscriptionDelaySubscriber(parent, source) {
        var _this = _super.call(this) || this;
        _this.parent = parent;
        _this.source = source;
        _this.sourceSubscribed = false;
        return _this;
    }
    SubscriptionDelaySubscriber.prototype._next = function (unused) {
        this.subscribeToSource();
    };
    SubscriptionDelaySubscriber.prototype._error = function (err) {
        this.unsubscribe();
        this.parent.error(err);
    };
    SubscriptionDelaySubscriber.prototype._complete = function () {
        this.unsubscribe();
        this.subscribeToSource();
    };
    SubscriptionDelaySubscriber.prototype.subscribeToSource = function () {
        if (!this.sourceSubscribed) {
            this.sourceSubscribed = true;
            this.unsubscribe();
            this.source.subscribe(this.parent);
        }
    };
    return SubscriptionDelaySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=delayWhen.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/dematerialize.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function dematerialize() {
    return function dematerializeOperatorFunction(source) {
        return source.lift(new DeMaterializeOperator());
    };
}
var DeMaterializeOperator = /*@__PURE__*/ (function () {
    function DeMaterializeOperator() {
    }
    DeMaterializeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new dematerialize_DeMaterializeSubscriber(subscriber));
    };
    return DeMaterializeOperator;
}());
var dematerialize_DeMaterializeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DeMaterializeSubscriber, _super);
    function DeMaterializeSubscriber(destination) {
        return _super.call(this, destination) || this;
    }
    DeMaterializeSubscriber.prototype._next = function (value) {
        value.observe(this.destination);
    };
    return DeMaterializeSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=dematerialize.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/distinct.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function distinct(keySelector, flushes) {
    return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); };
}
var DistinctOperator = /*@__PURE__*/ (function () {
    function DistinctOperator(keySelector, flushes) {
        this.keySelector = keySelector;
        this.flushes = flushes;
    }
    DistinctOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new distinct_DistinctSubscriber(subscriber, this.keySelector, this.flushes));
    };
    return DistinctOperator;
}());
var distinct_DistinctSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DistinctSubscriber, _super);
    function DistinctSubscriber(destination, keySelector, flushes) {
        var _this = _super.call(this, destination) || this;
        _this.keySelector = keySelector;
        _this.values = new Set();
        if (flushes) {
            _this.add(Object(subscribeToResult["a" /* subscribeToResult */])(_this, flushes));
        }
        return _this;
    }
    DistinctSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.values.clear();
    };
    DistinctSubscriber.prototype.notifyError = function (error, innerSub) {
        this._error(error);
    };
    DistinctSubscriber.prototype._next = function (value) {
        if (this.keySelector) {
            this._useKeySelector(value);
        }
        else {
            this._finalizeNext(value, value);
        }
    };
    DistinctSubscriber.prototype._useKeySelector = function (value) {
        var key;
        var destination = this.destination;
        try {
            key = this.keySelector(value);
        }
        catch (err) {
            destination.error(err);
            return;
        }
        this._finalizeNext(key, value);
    };
    DistinctSubscriber.prototype._finalizeNext = function (key, value) {
        var values = this.values;
        if (!values.has(key)) {
            values.add(key);
            this.destination.next(value);
        }
    };
    return DistinctSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));

//# sourceMappingURL=distinct.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/distinctUntilChanged.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function distinctUntilChanged(compare, keySelector) {
    return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); };
}
var DistinctUntilChangedOperator = /*@__PURE__*/ (function () {
    function DistinctUntilChangedOperator(compare, keySelector) {
        this.compare = compare;
        this.keySelector = keySelector;
    }
    DistinctUntilChangedOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new distinctUntilChanged_DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector));
    };
    return DistinctUntilChangedOperator;
}());
var distinctUntilChanged_DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](DistinctUntilChangedSubscriber, _super);
    function DistinctUntilChangedSubscriber(destination, compare, keySelector) {
        var _this = _super.call(this, destination) || this;
        _this.keySelector = keySelector;
        _this.hasKey = false;
        if (typeof compare === 'function') {
            _this.compare = compare;
        }
        return _this;
    }
    DistinctUntilChangedSubscriber.prototype.compare = function (x, y) {
        return x === y;
    };
    DistinctUntilChangedSubscriber.prototype._next = function (value) {
        var key;
        try {
            var keySelector = this.keySelector;
            key = keySelector ? keySelector(value) : value;
        }
        catch (err) {
            return this.destination.error(err);
        }
        var result = false;
        if (this.hasKey) {
            try {
                var compare = this.compare;
                result = compare(this.key, key);
            }
            catch (err) {
                return this.destination.error(err);
            }
        }
        else {
            this.hasKey = true;
        }
        if (!result) {
            this.key = key;
            this.destination.next(value);
        }
    };
    return DistinctUntilChangedSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=distinctUntilChanged.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/distinctUntilKeyChanged.js
/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */

function distinctUntilKeyChanged(key, compare) {
    return distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; });
}
//# sourceMappingURL=distinctUntilKeyChanged.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/ArgumentOutOfRangeError.js
var ArgumentOutOfRangeError = __webpack_require__(214);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/filter.js
var filter = __webpack_require__(169);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/EmptyError.js
var EmptyError = __webpack_require__(220);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/throwIfEmpty.js
/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */



function throwIfEmpty(errorFactory) {
    if (errorFactory === void 0) {
        errorFactory = defaultErrorFactory;
    }
    return function (source) {
        return source.lift(new ThrowIfEmptyOperator(errorFactory));
    };
}
var ThrowIfEmptyOperator = /*@__PURE__*/ (function () {
    function ThrowIfEmptyOperator(errorFactory) {
        this.errorFactory = errorFactory;
    }
    ThrowIfEmptyOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new throwIfEmpty_ThrowIfEmptySubscriber(subscriber, this.errorFactory));
    };
    return ThrowIfEmptyOperator;
}());
var throwIfEmpty_ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ThrowIfEmptySubscriber, _super);
    function ThrowIfEmptySubscriber(destination, errorFactory) {
        var _this = _super.call(this, destination) || this;
        _this.errorFactory = errorFactory;
        _this.hasValue = false;
        return _this;
    }
    ThrowIfEmptySubscriber.prototype._next = function (value) {
        this.hasValue = true;
        this.destination.next(value);
    };
    ThrowIfEmptySubscriber.prototype._complete = function () {
        if (!this.hasValue) {
            var err = void 0;
            try {
                err = this.errorFactory();
            }
            catch (e) {
                err = e;
            }
            this.destination.error(err);
        }
        else {
            return this.destination.complete();
        }
    };
    return ThrowIfEmptySubscriber;
}(Subscriber["a" /* Subscriber */]));
function defaultErrorFactory() {
    return new EmptyError["a" /* EmptyError */]();
}
//# sourceMappingURL=throwIfEmpty.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/take.js
var take = __webpack_require__(293);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/elementAt.js
/** PURE_IMPORTS_START _util_ArgumentOutOfRangeError,_filter,_throwIfEmpty,_defaultIfEmpty,_take PURE_IMPORTS_END */





function elementAt(index, defaultValue) {
    if (index < 0) {
        throw new ArgumentOutOfRangeError["a" /* ArgumentOutOfRangeError */]();
    }
    var hasDefaultValue = arguments.length >= 2;
    return function (source) {
        return source.pipe(Object(filter["a" /* filter */])(function (v, i) { return i === index; }), Object(take["a" /* take */])(1), hasDefaultValue
            ? defaultIfEmpty(defaultValue)
            : throwIfEmpty(function () { return new ArgumentOutOfRangeError["a" /* ArgumentOutOfRangeError */](); }));
    };
}
//# sourceMappingURL=elementAt.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/of.js
var of = __webpack_require__(254);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/endWith.js
/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */


function endWith() {
    var array = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        array[_i] = arguments[_i];
    }
    return function (source) { return Object(concat["a" /* concat */])(source, of["a" /* of */].apply(void 0, array)); };
}
//# sourceMappingURL=endWith.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/every.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function every(predicate, thisArg) {
    return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); };
}
var EveryOperator = /*@__PURE__*/ (function () {
    function EveryOperator(predicate, thisArg, source) {
        this.predicate = predicate;
        this.thisArg = thisArg;
        this.source = source;
    }
    EveryOperator.prototype.call = function (observer, source) {
        return source.subscribe(new every_EverySubscriber(observer, this.predicate, this.thisArg, this.source));
    };
    return EveryOperator;
}());
var every_EverySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](EverySubscriber, _super);
    function EverySubscriber(destination, predicate, thisArg, source) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.thisArg = thisArg;
        _this.source = source;
        _this.index = 0;
        _this.thisArg = thisArg || _this;
        return _this;
    }
    EverySubscriber.prototype.notifyComplete = function (everyValueMatch) {
        this.destination.next(everyValueMatch);
        this.destination.complete();
    };
    EverySubscriber.prototype._next = function (value) {
        var result = false;
        try {
            result = this.predicate.call(this.thisArg, value, this.index++, this.source);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        if (!result) {
            this.notifyComplete(false);
        }
    };
    EverySubscriber.prototype._complete = function () {
        this.notifyComplete(true);
    };
    return EverySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=every.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/exhaust.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function exhaust() {
    return function (source) { return source.lift(new SwitchFirstOperator()); };
}
var SwitchFirstOperator = /*@__PURE__*/ (function () {
    function SwitchFirstOperator() {
    }
    SwitchFirstOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new exhaust_SwitchFirstSubscriber(subscriber));
    };
    return SwitchFirstOperator;
}());
var exhaust_SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SwitchFirstSubscriber, _super);
    function SwitchFirstSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.hasCompleted = false;
        _this.hasSubscription = false;
        return _this;
    }
    SwitchFirstSubscriber.prototype._next = function (value) {
        if (!this.hasSubscription) {
            this.hasSubscription = true;
            this.add(Object(subscribeToResult["a" /* subscribeToResult */])(this, value));
        }
    };
    SwitchFirstSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (!this.hasSubscription) {
            this.destination.complete();
        }
    };
    SwitchFirstSubscriber.prototype.notifyComplete = function (innerSub) {
        this.remove(innerSub);
        this.hasSubscription = false;
        if (this.hasCompleted) {
            this.destination.complete();
        }
    };
    return SwitchFirstSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=exhaust.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/map.js
var map = __webpack_require__(116);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/exhaustMap.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */






function exhaustMap(project, resultSelector) {
    if (resultSelector) {
        return function (source) { return source.pipe(exhaustMap(function (a, i) { return Object(from["a" /* from */])(project(a, i)).pipe(Object(map["a" /* map */])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
    }
    return function (source) {
        return source.lift(new ExhaustMapOperator(project));
    };
}
var ExhaustMapOperator = /*@__PURE__*/ (function () {
    function ExhaustMapOperator(project) {
        this.project = project;
    }
    ExhaustMapOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new exhaustMap_ExhaustMapSubscriber(subscriber, this.project));
    };
    return ExhaustMapOperator;
}());
var exhaustMap_ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ExhaustMapSubscriber, _super);
    function ExhaustMapSubscriber(destination, project) {
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.hasSubscription = false;
        _this.hasCompleted = false;
        _this.index = 0;
        return _this;
    }
    ExhaustMapSubscriber.prototype._next = function (value) {
        if (!this.hasSubscription) {
            this.tryNext(value);
        }
    };
    ExhaustMapSubscriber.prototype.tryNext = function (value) {
        var result;
        var index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.hasSubscription = true;
        this._innerSub(result, value, index);
    };
    ExhaustMapSubscriber.prototype._innerSub = function (result, value, index) {
        var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](this, value, index);
        var destination = this.destination;
        destination.add(innerSubscriber);
        var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, result, undefined, undefined, innerSubscriber);
        if (innerSubscription !== innerSubscriber) {
            destination.add(innerSubscription);
        }
    };
    ExhaustMapSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (!this.hasSubscription) {
            this.destination.complete();
        }
        this.unsubscribe();
    };
    ExhaustMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(innerValue);
    };
    ExhaustMapSubscriber.prototype.notifyError = function (err) {
        this.destination.error(err);
    };
    ExhaustMapSubscriber.prototype.notifyComplete = function (innerSub) {
        var destination = this.destination;
        destination.remove(innerSub);
        this.hasSubscription = false;
        if (this.hasCompleted) {
            this.destination.complete();
        }
    };
    return ExhaustMapSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=exhaustMap.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/expand.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function expand(project, concurrent, scheduler) {
    if (concurrent === void 0) {
        concurrent = Number.POSITIVE_INFINITY;
    }
    if (scheduler === void 0) {
        scheduler = undefined;
    }
    concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent;
    return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); };
}
var ExpandOperator = /*@__PURE__*/ (function () {
    function ExpandOperator(project, concurrent, scheduler) {
        this.project = project;
        this.concurrent = concurrent;
        this.scheduler = scheduler;
    }
    ExpandOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new expand_ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler));
    };
    return ExpandOperator;
}());

var expand_ExpandSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ExpandSubscriber, _super);
    function ExpandSubscriber(destination, project, concurrent, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.concurrent = concurrent;
        _this.scheduler = scheduler;
        _this.index = 0;
        _this.active = 0;
        _this.hasCompleted = false;
        if (concurrent < Number.POSITIVE_INFINITY) {
            _this.buffer = [];
        }
        return _this;
    }
    ExpandSubscriber.dispatch = function (arg) {
        var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index;
        subscriber.subscribeToProjection(result, value, index);
    };
    ExpandSubscriber.prototype._next = function (value) {
        var destination = this.destination;
        if (destination.closed) {
            this._complete();
            return;
        }
        var index = this.index++;
        if (this.active < this.concurrent) {
            destination.next(value);
            try {
                var project = this.project;
                var result = project(value, index);
                if (!this.scheduler) {
                    this.subscribeToProjection(result, value, index);
                }
                else {
                    var state = { subscriber: this, result: result, value: value, index: index };
                    var destination_1 = this.destination;
                    destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state));
                }
            }
            catch (e) {
                destination.error(e);
            }
        }
        else {
            this.buffer.push(value);
        }
    };
    ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) {
        this.active++;
        var destination = this.destination;
        destination.add(Object(subscribeToResult["a" /* subscribeToResult */])(this, result, value, index));
    };
    ExpandSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (this.hasCompleted && this.active === 0) {
            this.destination.complete();
        }
        this.unsubscribe();
    };
    ExpandSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this._next(innerValue);
    };
    ExpandSubscriber.prototype.notifyComplete = function (innerSub) {
        var buffer = this.buffer;
        var destination = this.destination;
        destination.remove(innerSub);
        this.active--;
        if (buffer && buffer.length > 0) {
            this._next(buffer.shift());
        }
        if (this.hasCompleted && this.active === 0) {
            this.destination.complete();
        }
    };
    return ExpandSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));

//# sourceMappingURL=expand.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/finalize.js
/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */



function finalize(callback) {
    return function (source) { return source.lift(new FinallyOperator(callback)); };
}
var FinallyOperator = /*@__PURE__*/ (function () {
    function FinallyOperator(callback) {
        this.callback = callback;
    }
    FinallyOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new finalize_FinallySubscriber(subscriber, this.callback));
    };
    return FinallyOperator;
}());
var finalize_FinallySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](FinallySubscriber, _super);
    function FinallySubscriber(destination, callback) {
        var _this = _super.call(this, destination) || this;
        _this.add(new Subscription["a" /* Subscription */](callback));
        return _this;
    }
    return FinallySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=finalize.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/find.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function find(predicate, thisArg) {
    if (typeof predicate !== 'function') {
        throw new TypeError('predicate is not a function');
    }
    return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); };
}
var FindValueOperator = /*@__PURE__*/ (function () {
    function FindValueOperator(predicate, source, yieldIndex, thisArg) {
        this.predicate = predicate;
        this.source = source;
        this.yieldIndex = yieldIndex;
        this.thisArg = thisArg;
    }
    FindValueOperator.prototype.call = function (observer, source) {
        return source.subscribe(new find_FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg));
    };
    return FindValueOperator;
}());

var find_FindValueSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](FindValueSubscriber, _super);
    function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.source = source;
        _this.yieldIndex = yieldIndex;
        _this.thisArg = thisArg;
        _this.index = 0;
        return _this;
    }
    FindValueSubscriber.prototype.notifyComplete = function (value) {
        var destination = this.destination;
        destination.next(value);
        destination.complete();
        this.unsubscribe();
    };
    FindValueSubscriber.prototype._next = function (value) {
        var _a = this, predicate = _a.predicate, thisArg = _a.thisArg;
        var index = this.index++;
        try {
            var result = predicate.call(thisArg || this, value, index, this.source);
            if (result) {
                this.notifyComplete(this.yieldIndex ? index : value);
            }
        }
        catch (err) {
            this.destination.error(err);
        }
    };
    FindValueSubscriber.prototype._complete = function () {
        this.notifyComplete(this.yieldIndex ? -1 : undefined);
    };
    return FindValueSubscriber;
}(Subscriber["a" /* Subscriber */]));

//# sourceMappingURL=find.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/findIndex.js
/** PURE_IMPORTS_START _operators_find PURE_IMPORTS_END */

function findIndex(predicate, thisArg) {
    return function (source) { return source.lift(new FindValueOperator(predicate, source, true, thisArg)); };
}
//# sourceMappingURL=findIndex.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/identity.js
var identity = __webpack_require__(181);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/first.js
/** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */






function first(predicate, defaultValue) {
    var hasDefaultValue = arguments.length >= 2;
    return function (source) { return source.pipe(predicate ? Object(filter["a" /* filter */])(function (v, i) { return predicate(v, i, source); }) : identity["a" /* identity */], Object(take["a" /* take */])(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError["a" /* EmptyError */](); })); };
}
//# sourceMappingURL=first.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/groupBy.js
var groupBy = __webpack_require__(336);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/ignoreElements.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function ignoreElements() {
    return function ignoreElementsOperatorFunction(source) {
        return source.lift(new IgnoreElementsOperator());
    };
}
var IgnoreElementsOperator = /*@__PURE__*/ (function () {
    function IgnoreElementsOperator() {
    }
    IgnoreElementsOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new ignoreElements_IgnoreElementsSubscriber(subscriber));
    };
    return IgnoreElementsOperator;
}());
var ignoreElements_IgnoreElementsSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](IgnoreElementsSubscriber, _super);
    function IgnoreElementsSubscriber() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    IgnoreElementsSubscriber.prototype._next = function (unused) {
    };
    return IgnoreElementsSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=ignoreElements.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/isEmpty.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function isEmpty() {
    return function (source) { return source.lift(new IsEmptyOperator()); };
}
var IsEmptyOperator = /*@__PURE__*/ (function () {
    function IsEmptyOperator() {
    }
    IsEmptyOperator.prototype.call = function (observer, source) {
        return source.subscribe(new isEmpty_IsEmptySubscriber(observer));
    };
    return IsEmptyOperator;
}());
var isEmpty_IsEmptySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](IsEmptySubscriber, _super);
    function IsEmptySubscriber(destination) {
        return _super.call(this, destination) || this;
    }
    IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) {
        var destination = this.destination;
        destination.next(isEmpty);
        destination.complete();
    };
    IsEmptySubscriber.prototype._next = function (value) {
        this.notifyComplete(false);
    };
    IsEmptySubscriber.prototype._complete = function () {
        this.notifyComplete(true);
    };
    return IsEmptySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=isEmpty.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/empty.js
var empty = __webpack_require__(133);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/takeLast.js
/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */




function takeLast(count) {
    return function takeLastOperatorFunction(source) {
        if (count === 0) {
            return Object(empty["b" /* empty */])();
        }
        else {
            return source.lift(new takeLast_TakeLastOperator(count));
        }
    };
}
var takeLast_TakeLastOperator = /*@__PURE__*/ (function () {
    function TakeLastOperator(total) {
        this.total = total;
        if (this.total < 0) {
            throw new ArgumentOutOfRangeError["a" /* ArgumentOutOfRangeError */];
        }
    }
    TakeLastOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new takeLast_TakeLastSubscriber(subscriber, this.total));
    };
    return TakeLastOperator;
}());
var takeLast_TakeLastSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](TakeLastSubscriber, _super);
    function TakeLastSubscriber(destination, total) {
        var _this = _super.call(this, destination) || this;
        _this.total = total;
        _this.ring = new Array();
        _this.count = 0;
        return _this;
    }
    TakeLastSubscriber.prototype._next = function (value) {
        var ring = this.ring;
        var total = this.total;
        var count = this.count++;
        if (ring.length < total) {
            ring.push(value);
        }
        else {
            var index = count % total;
            ring[index] = value;
        }
    };
    TakeLastSubscriber.prototype._complete = function () {
        var destination = this.destination;
        var count = this.count;
        if (count > 0) {
            var total = this.count >= this.total ? this.total : this.count;
            var ring = this.ring;
            for (var i = 0; i < total; i++) {
                var idx = (count++) % total;
                destination.next(ring[idx]);
            }
        }
        destination.complete();
    };
    return TakeLastSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=takeLast.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/last.js
/** PURE_IMPORTS_START _util_EmptyError,_filter,_takeLast,_throwIfEmpty,_defaultIfEmpty,_util_identity PURE_IMPORTS_END */






function last(predicate, defaultValue) {
    var hasDefaultValue = arguments.length >= 2;
    return function (source) { return source.pipe(predicate ? Object(filter["a" /* filter */])(function (v, i) { return predicate(v, i, source); }) : identity["a" /* identity */], takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError["a" /* EmptyError */](); })); };
}
//# sourceMappingURL=last.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/mapTo.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function mapTo(value) {
    return function (source) { return source.lift(new MapToOperator(value)); };
}
var MapToOperator = /*@__PURE__*/ (function () {
    function MapToOperator(value) {
        this.value = value;
    }
    MapToOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new mapTo_MapToSubscriber(subscriber, this.value));
    };
    return MapToOperator;
}());
var mapTo_MapToSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](MapToSubscriber, _super);
    function MapToSubscriber(destination, value) {
        var _this = _super.call(this, destination) || this;
        _this.value = value;
        return _this;
    }
    MapToSubscriber.prototype._next = function (x) {
        this.destination.next(this.value);
    };
    return MapToSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=mapTo.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/materialize.js
/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */



function materialize() {
    return function materializeOperatorFunction(source) {
        return source.lift(new MaterializeOperator());
    };
}
var MaterializeOperator = /*@__PURE__*/ (function () {
    function MaterializeOperator() {
    }
    MaterializeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new materialize_MaterializeSubscriber(subscriber));
    };
    return MaterializeOperator;
}());
var materialize_MaterializeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](MaterializeSubscriber, _super);
    function MaterializeSubscriber(destination) {
        return _super.call(this, destination) || this;
    }
    MaterializeSubscriber.prototype._next = function (value) {
        this.destination.next(Notification["a" /* Notification */].createNext(value));
    };
    MaterializeSubscriber.prototype._error = function (err) {
        var destination = this.destination;
        destination.next(Notification["a" /* Notification */].createError(err));
        destination.complete();
    };
    MaterializeSubscriber.prototype._complete = function () {
        var destination = this.destination;
        destination.next(Notification["a" /* Notification */].createComplete());
        destination.complete();
    };
    return MaterializeSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=materialize.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/scan.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function scan(accumulator, seed) {
    var hasSeed = false;
    if (arguments.length >= 2) {
        hasSeed = true;
    }
    return function scanOperatorFunction(source) {
        return source.lift(new ScanOperator(accumulator, seed, hasSeed));
    };
}
var ScanOperator = /*@__PURE__*/ (function () {
    function ScanOperator(accumulator, seed, hasSeed) {
        if (hasSeed === void 0) {
            hasSeed = false;
        }
        this.accumulator = accumulator;
        this.seed = seed;
        this.hasSeed = hasSeed;
    }
    ScanOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new scan_ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed));
    };
    return ScanOperator;
}());
var scan_ScanSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ScanSubscriber, _super);
    function ScanSubscriber(destination, accumulator, _seed, hasSeed) {
        var _this = _super.call(this, destination) || this;
        _this.accumulator = accumulator;
        _this._seed = _seed;
        _this.hasSeed = hasSeed;
        _this.index = 0;
        return _this;
    }
    Object.defineProperty(ScanSubscriber.prototype, "seed", {
        get: function () {
            return this._seed;
        },
        set: function (value) {
            this.hasSeed = true;
            this._seed = value;
        },
        enumerable: true,
        configurable: true
    });
    ScanSubscriber.prototype._next = function (value) {
        if (!this.hasSeed) {
            this.seed = value;
            this.destination.next(value);
        }
        else {
            return this._tryNext(value);
        }
    };
    ScanSubscriber.prototype._tryNext = function (value) {
        var index = this.index++;
        var result;
        try {
            result = this.accumulator(this.seed, value, index);
        }
        catch (err) {
            this.destination.error(err);
        }
        this.seed = result;
        this.destination.next(result);
    };
    return ScanSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=scan.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/pipe.js
var pipe = __webpack_require__(273);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/reduce.js
/** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */




function reduce(accumulator, seed) {
    if (arguments.length >= 2) {
        return function reduceOperatorFunctionWithSeed(source) {
            return Object(pipe["a" /* pipe */])(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source);
        };
    }
    return function reduceOperatorFunction(source) {
        return Object(pipe["a" /* pipe */])(scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast(1))(source);
    };
}
//# sourceMappingURL=reduce.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/max.js
/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */

function max_max(comparer) {
    var max = (typeof comparer === 'function')
        ? function (x, y) { return comparer(x, y) > 0 ? x : y; }
        : function (x, y) { return x > y ? x : y; };
    return reduce(max);
}
//# sourceMappingURL=max.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/merge.js
var merge = __webpack_require__(235);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/merge.js
/** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */

function merge_merge() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    return function (source) { return source.lift.call(merge["a" /* merge */].apply(void 0, [source].concat(observables))); };
}
//# sourceMappingURL=merge.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/mergeAll.js
var mergeAll = __webpack_require__(292);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/mergeMapTo.js
/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */

function mergeMapTo(innerObservable, resultSelector, concurrent) {
    if (concurrent === void 0) {
        concurrent = Number.POSITIVE_INFINITY;
    }
    if (typeof resultSelector === 'function') {
        return Object(mergeMap["a" /* mergeMap */])(function () { return innerObservable; }, resultSelector, concurrent);
    }
    if (typeof resultSelector === 'number') {
        concurrent = resultSelector;
    }
    return Object(mergeMap["a" /* mergeMap */])(function () { return innerObservable; }, concurrent);
}
//# sourceMappingURL=mergeMapTo.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/mergeScan.js
/** PURE_IMPORTS_START tslib,_util_subscribeToResult,_OuterSubscriber,_InnerSubscriber PURE_IMPORTS_END */




function mergeScan(accumulator, seed, concurrent) {
    if (concurrent === void 0) {
        concurrent = Number.POSITIVE_INFINITY;
    }
    return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); };
}
var MergeScanOperator = /*@__PURE__*/ (function () {
    function MergeScanOperator(accumulator, seed, concurrent) {
        this.accumulator = accumulator;
        this.seed = seed;
        this.concurrent = concurrent;
    }
    MergeScanOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new mergeScan_MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent));
    };
    return MergeScanOperator;
}());

var mergeScan_MergeScanSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](MergeScanSubscriber, _super);
    function MergeScanSubscriber(destination, accumulator, acc, concurrent) {
        var _this = _super.call(this, destination) || this;
        _this.accumulator = accumulator;
        _this.acc = acc;
        _this.concurrent = concurrent;
        _this.hasValue = false;
        _this.hasCompleted = false;
        _this.buffer = [];
        _this.active = 0;
        _this.index = 0;
        return _this;
    }
    MergeScanSubscriber.prototype._next = function (value) {
        if (this.active < this.concurrent) {
            var index = this.index++;
            var destination = this.destination;
            var ish = void 0;
            try {
                var accumulator = this.accumulator;
                ish = accumulator(this.acc, value, index);
            }
            catch (e) {
                return destination.error(e);
            }
            this.active++;
            this._innerSub(ish, value, index);
        }
        else {
            this.buffer.push(value);
        }
    };
    MergeScanSubscriber.prototype._innerSub = function (ish, value, index) {
        var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](this, value, index);
        var destination = this.destination;
        destination.add(innerSubscriber);
        var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, ish, undefined, undefined, innerSubscriber);
        if (innerSubscription !== innerSubscriber) {
            destination.add(innerSubscription);
        }
    };
    MergeScanSubscriber.prototype._complete = function () {
        this.hasCompleted = true;
        if (this.active === 0 && this.buffer.length === 0) {
            if (this.hasValue === false) {
                this.destination.next(this.acc);
            }
            this.destination.complete();
        }
        this.unsubscribe();
    };
    MergeScanSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        var destination = this.destination;
        this.acc = innerValue;
        this.hasValue = true;
        destination.next(innerValue);
    };
    MergeScanSubscriber.prototype.notifyComplete = function (innerSub) {
        var buffer = this.buffer;
        var destination = this.destination;
        destination.remove(innerSub);
        this.active--;
        if (buffer.length > 0) {
            this._next(buffer.shift());
        }
        else if (this.active === 0 && this.hasCompleted) {
            if (this.hasValue === false) {
                this.destination.next(this.acc);
            }
            this.destination.complete();
        }
    };
    return MergeScanSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));

//# sourceMappingURL=mergeScan.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/min.js
/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */

function min_min(comparer) {
    var min = (typeof comparer === 'function')
        ? function (x, y) { return comparer(x, y) < 0 ? x : y; }
        : function (x, y) { return x < y ? x : y; };
    return reduce(min);
}
//# sourceMappingURL=min.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/ConnectableObservable.js
var ConnectableObservable = __webpack_require__(346);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/multicast.js
/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */

function multicast(subjectOrSubjectFactory, selector) {
    return function multicastOperatorFunction(source) {
        var subjectFactory;
        if (typeof subjectOrSubjectFactory === 'function') {
            subjectFactory = subjectOrSubjectFactory;
        }
        else {
            subjectFactory = function subjectFactory() {
                return subjectOrSubjectFactory;
            };
        }
        if (typeof selector === 'function') {
            return source.lift(new MulticastOperator(subjectFactory, selector));
        }
        var connectable = Object.create(source, ConnectableObservable["b" /* connectableObservableDescriptor */]);
        connectable.source = source;
        connectable.subjectFactory = subjectFactory;
        return connectable;
    };
}
var MulticastOperator = /*@__PURE__*/ (function () {
    function MulticastOperator(subjectFactory, selector) {
        this.subjectFactory = subjectFactory;
        this.selector = selector;
    }
    MulticastOperator.prototype.call = function (subscriber, source) {
        var selector = this.selector;
        var subject = this.subjectFactory();
        var subscription = selector(subject).subscribe(subscriber);
        subscription.add(source.subscribe(subject));
        return subscription;
    };
    return MulticastOperator;
}());

//# sourceMappingURL=multicast.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/observeOn.js
var observeOn = __webpack_require__(347);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/onErrorResumeNext.js
/** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */






function onErrorResumeNext() {
    var nextSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        nextSources[_i] = arguments[_i];
    }
    if (nextSources.length === 1 && Object(isArray["a" /* isArray */])(nextSources[0])) {
        nextSources = nextSources[0];
    }
    return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); };
}
function onErrorResumeNextStatic() {
    var nextSources = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        nextSources[_i] = arguments[_i];
    }
    var source = null;
    if (nextSources.length === 1 && Object(isArray["a" /* isArray */])(nextSources[0])) {
        nextSources = nextSources[0];
    }
    source = nextSources.shift();
    return Object(from["a" /* from */])(source, null).lift(new OnErrorResumeNextOperator(nextSources));
}
var OnErrorResumeNextOperator = /*@__PURE__*/ (function () {
    function OnErrorResumeNextOperator(nextSources) {
        this.nextSources = nextSources;
    }
    OnErrorResumeNextOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new onErrorResumeNext_OnErrorResumeNextSubscriber(subscriber, this.nextSources));
    };
    return OnErrorResumeNextOperator;
}());
var onErrorResumeNext_OnErrorResumeNextSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](OnErrorResumeNextSubscriber, _super);
    function OnErrorResumeNextSubscriber(destination, nextSources) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        _this.nextSources = nextSources;
        return _this;
    }
    OnErrorResumeNextSubscriber.prototype.notifyError = function (error, innerSub) {
        this.subscribeToNextSource();
    };
    OnErrorResumeNextSubscriber.prototype.notifyComplete = function (innerSub) {
        this.subscribeToNextSource();
    };
    OnErrorResumeNextSubscriber.prototype._error = function (err) {
        this.subscribeToNextSource();
        this.unsubscribe();
    };
    OnErrorResumeNextSubscriber.prototype._complete = function () {
        this.subscribeToNextSource();
        this.unsubscribe();
    };
    OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () {
        var next = this.nextSources.shift();
        if (!!next) {
            var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](this, undefined, undefined);
            var destination = this.destination;
            destination.add(innerSubscriber);
            var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, next, undefined, undefined, innerSubscriber);
            if (innerSubscription !== innerSubscriber) {
                destination.add(innerSubscription);
            }
        }
        else {
            this.destination.complete();
        }
    };
    return OnErrorResumeNextSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=onErrorResumeNext.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/pairwise.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function pairwise() {
    return function (source) { return source.lift(new PairwiseOperator()); };
}
var PairwiseOperator = /*@__PURE__*/ (function () {
    function PairwiseOperator() {
    }
    PairwiseOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new pairwise_PairwiseSubscriber(subscriber));
    };
    return PairwiseOperator;
}());
var pairwise_PairwiseSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](PairwiseSubscriber, _super);
    function PairwiseSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.hasPrev = false;
        return _this;
    }
    PairwiseSubscriber.prototype._next = function (value) {
        var pair;
        if (this.hasPrev) {
            pair = [this.prev, value];
        }
        else {
            this.hasPrev = true;
        }
        this.prev = value;
        if (pair) {
            this.destination.next(pair);
        }
    };
    return PairwiseSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=pairwise.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/not.js
var not = __webpack_require__(378);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/partition.js
/** PURE_IMPORTS_START _util_not,_filter PURE_IMPORTS_END */


function partition(predicate, thisArg) {
    return function (source) {
        return [
            Object(filter["a" /* filter */])(predicate, thisArg)(source),
            Object(filter["a" /* filter */])(Object(not["a" /* not */])(predicate, thisArg))(source)
        ];
    };
}
//# sourceMappingURL=partition.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/pluck.js
/** PURE_IMPORTS_START _map PURE_IMPORTS_END */

function pluck() {
    var properties = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        properties[_i] = arguments[_i];
    }
    var length = properties.length;
    if (length === 0) {
        throw new Error('list of properties cannot be empty.');
    }
    return function (source) { return Object(map["a" /* map */])(plucker(properties, length))(source); };
}
function plucker(props, length) {
    var mapper = function (x) {
        var currentProp = x;
        for (var i = 0; i < length; i++) {
            var p = currentProp[props[i]];
            if (typeof p !== 'undefined') {
                currentProp = p;
            }
            else {
                return undefined;
            }
        }
        return currentProp;
    };
    return mapper;
}
//# sourceMappingURL=pluck.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/publish.js
/** PURE_IMPORTS_START _Subject,_multicast PURE_IMPORTS_END */


function publish(selector) {
    return selector ?
        multicast(function () { return new Subject["a" /* Subject */](); }, selector) :
        multicast(new Subject["a" /* Subject */]());
}
//# sourceMappingURL=publish.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/BehaviorSubject.js
var BehaviorSubject = __webpack_require__(279);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/publishBehavior.js
/** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */


function publishBehavior(value) {
    return function (source) { return multicast(new BehaviorSubject["a" /* BehaviorSubject */](value))(source); };
}
//# sourceMappingURL=publishBehavior.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/AsyncSubject.js
var AsyncSubject = __webpack_require__(226);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/publishLast.js
/** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */


function publishLast() {
    return function (source) { return multicast(new AsyncSubject["a" /* AsyncSubject */]())(source); };
}
//# sourceMappingURL=publishLast.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/ReplaySubject.js
var ReplaySubject = __webpack_require__(297);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/publishReplay.js
/** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */


function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) {
    if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') {
        scheduler = selectorOrScheduler;
    }
    var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined;
    var subject = new ReplaySubject["a" /* ReplaySubject */](bufferSize, windowTime, scheduler);
    return function (source) { return multicast(function () { return subject; }, selector)(source); };
}
//# sourceMappingURL=publishReplay.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/race.js
var race = __webpack_require__(348);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/race.js
/** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */


function race_race() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    return function raceOperatorFunction(source) {
        if (observables.length === 1 && Object(isArray["a" /* isArray */])(observables[0])) {
            observables = observables[0];
        }
        return source.lift.call(race["a" /* race */].apply(void 0, [source].concat(observables)));
    };
}
//# sourceMappingURL=race.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/repeat.js
/** PURE_IMPORTS_START tslib,_Subscriber,_observable_empty PURE_IMPORTS_END */



function repeat(count) {
    if (count === void 0) {
        count = -1;
    }
    return function (source) {
        if (count === 0) {
            return Object(empty["b" /* empty */])();
        }
        else if (count < 0) {
            return source.lift(new RepeatOperator(-1, source));
        }
        else {
            return source.lift(new RepeatOperator(count - 1, source));
        }
    };
}
var RepeatOperator = /*@__PURE__*/ (function () {
    function RepeatOperator(count, source) {
        this.count = count;
        this.source = source;
    }
    RepeatOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new repeat_RepeatSubscriber(subscriber, this.count, this.source));
    };
    return RepeatOperator;
}());
var repeat_RepeatSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](RepeatSubscriber, _super);
    function RepeatSubscriber(destination, count, source) {
        var _this = _super.call(this, destination) || this;
        _this.count = count;
        _this.source = source;
        return _this;
    }
    RepeatSubscriber.prototype.complete = function () {
        if (!this.isStopped) {
            var _a = this, source = _a.source, count = _a.count;
            if (count === 0) {
                return _super.prototype.complete.call(this);
            }
            else if (count > -1) {
                this.count = count - 1;
            }
            source.subscribe(this._unsubscribeAndRecycle());
        }
    };
    return RepeatSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=repeat.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/repeatWhen.js
/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function repeatWhen(notifier) {
    return function (source) { return source.lift(new RepeatWhenOperator(notifier)); };
}
var RepeatWhenOperator = /*@__PURE__*/ (function () {
    function RepeatWhenOperator(notifier) {
        this.notifier = notifier;
    }
    RepeatWhenOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new repeatWhen_RepeatWhenSubscriber(subscriber, this.notifier, source));
    };
    return RepeatWhenOperator;
}());
var repeatWhen_RepeatWhenSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](RepeatWhenSubscriber, _super);
    function RepeatWhenSubscriber(destination, notifier, source) {
        var _this = _super.call(this, destination) || this;
        _this.notifier = notifier;
        _this.source = source;
        _this.sourceIsBeingSubscribedTo = true;
        return _this;
    }
    RepeatWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.sourceIsBeingSubscribedTo = true;
        this.source.subscribe(this);
    };
    RepeatWhenSubscriber.prototype.notifyComplete = function (innerSub) {
        if (this.sourceIsBeingSubscribedTo === false) {
            return _super.prototype.complete.call(this);
        }
    };
    RepeatWhenSubscriber.prototype.complete = function () {
        this.sourceIsBeingSubscribedTo = false;
        if (!this.isStopped) {
            if (!this.retries) {
                this.subscribeToRetries();
            }
            if (!this.retriesSubscription || this.retriesSubscription.closed) {
                return _super.prototype.complete.call(this);
            }
            this._unsubscribeAndRecycle();
            this.notifications.next();
        }
    };
    RepeatWhenSubscriber.prototype._unsubscribe = function () {
        var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription;
        if (notifications) {
            notifications.unsubscribe();
            this.notifications = null;
        }
        if (retriesSubscription) {
            retriesSubscription.unsubscribe();
            this.retriesSubscription = null;
        }
        this.retries = null;
    };
    RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () {
        var _unsubscribe = this._unsubscribe;
        this._unsubscribe = null;
        _super.prototype._unsubscribeAndRecycle.call(this);
        this._unsubscribe = _unsubscribe;
        return this;
    };
    RepeatWhenSubscriber.prototype.subscribeToRetries = function () {
        this.notifications = new Subject["a" /* Subject */]();
        var retries;
        try {
            var notifier = this.notifier;
            retries = notifier(this.notifications);
        }
        catch (e) {
            return _super.prototype.complete.call(this);
        }
        this.retries = retries;
        this.retriesSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, retries);
    };
    return RepeatWhenSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=repeatWhen.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/retry.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function retry(count) {
    if (count === void 0) {
        count = -1;
    }
    return function (source) { return source.lift(new RetryOperator(count, source)); };
}
var RetryOperator = /*@__PURE__*/ (function () {
    function RetryOperator(count, source) {
        this.count = count;
        this.source = source;
    }
    RetryOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new retry_RetrySubscriber(subscriber, this.count, this.source));
    };
    return RetryOperator;
}());
var retry_RetrySubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](RetrySubscriber, _super);
    function RetrySubscriber(destination, count, source) {
        var _this = _super.call(this, destination) || this;
        _this.count = count;
        _this.source = source;
        return _this;
    }
    RetrySubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var _a = this, source = _a.source, count = _a.count;
            if (count === 0) {
                return _super.prototype.error.call(this, err);
            }
            else if (count > -1) {
                this.count = count - 1;
            }
            source.subscribe(this._unsubscribeAndRecycle());
        }
    };
    return RetrySubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=retry.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/retryWhen.js
/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function retryWhen(notifier) {
    return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); };
}
var RetryWhenOperator = /*@__PURE__*/ (function () {
    function RetryWhenOperator(notifier, source) {
        this.notifier = notifier;
        this.source = source;
    }
    RetryWhenOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new retryWhen_RetryWhenSubscriber(subscriber, this.notifier, this.source));
    };
    return RetryWhenOperator;
}());
var retryWhen_RetryWhenSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](RetryWhenSubscriber, _super);
    function RetryWhenSubscriber(destination, notifier, source) {
        var _this = _super.call(this, destination) || this;
        _this.notifier = notifier;
        _this.source = source;
        return _this;
    }
    RetryWhenSubscriber.prototype.error = function (err) {
        if (!this.isStopped) {
            var errors = this.errors;
            var retries = this.retries;
            var retriesSubscription = this.retriesSubscription;
            if (!retries) {
                errors = new Subject["a" /* Subject */]();
                try {
                    var notifier = this.notifier;
                    retries = notifier(errors);
                }
                catch (e) {
                    return _super.prototype.error.call(this, e);
                }
                retriesSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, retries);
            }
            else {
                this.errors = null;
                this.retriesSubscription = null;
            }
            this._unsubscribeAndRecycle();
            this.errors = errors;
            this.retries = retries;
            this.retriesSubscription = retriesSubscription;
            errors.next(err);
        }
    };
    RetryWhenSubscriber.prototype._unsubscribe = function () {
        var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription;
        if (errors) {
            errors.unsubscribe();
            this.errors = null;
        }
        if (retriesSubscription) {
            retriesSubscription.unsubscribe();
            this.retriesSubscription = null;
        }
        this.retries = null;
    };
    RetryWhenSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        var _unsubscribe = this._unsubscribe;
        this._unsubscribe = null;
        this._unsubscribeAndRecycle();
        this._unsubscribe = _unsubscribe;
        this.source.subscribe(this);
    };
    return RetryWhenSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=retryWhen.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/refCount.js
var operators_refCount = __webpack_require__(296);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/sample.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function sample(notifier) {
    return function (source) { return source.lift(new sample_SampleOperator(notifier)); };
}
var sample_SampleOperator = /*@__PURE__*/ (function () {
    function SampleOperator(notifier) {
        this.notifier = notifier;
    }
    SampleOperator.prototype.call = function (subscriber, source) {
        var sampleSubscriber = new sample_SampleSubscriber(subscriber);
        var subscription = source.subscribe(sampleSubscriber);
        subscription.add(Object(subscribeToResult["a" /* subscribeToResult */])(sampleSubscriber, this.notifier));
        return subscription;
    };
    return SampleOperator;
}());
var sample_SampleSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SampleSubscriber, _super);
    function SampleSubscriber() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.hasValue = false;
        return _this;
    }
    SampleSubscriber.prototype._next = function (value) {
        this.value = value;
        this.hasValue = true;
    };
    SampleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.emitValue();
    };
    SampleSubscriber.prototype.notifyComplete = function () {
        this.emitValue();
    };
    SampleSubscriber.prototype.emitValue = function () {
        if (this.hasValue) {
            this.hasValue = false;
            this.destination.next(this.value);
        }
    };
    return SampleSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=sample.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/sampleTime.js
/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */



function sampleTime(period, scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); };
}
var SampleTimeOperator = /*@__PURE__*/ (function () {
    function SampleTimeOperator(period, scheduler) {
        this.period = period;
        this.scheduler = scheduler;
    }
    SampleTimeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new sampleTime_SampleTimeSubscriber(subscriber, this.period, this.scheduler));
    };
    return SampleTimeOperator;
}());
var sampleTime_SampleTimeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SampleTimeSubscriber, _super);
    function SampleTimeSubscriber(destination, period, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.period = period;
        _this.scheduler = scheduler;
        _this.hasValue = false;
        _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period }));
        return _this;
    }
    SampleTimeSubscriber.prototype._next = function (value) {
        this.lastValue = value;
        this.hasValue = true;
    };
    SampleTimeSubscriber.prototype.notifyNext = function () {
        if (this.hasValue) {
            this.hasValue = false;
            this.destination.next(this.lastValue);
        }
    };
    return SampleTimeSubscriber;
}(Subscriber["a" /* Subscriber */]));
function dispatchNotification(state) {
    var subscriber = state.subscriber, period = state.period;
    subscriber.notifyNext();
    this.schedule(state, period);
}
//# sourceMappingURL=sampleTime.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/sequenceEqual.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function sequenceEqual(compareTo, comparator) {
    return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); };
}
var SequenceEqualOperator = /*@__PURE__*/ (function () {
    function SequenceEqualOperator(compareTo, comparator) {
        this.compareTo = compareTo;
        this.comparator = comparator;
    }
    SequenceEqualOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new sequenceEqual_SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator));
    };
    return SequenceEqualOperator;
}());

var sequenceEqual_SequenceEqualSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SequenceEqualSubscriber, _super);
    function SequenceEqualSubscriber(destination, compareTo, comparator) {
        var _this = _super.call(this, destination) || this;
        _this.compareTo = compareTo;
        _this.comparator = comparator;
        _this._a = [];
        _this._b = [];
        _this._oneComplete = false;
        _this.destination.add(compareTo.subscribe(new sequenceEqual_SequenceEqualCompareToSubscriber(destination, _this)));
        return _this;
    }
    SequenceEqualSubscriber.prototype._next = function (value) {
        if (this._oneComplete && this._b.length === 0) {
            this.emit(false);
        }
        else {
            this._a.push(value);
            this.checkValues();
        }
    };
    SequenceEqualSubscriber.prototype._complete = function () {
        if (this._oneComplete) {
            this.emit(this._a.length === 0 && this._b.length === 0);
        }
        else {
            this._oneComplete = true;
        }
        this.unsubscribe();
    };
    SequenceEqualSubscriber.prototype.checkValues = function () {
        var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator;
        while (_a.length > 0 && _b.length > 0) {
            var a = _a.shift();
            var b = _b.shift();
            var areEqual = false;
            try {
                areEqual = comparator ? comparator(a, b) : a === b;
            }
            catch (e) {
                this.destination.error(e);
            }
            if (!areEqual) {
                this.emit(false);
            }
        }
    };
    SequenceEqualSubscriber.prototype.emit = function (value) {
        var destination = this.destination;
        destination.next(value);
        destination.complete();
    };
    SequenceEqualSubscriber.prototype.nextB = function (value) {
        if (this._oneComplete && this._a.length === 0) {
            this.emit(false);
        }
        else {
            this._b.push(value);
            this.checkValues();
        }
    };
    SequenceEqualSubscriber.prototype.completeB = function () {
        if (this._oneComplete) {
            this.emit(this._a.length === 0 && this._b.length === 0);
        }
        else {
            this._oneComplete = true;
        }
    };
    return SequenceEqualSubscriber;
}(Subscriber["a" /* Subscriber */]));

var sequenceEqual_SequenceEqualCompareToSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SequenceEqualCompareToSubscriber, _super);
    function SequenceEqualCompareToSubscriber(destination, parent) {
        var _this = _super.call(this, destination) || this;
        _this.parent = parent;
        return _this;
    }
    SequenceEqualCompareToSubscriber.prototype._next = function (value) {
        this.parent.nextB(value);
    };
    SequenceEqualCompareToSubscriber.prototype._error = function (err) {
        this.parent.error(err);
        this.unsubscribe();
    };
    SequenceEqualCompareToSubscriber.prototype._complete = function () {
        this.parent.completeB();
        this.unsubscribe();
    };
    return SequenceEqualCompareToSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=sequenceEqual.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/share.js
/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */



function shareSubjectFactory() {
    return new Subject["a" /* Subject */]();
}
function share() {
    return function (source) { return Object(operators_refCount["a" /* refCount */])()(multicast(shareSubjectFactory)(source)); };
}
//# sourceMappingURL=share.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/shareReplay.js
/** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */

function shareReplay(configOrBufferSize, windowTime, scheduler) {
    var config;
    if (configOrBufferSize && typeof configOrBufferSize === 'object') {
        config = configOrBufferSize;
    }
    else {
        config = {
            bufferSize: configOrBufferSize,
            windowTime: windowTime,
            refCount: false,
            scheduler: scheduler
        };
    }
    return function (source) { return source.lift(shareReplayOperator(config)); };
}
function shareReplayOperator(_a) {
    var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler;
    var subject;
    var refCount = 0;
    var subscription;
    var hasError = false;
    var isComplete = false;
    return function shareReplayOperation(source) {
        refCount++;
        if (!subject || hasError) {
            hasError = false;
            subject = new ReplaySubject["a" /* ReplaySubject */](bufferSize, windowTime, scheduler);
            subscription = source.subscribe({
                next: function (value) { subject.next(value); },
                error: function (err) {
                    hasError = true;
                    subject.error(err);
                },
                complete: function () {
                    isComplete = true;
                    subscription = undefined;
                    subject.complete();
                },
            });
        }
        var innerSub = subject.subscribe(this);
        this.add(function () {
            refCount--;
            innerSub.unsubscribe();
            if (subscription && !isComplete && useRefCount && refCount === 0) {
                subscription.unsubscribe();
                subscription = undefined;
                subject = undefined;
            }
        });
    };
}
//# sourceMappingURL=shareReplay.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/single.js
/** PURE_IMPORTS_START tslib,_Subscriber,_util_EmptyError PURE_IMPORTS_END */



function single(predicate) {
    return function (source) { return source.lift(new SingleOperator(predicate, source)); };
}
var SingleOperator = /*@__PURE__*/ (function () {
    function SingleOperator(predicate, source) {
        this.predicate = predicate;
        this.source = source;
    }
    SingleOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new single_SingleSubscriber(subscriber, this.predicate, this.source));
    };
    return SingleOperator;
}());
var single_SingleSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SingleSubscriber, _super);
    function SingleSubscriber(destination, predicate, source) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.source = source;
        _this.seenValue = false;
        _this.index = 0;
        return _this;
    }
    SingleSubscriber.prototype.applySingleValue = function (value) {
        if (this.seenValue) {
            this.destination.error('Sequence contains more than one element');
        }
        else {
            this.seenValue = true;
            this.singleValue = value;
        }
    };
    SingleSubscriber.prototype._next = function (value) {
        var index = this.index++;
        if (this.predicate) {
            this.tryNext(value, index);
        }
        else {
            this.applySingleValue(value);
        }
    };
    SingleSubscriber.prototype.tryNext = function (value, index) {
        try {
            if (this.predicate(value, index, this.source)) {
                this.applySingleValue(value);
            }
        }
        catch (err) {
            this.destination.error(err);
        }
    };
    SingleSubscriber.prototype._complete = function () {
        var destination = this.destination;
        if (this.index > 0) {
            destination.next(this.seenValue ? this.singleValue : undefined);
            destination.complete();
        }
        else {
            destination.error(new EmptyError["a" /* EmptyError */]);
        }
    };
    return SingleSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=single.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/skip.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function skip(count) {
    return function (source) { return source.lift(new SkipOperator(count)); };
}
var SkipOperator = /*@__PURE__*/ (function () {
    function SkipOperator(total) {
        this.total = total;
    }
    SkipOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new skip_SkipSubscriber(subscriber, this.total));
    };
    return SkipOperator;
}());
var skip_SkipSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SkipSubscriber, _super);
    function SkipSubscriber(destination, total) {
        var _this = _super.call(this, destination) || this;
        _this.total = total;
        _this.count = 0;
        return _this;
    }
    SkipSubscriber.prototype._next = function (x) {
        if (++this.count > this.total) {
            this.destination.next(x);
        }
    };
    return SkipSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=skip.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/skipLast.js
/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError PURE_IMPORTS_END */



function skipLast(count) {
    return function (source) { return source.lift(new skipLast_SkipLastOperator(count)); };
}
var skipLast_SkipLastOperator = /*@__PURE__*/ (function () {
    function SkipLastOperator(_skipCount) {
        this._skipCount = _skipCount;
        if (this._skipCount < 0) {
            throw new ArgumentOutOfRangeError["a" /* ArgumentOutOfRangeError */];
        }
    }
    SkipLastOperator.prototype.call = function (subscriber, source) {
        if (this._skipCount === 0) {
            return source.subscribe(new Subscriber["a" /* Subscriber */](subscriber));
        }
        else {
            return source.subscribe(new skipLast_SkipLastSubscriber(subscriber, this._skipCount));
        }
    };
    return SkipLastOperator;
}());
var skipLast_SkipLastSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SkipLastSubscriber, _super);
    function SkipLastSubscriber(destination, _skipCount) {
        var _this = _super.call(this, destination) || this;
        _this._skipCount = _skipCount;
        _this._count = 0;
        _this._ring = new Array(_skipCount);
        return _this;
    }
    SkipLastSubscriber.prototype._next = function (value) {
        var skipCount = this._skipCount;
        var count = this._count++;
        if (count < skipCount) {
            this._ring[count] = value;
        }
        else {
            var currentIndex = count % skipCount;
            var ring = this._ring;
            var oldValue = ring[currentIndex];
            ring[currentIndex] = value;
            this.destination.next(oldValue);
        }
    };
    return SkipLastSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=skipLast.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/skipUntil.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function skipUntil(notifier) {
    return function (source) { return source.lift(new SkipUntilOperator(notifier)); };
}
var SkipUntilOperator = /*@__PURE__*/ (function () {
    function SkipUntilOperator(notifier) {
        this.notifier = notifier;
    }
    SkipUntilOperator.prototype.call = function (destination, source) {
        return source.subscribe(new skipUntil_SkipUntilSubscriber(destination, this.notifier));
    };
    return SkipUntilOperator;
}());
var skipUntil_SkipUntilSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SkipUntilSubscriber, _super);
    function SkipUntilSubscriber(destination, notifier) {
        var _this = _super.call(this, destination) || this;
        _this.hasValue = false;
        var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](_this, undefined, undefined);
        _this.add(innerSubscriber);
        _this.innerSubscription = innerSubscriber;
        var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(_this, notifier, undefined, undefined, innerSubscriber);
        if (innerSubscription !== innerSubscriber) {
            _this.add(innerSubscription);
            _this.innerSubscription = innerSubscription;
        }
        return _this;
    }
    SkipUntilSubscriber.prototype._next = function (value) {
        if (this.hasValue) {
            _super.prototype._next.call(this, value);
        }
    };
    SkipUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.hasValue = true;
        if (this.innerSubscription) {
            this.innerSubscription.unsubscribe();
        }
    };
    SkipUntilSubscriber.prototype.notifyComplete = function () {
    };
    return SkipUntilSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=skipUntil.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/skipWhile.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function skipWhile(predicate) {
    return function (source) { return source.lift(new SkipWhileOperator(predicate)); };
}
var SkipWhileOperator = /*@__PURE__*/ (function () {
    function SkipWhileOperator(predicate) {
        this.predicate = predicate;
    }
    SkipWhileOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new skipWhile_SkipWhileSubscriber(subscriber, this.predicate));
    };
    return SkipWhileOperator;
}());
var skipWhile_SkipWhileSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SkipWhileSubscriber, _super);
    function SkipWhileSubscriber(destination, predicate) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.skipping = true;
        _this.index = 0;
        return _this;
    }
    SkipWhileSubscriber.prototype._next = function (value) {
        var destination = this.destination;
        if (this.skipping) {
            this.tryCallPredicate(value);
        }
        if (!this.skipping) {
            destination.next(value);
        }
    };
    SkipWhileSubscriber.prototype.tryCallPredicate = function (value) {
        try {
            var result = this.predicate(value, this.index++);
            this.skipping = Boolean(result);
        }
        catch (err) {
            this.destination.error(err);
        }
    };
    return SkipWhileSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=skipWhile.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/startWith.js
/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */


function startWith() {
    var array = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        array[_i] = arguments[_i];
    }
    var scheduler = array[array.length - 1];
    if (Object(isScheduler["a" /* isScheduler */])(scheduler)) {
        array.pop();
        return function (source) { return Object(concat["a" /* concat */])(array, source, scheduler); };
    }
    else {
        return function (source) { return Object(concat["a" /* concat */])(array, source); };
    }
}
//# sourceMappingURL=startWith.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/asap.js + 3 modules
var asap = __webpack_require__(312);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isNumeric.js
var isNumeric = __webpack_require__(231);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/observable/SubscribeOnObservable.js
/** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */




var SubscribeOnObservable_SubscribeOnObservable = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SubscribeOnObservable, _super);
    function SubscribeOnObservable(source, delayTime, scheduler) {
        if (delayTime === void 0) {
            delayTime = 0;
        }
        if (scheduler === void 0) {
            scheduler = asap["a" /* asap */];
        }
        var _this = _super.call(this) || this;
        _this.source = source;
        _this.delayTime = delayTime;
        _this.scheduler = scheduler;
        if (!Object(isNumeric["a" /* isNumeric */])(delayTime) || delayTime < 0) {
            _this.delayTime = 0;
        }
        if (!scheduler || typeof scheduler.schedule !== 'function') {
            _this.scheduler = asap["a" /* asap */];
        }
        return _this;
    }
    SubscribeOnObservable.create = function (source, delay, scheduler) {
        if (delay === void 0) {
            delay = 0;
        }
        if (scheduler === void 0) {
            scheduler = asap["a" /* asap */];
        }
        return new SubscribeOnObservable(source, delay, scheduler);
    };
    SubscribeOnObservable.dispatch = function (arg) {
        var source = arg.source, subscriber = arg.subscriber;
        return this.add(source.subscribe(subscriber));
    };
    SubscribeOnObservable.prototype._subscribe = function (subscriber) {
        var delay = this.delayTime;
        var source = this.source;
        var scheduler = this.scheduler;
        return scheduler.schedule(SubscribeOnObservable.dispatch, delay, {
            source: source, subscriber: subscriber
        });
    };
    return SubscribeOnObservable;
}(Observable["a" /* Observable */]));

//# sourceMappingURL=SubscribeOnObservable.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/subscribeOn.js
/** PURE_IMPORTS_START _observable_SubscribeOnObservable PURE_IMPORTS_END */

function subscribeOn(scheduler, delay) {
    if (delay === void 0) {
        delay = 0;
    }
    return function subscribeOnOperatorFunction(source) {
        return source.lift(new subscribeOn_SubscribeOnOperator(scheduler, delay));
    };
}
var subscribeOn_SubscribeOnOperator = /*@__PURE__*/ (function () {
    function SubscribeOnOperator(scheduler, delay) {
        this.scheduler = scheduler;
        this.delay = delay;
    }
    SubscribeOnOperator.prototype.call = function (subscriber, source) {
        return new SubscribeOnObservable_SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber);
    };
    return SubscribeOnOperator;
}());
//# sourceMappingURL=subscribeOn.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/switchMap.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_InnerSubscriber,_util_subscribeToResult,_map,_observable_from PURE_IMPORTS_END */






function switchMap(project, resultSelector) {
    if (typeof resultSelector === 'function') {
        return function (source) { return source.pipe(switchMap(function (a, i) { return Object(from["a" /* from */])(project(a, i)).pipe(Object(map["a" /* map */])(function (b, ii) { return resultSelector(a, b, i, ii); })); })); };
    }
    return function (source) { return source.lift(new SwitchMapOperator(project)); };
}
var SwitchMapOperator = /*@__PURE__*/ (function () {
    function SwitchMapOperator(project) {
        this.project = project;
    }
    SwitchMapOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new switchMap_SwitchMapSubscriber(subscriber, this.project));
    };
    return SwitchMapOperator;
}());
var switchMap_SwitchMapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](SwitchMapSubscriber, _super);
    function SwitchMapSubscriber(destination, project) {
        var _this = _super.call(this, destination) || this;
        _this.project = project;
        _this.index = 0;
        return _this;
    }
    SwitchMapSubscriber.prototype._next = function (value) {
        var result;
        var index = this.index++;
        try {
            result = this.project(value, index);
        }
        catch (error) {
            this.destination.error(error);
            return;
        }
        this._innerSub(result, value, index);
    };
    SwitchMapSubscriber.prototype._innerSub = function (result, value, index) {
        var innerSubscription = this.innerSubscription;
        if (innerSubscription) {
            innerSubscription.unsubscribe();
        }
        var innerSubscriber = new InnerSubscriber["a" /* InnerSubscriber */](this, value, index);
        var destination = this.destination;
        destination.add(innerSubscriber);
        this.innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, result, undefined, undefined, innerSubscriber);
        if (this.innerSubscription !== innerSubscriber) {
            destination.add(this.innerSubscription);
        }
    };
    SwitchMapSubscriber.prototype._complete = function () {
        var innerSubscription = this.innerSubscription;
        if (!innerSubscription || innerSubscription.closed) {
            _super.prototype._complete.call(this);
        }
        this.unsubscribe();
    };
    SwitchMapSubscriber.prototype._unsubscribe = function () {
        this.innerSubscription = null;
    };
    SwitchMapSubscriber.prototype.notifyComplete = function (innerSub) {
        var destination = this.destination;
        destination.remove(innerSub);
        this.innerSubscription = null;
        if (this.isStopped) {
            _super.prototype._complete.call(this);
        }
    };
    SwitchMapSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.destination.next(innerValue);
    };
    return SwitchMapSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=switchMap.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/switchAll.js
/** PURE_IMPORTS_START _switchMap,_util_identity PURE_IMPORTS_END */


function switchAll() {
    return switchMap(identity["a" /* identity */]);
}
//# sourceMappingURL=switchAll.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/switchMapTo.js
/** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */

function switchMapTo(innerObservable, resultSelector) {
    return resultSelector ? switchMap(function () { return innerObservable; }, resultSelector) : switchMap(function () { return innerObservable; });
}
//# sourceMappingURL=switchMapTo.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/takeUntil.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function takeUntil(notifier) {
    return function (source) { return source.lift(new takeUntil_TakeUntilOperator(notifier)); };
}
var takeUntil_TakeUntilOperator = /*@__PURE__*/ (function () {
    function TakeUntilOperator(notifier) {
        this.notifier = notifier;
    }
    TakeUntilOperator.prototype.call = function (subscriber, source) {
        var takeUntilSubscriber = new takeUntil_TakeUntilSubscriber(subscriber);
        var notifierSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(takeUntilSubscriber, this.notifier);
        if (notifierSubscription && !takeUntilSubscriber.seenValue) {
            takeUntilSubscriber.add(notifierSubscription);
            return source.subscribe(takeUntilSubscriber);
        }
        return takeUntilSubscriber;
    };
    return TakeUntilOperator;
}());
var takeUntil_TakeUntilSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](TakeUntilSubscriber, _super);
    function TakeUntilSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.seenValue = false;
        return _this;
    }
    TakeUntilSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.seenValue = true;
        this.complete();
    };
    TakeUntilSubscriber.prototype.notifyComplete = function () {
    };
    return TakeUntilSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=takeUntil.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/takeWhile.js
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function takeWhile(predicate, inclusive) {
    if (inclusive === void 0) {
        inclusive = false;
    }
    return function (source) {
        return source.lift(new TakeWhileOperator(predicate, inclusive));
    };
}
var TakeWhileOperator = /*@__PURE__*/ (function () {
    function TakeWhileOperator(predicate, inclusive) {
        this.predicate = predicate;
        this.inclusive = inclusive;
    }
    TakeWhileOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new takeWhile_TakeWhileSubscriber(subscriber, this.predicate, this.inclusive));
    };
    return TakeWhileOperator;
}());
var takeWhile_TakeWhileSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](TakeWhileSubscriber, _super);
    function TakeWhileSubscriber(destination, predicate, inclusive) {
        var _this = _super.call(this, destination) || this;
        _this.predicate = predicate;
        _this.inclusive = inclusive;
        _this.index = 0;
        return _this;
    }
    TakeWhileSubscriber.prototype._next = function (value) {
        var destination = this.destination;
        var result;
        try {
            result = this.predicate(value, this.index++);
        }
        catch (err) {
            destination.error(err);
            return;
        }
        this.nextOrComplete(value, result);
    };
    TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) {
        var destination = this.destination;
        if (Boolean(predicateResult)) {
            destination.next(value);
        }
        else {
            if (this.inclusive) {
                destination.next(value);
            }
            destination.complete();
        }
    };
    return TakeWhileSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=takeWhile.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/noop.js
var noop = __webpack_require__(199);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isFunction.js
var isFunction = __webpack_require__(215);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/tap.js
/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */




function tap(nextOrObserver, error, complete) {
    return function tapOperatorFunction(source) {
        return source.lift(new DoOperator(nextOrObserver, error, complete));
    };
}
var DoOperator = /*@__PURE__*/ (function () {
    function DoOperator(nextOrObserver, error, complete) {
        this.nextOrObserver = nextOrObserver;
        this.error = error;
        this.complete = complete;
    }
    DoOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new tap_TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete));
    };
    return DoOperator;
}());
var tap_TapSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](TapSubscriber, _super);
    function TapSubscriber(destination, observerOrNext, error, complete) {
        var _this = _super.call(this, destination) || this;
        _this._tapNext = noop["a" /* noop */];
        _this._tapError = noop["a" /* noop */];
        _this._tapComplete = noop["a" /* noop */];
        _this._tapError = error || noop["a" /* noop */];
        _this._tapComplete = complete || noop["a" /* noop */];
        if (Object(isFunction["a" /* isFunction */])(observerOrNext)) {
            _this._context = _this;
            _this._tapNext = observerOrNext;
        }
        else if (observerOrNext) {
            _this._context = observerOrNext;
            _this._tapNext = observerOrNext.next || noop["a" /* noop */];
            _this._tapError = observerOrNext.error || noop["a" /* noop */];
            _this._tapComplete = observerOrNext.complete || noop["a" /* noop */];
        }
        return _this;
    }
    TapSubscriber.prototype._next = function (value) {
        try {
            this._tapNext.call(this._context, value);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(value);
    };
    TapSubscriber.prototype._error = function (err) {
        try {
            this._tapError.call(this._context, err);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.error(err);
    };
    TapSubscriber.prototype._complete = function () {
        try {
            this._tapComplete.call(this._context);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        return this.destination.complete();
    };
    return TapSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=tap.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/throttle.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



var defaultThrottleConfig = {
    leading: true,
    trailing: false
};
function throttle(durationSelector, config) {
    if (config === void 0) {
        config = defaultThrottleConfig;
    }
    return function (source) { return source.lift(new ThrottleOperator(durationSelector, config.leading, config.trailing)); };
}
var ThrottleOperator = /*@__PURE__*/ (function () {
    function ThrottleOperator(durationSelector, leading, trailing) {
        this.durationSelector = durationSelector;
        this.leading = leading;
        this.trailing = trailing;
    }
    ThrottleOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new throttle_ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing));
    };
    return ThrottleOperator;
}());
var throttle_ThrottleSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ThrottleSubscriber, _super);
    function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        _this.durationSelector = durationSelector;
        _this._leading = _leading;
        _this._trailing = _trailing;
        _this._hasValue = false;
        return _this;
    }
    ThrottleSubscriber.prototype._next = function (value) {
        this._hasValue = true;
        this._sendValue = value;
        if (!this._throttled) {
            if (this._leading) {
                this.send();
            }
            else {
                this.throttle(value);
            }
        }
    };
    ThrottleSubscriber.prototype.send = function () {
        var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue;
        if (_hasValue) {
            this.destination.next(_sendValue);
            this.throttle(_sendValue);
        }
        this._hasValue = false;
        this._sendValue = null;
    };
    ThrottleSubscriber.prototype.throttle = function (value) {
        var duration = this.tryDurationSelector(value);
        if (!!duration) {
            this.add(this._throttled = Object(subscribeToResult["a" /* subscribeToResult */])(this, duration));
        }
    };
    ThrottleSubscriber.prototype.tryDurationSelector = function (value) {
        try {
            return this.durationSelector(value);
        }
        catch (err) {
            this.destination.error(err);
            return null;
        }
    };
    ThrottleSubscriber.prototype.throttlingDone = function () {
        var _a = this, _throttled = _a._throttled, _trailing = _a._trailing;
        if (_throttled) {
            _throttled.unsubscribe();
        }
        this._throttled = null;
        if (_trailing) {
            this.send();
        }
    };
    ThrottleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.throttlingDone();
    };
    ThrottleSubscriber.prototype.notifyComplete = function () {
        this.throttlingDone();
    };
    return ThrottleSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=throttle.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/throttleTime.js
/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */




function throttleTime(duration, scheduler, config) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    if (config === void 0) {
        config = defaultThrottleConfig;
    }
    return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); };
}
var ThrottleTimeOperator = /*@__PURE__*/ (function () {
    function ThrottleTimeOperator(duration, scheduler, leading, trailing) {
        this.duration = duration;
        this.scheduler = scheduler;
        this.leading = leading;
        this.trailing = trailing;
    }
    ThrottleTimeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new throttleTime_ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing));
    };
    return ThrottleTimeOperator;
}());
var throttleTime_ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](ThrottleTimeSubscriber, _super);
    function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) {
        var _this = _super.call(this, destination) || this;
        _this.duration = duration;
        _this.scheduler = scheduler;
        _this.leading = leading;
        _this.trailing = trailing;
        _this._hasTrailingValue = false;
        _this._trailingValue = null;
        return _this;
    }
    ThrottleTimeSubscriber.prototype._next = function (value) {
        if (this.throttled) {
            if (this.trailing) {
                this._trailingValue = value;
                this._hasTrailingValue = true;
            }
        }
        else {
            this.add(this.throttled = this.scheduler.schedule(dispatchNext, this.duration, { subscriber: this }));
            if (this.leading) {
                this.destination.next(value);
            }
            else if (this.trailing) {
                this._trailingValue = value;
                this._hasTrailingValue = true;
            }
        }
    };
    ThrottleTimeSubscriber.prototype._complete = function () {
        if (this._hasTrailingValue) {
            this.destination.next(this._trailingValue);
            this.destination.complete();
        }
        else {
            this.destination.complete();
        }
    };
    ThrottleTimeSubscriber.prototype.clearThrottle = function () {
        var throttled = this.throttled;
        if (throttled) {
            if (this.trailing && this._hasTrailingValue) {
                this.destination.next(this._trailingValue);
                this._trailingValue = null;
                this._hasTrailingValue = false;
            }
            throttled.unsubscribe();
            this.remove(throttled);
            this.throttled = null;
        }
    };
    return ThrottleTimeSubscriber;
}(Subscriber["a" /* Subscriber */]));
function dispatchNext(arg) {
    var subscriber = arg.subscriber;
    subscriber.clearThrottle();
}
//# sourceMappingURL=throttleTime.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/defer.js
var defer = __webpack_require__(298);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/timeInterval.js
/** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */




function timeInterval(scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return function (source) {
        return Object(defer["a" /* defer */])(function () {
            return source.pipe(scan(function (_a, value) {
                var current = _a.current;
                return ({ value: value, current: scheduler.now(), last: current });
            }, { current: scheduler.now(), value: undefined, last: undefined }), Object(map["a" /* map */])(function (_a) {
                var current = _a.current, last = _a.last, value = _a.value;
                return new TimeInterval(value, current - last);
            }));
        });
    };
}
var TimeInterval = /*@__PURE__*/ (function () {
    function TimeInterval(value, interval) {
        this.value = value;
        this.interval = interval;
    }
    return TimeInterval;
}());

//# sourceMappingURL=timeInterval.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/TimeoutError.js
var TimeoutError = __webpack_require__(349);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/timeoutWith.js
/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */





function timeoutWith(due, withObservable, scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return function (source) {
        var absoluteTimeout = isDate(due);
        var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due);
        return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler));
    };
}
var TimeoutWithOperator = /*@__PURE__*/ (function () {
    function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) {
        this.waitFor = waitFor;
        this.absoluteTimeout = absoluteTimeout;
        this.withObservable = withObservable;
        this.scheduler = scheduler;
    }
    TimeoutWithOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new timeoutWith_TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler));
    };
    return TimeoutWithOperator;
}());
var timeoutWith_TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](TimeoutWithSubscriber, _super);
    function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.absoluteTimeout = absoluteTimeout;
        _this.waitFor = waitFor;
        _this.withObservable = withObservable;
        _this.scheduler = scheduler;
        _this.action = null;
        _this.scheduleTimeout();
        return _this;
    }
    TimeoutWithSubscriber.dispatchTimeout = function (subscriber) {
        var withObservable = subscriber.withObservable;
        subscriber._unsubscribeAndRecycle();
        subscriber.add(Object(subscribeToResult["a" /* subscribeToResult */])(subscriber, withObservable));
    };
    TimeoutWithSubscriber.prototype.scheduleTimeout = function () {
        var action = this.action;
        if (action) {
            this.action = action.schedule(this, this.waitFor);
        }
        else {
            this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this));
        }
    };
    TimeoutWithSubscriber.prototype._next = function (value) {
        if (!this.absoluteTimeout) {
            this.scheduleTimeout();
        }
        _super.prototype._next.call(this, value);
    };
    TimeoutWithSubscriber.prototype._unsubscribe = function () {
        this.action = null;
        this.scheduler = null;
        this.withObservable = null;
    };
    return TimeoutWithSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=timeoutWith.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/throwError.js
var throwError = __webpack_require__(295);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/timeout.js
/** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */




function timeout(due, scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return timeoutWith(due, Object(throwError["a" /* throwError */])(new TimeoutError["a" /* TimeoutError */]()), scheduler);
}
//# sourceMappingURL=timeout.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/timestamp.js
/** PURE_IMPORTS_START _scheduler_async,_map PURE_IMPORTS_END */


function timestamp(scheduler) {
    if (scheduler === void 0) {
        scheduler = scheduler_async["a" /* async */];
    }
    return Object(map["a" /* map */])(function (value) { return new Timestamp(value, scheduler.now()); });
}
var Timestamp = /*@__PURE__*/ (function () {
    function Timestamp(value, timestamp) {
        this.value = value;
        this.timestamp = timestamp;
    }
    return Timestamp;
}());

//# sourceMappingURL=timestamp.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/toArray.js
/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */

function toArrayReducer(arr, item, index) {
    if (index === 0) {
        return [item];
    }
    arr.push(item);
    return arr;
}
function toArray() {
    return reduce(toArrayReducer, []);
}
//# sourceMappingURL=toArray.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/window.js
/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function window_window(windowBoundaries) {
    return function windowOperatorFunction(source) {
        return source.lift(new window_WindowOperator(windowBoundaries));
    };
}
var window_WindowOperator = /*@__PURE__*/ (function () {
    function WindowOperator(windowBoundaries) {
        this.windowBoundaries = windowBoundaries;
    }
    WindowOperator.prototype.call = function (subscriber, source) {
        var windowSubscriber = new window_WindowSubscriber(subscriber);
        var sourceSubscription = source.subscribe(windowSubscriber);
        if (!sourceSubscription.closed) {
            windowSubscriber.add(Object(subscribeToResult["a" /* subscribeToResult */])(windowSubscriber, this.windowBoundaries));
        }
        return sourceSubscription;
    };
    return WindowOperator;
}());
var window_WindowSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WindowSubscriber, _super);
    function WindowSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.window = new Subject["a" /* Subject */]();
        destination.next(_this.window);
        return _this;
    }
    WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.openWindow();
    };
    WindowSubscriber.prototype.notifyError = function (error, innerSub) {
        this._error(error);
    };
    WindowSubscriber.prototype.notifyComplete = function (innerSub) {
        this._complete();
    };
    WindowSubscriber.prototype._next = function (value) {
        this.window.next(value);
    };
    WindowSubscriber.prototype._error = function (err) {
        this.window.error(err);
        this.destination.error(err);
    };
    WindowSubscriber.prototype._complete = function () {
        this.window.complete();
        this.destination.complete();
    };
    WindowSubscriber.prototype._unsubscribe = function () {
        this.window = null;
    };
    WindowSubscriber.prototype.openWindow = function () {
        var prevWindow = this.window;
        if (prevWindow) {
            prevWindow.complete();
        }
        var destination = this.destination;
        var newWindow = this.window = new Subject["a" /* Subject */]();
        destination.next(newWindow);
    };
    return WindowSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=window.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/windowCount.js
/** PURE_IMPORTS_START tslib,_Subscriber,_Subject PURE_IMPORTS_END */



function windowCount(windowSize, startWindowEvery) {
    if (startWindowEvery === void 0) {
        startWindowEvery = 0;
    }
    return function windowCountOperatorFunction(source) {
        return source.lift(new WindowCountOperator(windowSize, startWindowEvery));
    };
}
var WindowCountOperator = /*@__PURE__*/ (function () {
    function WindowCountOperator(windowSize, startWindowEvery) {
        this.windowSize = windowSize;
        this.startWindowEvery = startWindowEvery;
    }
    WindowCountOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new windowCount_WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery));
    };
    return WindowCountOperator;
}());
var windowCount_WindowCountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WindowCountSubscriber, _super);
    function WindowCountSubscriber(destination, windowSize, startWindowEvery) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        _this.windowSize = windowSize;
        _this.startWindowEvery = startWindowEvery;
        _this.windows = [new Subject["a" /* Subject */]()];
        _this.count = 0;
        destination.next(_this.windows[0]);
        return _this;
    }
    WindowCountSubscriber.prototype._next = function (value) {
        var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize;
        var destination = this.destination;
        var windowSize = this.windowSize;
        var windows = this.windows;
        var len = windows.length;
        for (var i = 0; i < len && !this.closed; i++) {
            windows[i].next(value);
        }
        var c = this.count - windowSize + 1;
        if (c >= 0 && c % startWindowEvery === 0 && !this.closed) {
            windows.shift().complete();
        }
        if (++this.count % startWindowEvery === 0 && !this.closed) {
            var window_1 = new Subject["a" /* Subject */]();
            windows.push(window_1);
            destination.next(window_1);
        }
    };
    WindowCountSubscriber.prototype._error = function (err) {
        var windows = this.windows;
        if (windows) {
            while (windows.length > 0 && !this.closed) {
                windows.shift().error(err);
            }
        }
        this.destination.error(err);
    };
    WindowCountSubscriber.prototype._complete = function () {
        var windows = this.windows;
        if (windows) {
            while (windows.length > 0 && !this.closed) {
                windows.shift().complete();
            }
        }
        this.destination.complete();
    };
    WindowCountSubscriber.prototype._unsubscribe = function () {
        this.count = 0;
        this.windows = null;
    };
    return WindowCountSubscriber;
}(Subscriber["a" /* Subscriber */]));
//# sourceMappingURL=windowCount.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/windowTime.js
/** PURE_IMPORTS_START tslib,_Subject,_scheduler_async,_Subscriber,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */






function windowTime_windowTime(windowTimeSpan) {
    var scheduler = scheduler_async["a" /* async */];
    var windowCreationInterval = null;
    var maxWindowSize = Number.POSITIVE_INFINITY;
    if (Object(isScheduler["a" /* isScheduler */])(arguments[3])) {
        scheduler = arguments[3];
    }
    if (Object(isScheduler["a" /* isScheduler */])(arguments[2])) {
        scheduler = arguments[2];
    }
    else if (Object(isNumeric["a" /* isNumeric */])(arguments[2])) {
        maxWindowSize = arguments[2];
    }
    if (Object(isScheduler["a" /* isScheduler */])(arguments[1])) {
        scheduler = arguments[1];
    }
    else if (Object(isNumeric["a" /* isNumeric */])(arguments[1])) {
        windowCreationInterval = arguments[1];
    }
    return function windowTimeOperatorFunction(source) {
        return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler));
    };
}
var WindowTimeOperator = /*@__PURE__*/ (function () {
    function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
        this.windowTimeSpan = windowTimeSpan;
        this.windowCreationInterval = windowCreationInterval;
        this.maxWindowSize = maxWindowSize;
        this.scheduler = scheduler;
    }
    WindowTimeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new windowTime_WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler));
    };
    return WindowTimeOperator;
}());
var windowTime_CountedSubject = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](CountedSubject, _super);
    function CountedSubject() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._numberOfNextedValues = 0;
        return _this;
    }
    CountedSubject.prototype.next = function (value) {
        this._numberOfNextedValues++;
        _super.prototype.next.call(this, value);
    };
    Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", {
        get: function () {
            return this._numberOfNextedValues;
        },
        enumerable: true,
        configurable: true
    });
    return CountedSubject;
}(Subject["a" /* Subject */]));
var windowTime_WindowTimeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WindowTimeSubscriber, _super);
    function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        _this.windowTimeSpan = windowTimeSpan;
        _this.windowCreationInterval = windowCreationInterval;
        _this.maxWindowSize = maxWindowSize;
        _this.scheduler = scheduler;
        _this.windows = [];
        var window = _this.openWindow();
        if (windowCreationInterval !== null && windowCreationInterval >= 0) {
            var closeState = { subscriber: _this, window: window, context: null };
            var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler };
            _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState));
            _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState));
        }
        else {
            var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan };
            _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState));
        }
        return _this;
    }
    WindowTimeSubscriber.prototype._next = function (value) {
        var windows = this.windows;
        var len = windows.length;
        for (var i = 0; i < len; i++) {
            var window_1 = windows[i];
            if (!window_1.closed) {
                window_1.next(value);
                if (window_1.numberOfNextedValues >= this.maxWindowSize) {
                    this.closeWindow(window_1);
                }
            }
        }
    };
    WindowTimeSubscriber.prototype._error = function (err) {
        var windows = this.windows;
        while (windows.length > 0) {
            windows.shift().error(err);
        }
        this.destination.error(err);
    };
    WindowTimeSubscriber.prototype._complete = function () {
        var windows = this.windows;
        while (windows.length > 0) {
            var window_2 = windows.shift();
            if (!window_2.closed) {
                window_2.complete();
            }
        }
        this.destination.complete();
    };
    WindowTimeSubscriber.prototype.openWindow = function () {
        var window = new windowTime_CountedSubject();
        this.windows.push(window);
        var destination = this.destination;
        destination.next(window);
        return window;
    };
    WindowTimeSubscriber.prototype.closeWindow = function (window) {
        window.complete();
        var windows = this.windows;
        windows.splice(windows.indexOf(window), 1);
    };
    return WindowTimeSubscriber;
}(Subscriber["a" /* Subscriber */]));
function dispatchWindowTimeSpanOnly(state) {
    var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window;
    if (window) {
        subscriber.closeWindow(window);
    }
    state.window = subscriber.openWindow();
    this.schedule(state, windowTimeSpan);
}
function dispatchWindowCreation(state) {
    var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval;
    var window = subscriber.openWindow();
    var action = this;
    var context = { action: action, subscription: null };
    var timeSpanState = { subscriber: subscriber, window: window, context: context };
    context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState);
    action.add(context.subscription);
    action.schedule(state, windowCreationInterval);
}
function dispatchWindowClose(state) {
    var subscriber = state.subscriber, window = state.window, context = state.context;
    if (context && context.action && context.subscription) {
        context.action.remove(context.subscription);
    }
    subscriber.closeWindow(window);
}
//# sourceMappingURL=windowTime.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/windowToggle.js
/** PURE_IMPORTS_START tslib,_Subject,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */





function windowToggle(openings, closingSelector) {
    return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); };
}
var WindowToggleOperator = /*@__PURE__*/ (function () {
    function WindowToggleOperator(openings, closingSelector) {
        this.openings = openings;
        this.closingSelector = closingSelector;
    }
    WindowToggleOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new windowToggle_WindowToggleSubscriber(subscriber, this.openings, this.closingSelector));
    };
    return WindowToggleOperator;
}());
var windowToggle_WindowToggleSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WindowToggleSubscriber, _super);
    function WindowToggleSubscriber(destination, openings, closingSelector) {
        var _this = _super.call(this, destination) || this;
        _this.openings = openings;
        _this.closingSelector = closingSelector;
        _this.contexts = [];
        _this.add(_this.openSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(_this, openings, openings));
        return _this;
    }
    WindowToggleSubscriber.prototype._next = function (value) {
        var contexts = this.contexts;
        if (contexts) {
            var len = contexts.length;
            for (var i = 0; i < len; i++) {
                contexts[i].window.next(value);
            }
        }
    };
    WindowToggleSubscriber.prototype._error = function (err) {
        var contexts = this.contexts;
        this.contexts = null;
        if (contexts) {
            var len = contexts.length;
            var index = -1;
            while (++index < len) {
                var context_1 = contexts[index];
                context_1.window.error(err);
                context_1.subscription.unsubscribe();
            }
        }
        _super.prototype._error.call(this, err);
    };
    WindowToggleSubscriber.prototype._complete = function () {
        var contexts = this.contexts;
        this.contexts = null;
        if (contexts) {
            var len = contexts.length;
            var index = -1;
            while (++index < len) {
                var context_2 = contexts[index];
                context_2.window.complete();
                context_2.subscription.unsubscribe();
            }
        }
        _super.prototype._complete.call(this);
    };
    WindowToggleSubscriber.prototype._unsubscribe = function () {
        var contexts = this.contexts;
        this.contexts = null;
        if (contexts) {
            var len = contexts.length;
            var index = -1;
            while (++index < len) {
                var context_3 = contexts[index];
                context_3.window.unsubscribe();
                context_3.subscription.unsubscribe();
            }
        }
    };
    WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        if (outerValue === this.openings) {
            var closingNotifier = void 0;
            try {
                var closingSelector = this.closingSelector;
                closingNotifier = closingSelector(innerValue);
            }
            catch (e) {
                return this.error(e);
            }
            var window_1 = new Subject["a" /* Subject */]();
            var subscription = new Subscription["a" /* Subscription */]();
            var context_4 = { window: window_1, subscription: subscription };
            this.contexts.push(context_4);
            var innerSubscription = Object(subscribeToResult["a" /* subscribeToResult */])(this, closingNotifier, context_4);
            if (innerSubscription.closed) {
                this.closeWindow(this.contexts.length - 1);
            }
            else {
                innerSubscription.context = context_4;
                subscription.add(innerSubscription);
            }
            this.destination.next(window_1);
        }
        else {
            this.closeWindow(this.contexts.indexOf(outerValue));
        }
    };
    WindowToggleSubscriber.prototype.notifyError = function (err) {
        this.error(err);
    };
    WindowToggleSubscriber.prototype.notifyComplete = function (inner) {
        if (inner !== this.openSubscription) {
            this.closeWindow(this.contexts.indexOf(inner.context));
        }
    };
    WindowToggleSubscriber.prototype.closeWindow = function (index) {
        if (index === -1) {
            return;
        }
        var contexts = this.contexts;
        var context = contexts[index];
        var window = context.window, subscription = context.subscription;
        contexts.splice(index, 1);
        window.complete();
        subscription.unsubscribe();
    };
    return WindowToggleSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=windowToggle.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/windowWhen.js
/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */




function windowWhen(closingSelector) {
    return function windowWhenOperatorFunction(source) {
        return source.lift(new windowWhen_WindowOperator(closingSelector));
    };
}
var windowWhen_WindowOperator = /*@__PURE__*/ (function () {
    function WindowOperator(closingSelector) {
        this.closingSelector = closingSelector;
    }
    WindowOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new windowWhen_WindowSubscriber(subscriber, this.closingSelector));
    };
    return WindowOperator;
}());
var windowWhen_WindowSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WindowSubscriber, _super);
    function WindowSubscriber(destination, closingSelector) {
        var _this = _super.call(this, destination) || this;
        _this.destination = destination;
        _this.closingSelector = closingSelector;
        _this.openWindow();
        return _this;
    }
    WindowSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.openWindow(innerSub);
    };
    WindowSubscriber.prototype.notifyError = function (error, innerSub) {
        this._error(error);
    };
    WindowSubscriber.prototype.notifyComplete = function (innerSub) {
        this.openWindow(innerSub);
    };
    WindowSubscriber.prototype._next = function (value) {
        this.window.next(value);
    };
    WindowSubscriber.prototype._error = function (err) {
        this.window.error(err);
        this.destination.error(err);
        this.unsubscribeClosingNotification();
    };
    WindowSubscriber.prototype._complete = function () {
        this.window.complete();
        this.destination.complete();
        this.unsubscribeClosingNotification();
    };
    WindowSubscriber.prototype.unsubscribeClosingNotification = function () {
        if (this.closingNotification) {
            this.closingNotification.unsubscribe();
        }
    };
    WindowSubscriber.prototype.openWindow = function (innerSub) {
        if (innerSub === void 0) {
            innerSub = null;
        }
        if (innerSub) {
            this.remove(innerSub);
            innerSub.unsubscribe();
        }
        var prevWindow = this.window;
        if (prevWindow) {
            prevWindow.complete();
        }
        var window = this.window = new Subject["a" /* Subject */]();
        this.destination.next(window);
        var closingNotifier;
        try {
            var closingSelector = this.closingSelector;
            closingNotifier = closingSelector();
        }
        catch (e) {
            this.destination.error(e);
            this.window.error(e);
            return;
        }
        this.add(this.closingNotification = Object(subscribeToResult["a" /* subscribeToResult */])(this, closingNotifier));
    };
    return WindowSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=windowWhen.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/withLatestFrom.js
/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */



function withLatestFrom() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    return function (source) {
        var project;
        if (typeof args[args.length - 1] === 'function') {
            project = args.pop();
        }
        var observables = args;
        return source.lift(new WithLatestFromOperator(observables, project));
    };
}
var WithLatestFromOperator = /*@__PURE__*/ (function () {
    function WithLatestFromOperator(observables, project) {
        this.observables = observables;
        this.project = project;
    }
    WithLatestFromOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new withLatestFrom_WithLatestFromSubscriber(subscriber, this.observables, this.project));
    };
    return WithLatestFromOperator;
}());
var withLatestFrom_WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](WithLatestFromSubscriber, _super);
    function WithLatestFromSubscriber(destination, observables, project) {
        var _this = _super.call(this, destination) || this;
        _this.observables = observables;
        _this.project = project;
        _this.toRespond = [];
        var len = observables.length;
        _this.values = new Array(len);
        for (var i = 0; i < len; i++) {
            _this.toRespond.push(i);
        }
        for (var i = 0; i < len; i++) {
            var observable = observables[i];
            _this.add(Object(subscribeToResult["a" /* subscribeToResult */])(_this, observable, observable, i));
        }
        return _this;
    }
    WithLatestFromSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.values[outerIndex] = innerValue;
        var toRespond = this.toRespond;
        if (toRespond.length > 0) {
            var found = toRespond.indexOf(outerIndex);
            if (found !== -1) {
                toRespond.splice(found, 1);
            }
        }
    };
    WithLatestFromSubscriber.prototype.notifyComplete = function () {
    };
    WithLatestFromSubscriber.prototype._next = function (value) {
        if (this.toRespond.length === 0) {
            var args = [value].concat(this.values);
            if (this.project) {
                this._tryProject(args);
            }
            else {
                this.destination.next(args);
            }
        }
    };
    WithLatestFromSubscriber.prototype._tryProject = function (args) {
        var result;
        try {
            result = this.project.apply(this, args);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(result);
    };
    return WithLatestFromSubscriber;
}(OuterSubscriber["a" /* OuterSubscriber */]));
//# sourceMappingURL=withLatestFrom.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/zip.js
var zip = __webpack_require__(299);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/zip.js
/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */

function zip_zip() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    return function zipOperatorFunction(source) {
        return source.lift.call(zip["b" /* zip */].apply(void 0, [source].concat(observables)));
    };
}
//# sourceMappingURL=zip.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/operators/zipAll.js
/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */

function zipAll(project) {
    return function (source) { return source.lift(new zip["a" /* ZipOperator */](project)); };
}
//# sourceMappingURL=zipAll.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/operators/index.js
/** PURE_IMPORTS_START  PURE_IMPORTS_END */








































































































//# sourceMappingURL=index.js.map


/***/ }),
/* 239 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(16);
/* harmony import */ var _model__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(243);
/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(166);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(112);
/* harmony import */ var _unit__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(37);
/* harmony import */ var _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(113);
/* harmony import */ var _properties__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(168);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var StructureSymmetry;
(function (StructureSymmetry) {
    function buildAssembly(structure, asmName) {
        var _this = this;
        return _mol_task__WEBPACK_IMPORTED_MODULE_5__[/* Task */ "b"].create('Build Assembly', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var models, assembly, coordinateSystem, assembler, queryCtx, _i, _a, g, selection, units, _b, _c, oper, _d, units_1, unit;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_e) {
                models = structure.models;
                if (models.length !== 1)
                    throw new Error('Can only build assemblies from structures based on 1 model.');
                assembly = _model__WEBPACK_IMPORTED_MODULE_6__["Symmetry"].findAssembly(models[0], asmName);
                if (!assembly)
                    throw new Error("Assembly '" + asmName + "' is not defined.");
                coordinateSystem = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SymmetryOperator */ "h"].create(assembly.id, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].identity(), { assembly: { id: assembly.id, operId: 0, operList: [] } });
                assembler = _structure__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].Builder({ coordinateSystem: coordinateSystem, label: structure.label });
                queryCtx = new _query__WEBPACK_IMPORTED_MODULE_7__[/* QueryContext */ "b"](structure);
                for (_i = 0, _a = assembly.operatorGroups; _i < _a.length; _i++) {
                    g = _a[_i];
                    selection = g.selector(queryCtx);
                    if (_query__WEBPACK_IMPORTED_MODULE_7__[/* StructureSelection */ "d"].structureCount(selection) === 0) {
                        continue;
                    }
                    units = _query__WEBPACK_IMPORTED_MODULE_7__[/* StructureSelection */ "d"].unionStructure(selection).units;
                    for (_b = 0, _c = g.operators; _b < _c.length; _b++) {
                        oper = _c[_b];
                        for (_d = 0, units_1 = units; _d < units_1.length; _d++) {
                            unit = units_1[_d];
                            assembler.addWithOperator(unit, oper);
                        }
                    }
                }
                return [2 /*return*/, assembler.getStructure()];
            });
        }); });
    }
    StructureSymmetry.buildAssembly = buildAssembly;
    function buildSymmetryAssembly(structure, generators, symmetry) {
        var _this = this;
        return _mol_task__WEBPACK_IMPORTED_MODULE_5__[/* Task */ "b"].create('Build Symmetry Assembly', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var models, modelCenter, assembler, queryCtx, _i, generators_1, g, selector, selection, units, _a, _b, _c, index, _d, i, j, k, operators, _e, units_2, unit, _f, operators_1, op;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                models = structure.models;
                if (models.length !== 1)
                    throw new Error('Can only build symmetry assemblies from structures based on 1 model.');
                modelCenter = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])();
                assembler = _structure__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].Builder({ label: structure.label, representativeModel: models[0] });
                queryCtx = new _query__WEBPACK_IMPORTED_MODULE_7__[/* QueryContext */ "b"](structure);
                for (_i = 0, generators_1 = generators; _i < generators_1.length; _i++) {
                    g = generators_1[_i];
                    selector = getSelector(g.asymIds);
                    selection = selector(queryCtx);
                    if (_query__WEBPACK_IMPORTED_MODULE_7__[/* StructureSelection */ "d"].structureCount(selection) === 0) {
                        continue;
                    }
                    units = _query__WEBPACK_IMPORTED_MODULE_7__[/* StructureSelection */ "d"].unionStructure(selection).units;
                    for (_a = 0, _b = g.operators; _a < _b.length; _a++) {
                        _c = _b[_a], index = _c.index, _d = _c.shift, i = _d[0], j = _d[1], k = _d[2];
                        operators = getOperatorsForIndex(symmetry, index, i, j, k, modelCenter);
                        for (_e = 0, units_2 = units; _e < units_2.length; _e++) {
                            unit = units_2[_e];
                            for (_f = 0, operators_1 = operators; _f < operators_1.length; _f++) {
                                op = operators_1[_f];
                                assembler.addWithOperator(unit, op);
                            }
                        }
                    }
                }
                return [2 /*return*/, assembler.getStructure()];
            });
        }); });
    }
    StructureSymmetry.buildSymmetryAssembly = buildSymmetryAssembly;
    function builderSymmetryMates(structure, radius) {
        return _mol_task__WEBPACK_IMPORTED_MODULE_5__[/* Task */ "b"].create('Find Symmetry Mates', function (ctx) { return findMatesRadius(ctx, structure, radius); });
    }
    StructureSymmetry.builderSymmetryMates = builderSymmetryMates;
    function buildSymmetryRange(structure, ijkMin, ijkMax) {
        return _mol_task__WEBPACK_IMPORTED_MODULE_5__[/* Task */ "b"].create('Build Symmetry', function (ctx) { return findSymmetryRange(ctx, structure, ijkMin, ijkMax); });
    }
    StructureSymmetry.buildSymmetryRange = buildSymmetryRange;
    /** Builds NCS structure, returns the original if NCS operators are not present. */
    function buildNcs(structure) {
        return _mol_task__WEBPACK_IMPORTED_MODULE_5__[/* Task */ "b"].create('Build NCS', function (ctx) { return _buildNCS(ctx, structure); });
    }
    StructureSymmetry.buildNcs = buildNcs;
    function areUnitsEquivalent(a, b) {
        return a.invariantId === b.invariantId && a.model.id === b.model.id && _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].areEqual(a.elements, b.elements);
    }
    StructureSymmetry.areUnitsEquivalent = areUnitsEquivalent;
    function UnitEquivalenceBuilder() {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* EquivalenceClasses */ "b"])(_unit__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"].hashUnit, areUnitsEquivalent);
    }
    StructureSymmetry.UnitEquivalenceBuilder = UnitEquivalenceBuilder;
    function computeTransformGroups(s) {
        var groups = UnitEquivalenceBuilder();
        for (var _i = 0, _a = s.units; _i < _a.length; _i++) {
            var u = _a[_i];
            groups.add(u.id, u);
        }
        var ret = [];
        for (var _b = 0, _c = groups.groups; _b < _c.length; _b++) {
            var eqUnits = _c[_b];
            ret.push(_unit__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"].SymmetryGroup(eqUnits.map(function (id) { return s.unitMap.get(id); })));
        }
        return ret;
    }
    StructureSymmetry.computeTransformGroups = computeTransformGroups;
    /** Checks if transform groups are equal up to their unit's transformations */
    function areTransformGroupsEquivalent(a, b) {
        if (a.length !== b.length)
            return false;
        for (var i = 0, il = a.length; i < il; ++i) {
            var au = a[i].units, bu = b[i].units;
            if (au.length !== bu.length)
                return false;
            if (a[i].hashCode !== b[i].hashCode)
                return false;
            for (var j = 0, _j = au.length; j < _j; j++) {
                if (au[j].conformation !== bu[j].conformation)
                    return false;
            }
        }
        return true;
    }
    StructureSymmetry.areTransformGroupsEquivalent = areTransformGroupsEquivalent;
})(StructureSymmetry || (StructureSymmetry = {}));
function getSelector(asymIds) {
    return _query__WEBPACK_IMPORTED_MODULE_7__[/* Queries */ "a"].generators.atoms({ chainTest: _query__WEBPACK_IMPORTED_MODULE_7__[/* Queries */ "a"].pred.and(_query__WEBPACK_IMPORTED_MODULE_7__[/* Queries */ "a"].pred.eq(function (ctx) { return _properties__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"].unit.operator_name(ctx.element); }, _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SymmetryOperator */ "h"].DefaultName), _query__WEBPACK_IMPORTED_MODULE_7__[/* Queries */ "a"].pred.inSet(function (ctx) { return _properties__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"].chain.label_asym_id(ctx.element); }, asymIds)) });
}
function getOperatorsForIndex(symmetry, index, i, j, k, modelCenter) {
    var spacegroup = symmetry.spacegroup, ncsOperators = symmetry.ncsOperators;
    var operators = [];
    var toFractional = spacegroup.cell.toFractional;
    var ref = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].transformMat4(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), modelCenter, toFractional);
    var symOp = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Spacegroup */ "e"].getSymmetryOperatorRef(spacegroup, index, i, j, k, ref);
    if (ncsOperators && ncsOperators.length) {
        for (var u = 0, ul = ncsOperators.length; u < ul; ++u) {
            var ncsOp = ncsOperators[u];
            var matrix = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].mul(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"])(), symOp.matrix, ncsOp.matrix);
            var operator = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SymmetryOperator */ "h"].create(symOp.name + " " + ncsOp.name, matrix, {
                assembly: symOp.assembly,
                ncsId: ncsOp.ncsId,
                hkl: symOp.hkl,
                spgrOp: symOp.spgrOp
            });
            operators.push(operator);
        }
    }
    else {
        operators.push(symOp);
    }
    return operators;
}
function getOperatorsForRange(symmetry, ijkMin, ijkMax, modelCenter) {
    var spacegroup = symmetry.spacegroup, ncsOperators = symmetry.ncsOperators;
    var ncsCount = (ncsOperators && ncsOperators.length) || 0;
    var operators = [];
    if (!ncsCount &&
        ijkMin[0] <= 0 && ijkMax[0] >= 0 &&
        ijkMin[1] <= 0 && ijkMax[1] >= 0 &&
        ijkMin[2] <= 0 && ijkMax[2] >= 0) {
        operators[0] = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Spacegroup */ "e"].getSymmetryOperator(spacegroup, 0, 0, 0, 0);
    }
    var toFractional = spacegroup.cell.toFractional;
    var ref = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].transformMat4(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), modelCenter, toFractional);
    for (var op = 0; op < spacegroup.operators.length; op++) {
        for (var i = ijkMin[0]; i <= ijkMax[0]; i++) {
            for (var j = ijkMin[1]; j <= ijkMax[1]; j++) {
                for (var k = ijkMin[2]; k <= ijkMax[2]; k++) {
                    // check if we have added identity as the 1st operator.
                    if (!ncsCount && op === 0 && i === 0 && j === 0 && k === 0)
                        continue;
                    operators.push.apply(operators, getOperatorsForIndex(symmetry, op, i, j, k, ref));
                }
            }
        }
    }
    return operators;
}
function getOperatorsCached333(symmetry, ref) {
    if (symmetry._operators_333 && _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].equals(ref, symmetry._operators_333.ref)) {
        return symmetry._operators_333.operators;
    }
    symmetry._operators_333 = {
        ref: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].clone(ref),
        operators: getOperatorsForRange(symmetry, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].create(-3, -3, -3), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].create(3, 3, 3), ref)
    };
    return symmetry._operators_333.operators;
}
function assembleOperators(structure, operators) {
    var assembler = _structure__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].Builder({ label: structure.label });
    var units = structure.units;
    for (var _i = 0, operators_2 = operators; _i < operators_2.length; _i++) {
        var oper = operators_2[_i];
        for (var _a = 0, units_3 = units; _a < units_3.length; _a++) {
            var unit = units_3[_a];
            assembler.addWithOperator(unit, oper);
        }
    }
    return assembler.getStructure();
}
function _buildNCS(ctx, structure) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var models, symmetry, operators;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            models = structure.models;
            if (models.length !== 1)
                throw new Error('Can only build NCS from structures based on 1 model.');
            symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_10__[/* ModelSymmetry */ "a"].Provider.get(models[0]);
            if (!symmetry)
                return [2 /*return*/, structure];
            operators = symmetry.ncsOperators;
            if (!operators || !operators.length)
                return [2 /*return*/, structure];
            return [2 /*return*/, assembleOperators(structure, operators)];
        });
    });
}
function findSymmetryRange(ctx, structure, ijkMin, ijkMax) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var models, symmetry, spacegroup, modelCenter, operators;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            models = structure.models;
            if (models.length !== 1)
                throw new Error('Can only build symmetries from structures based on 1 model.');
            symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_10__[/* ModelSymmetry */ "a"].Provider.get(models[0]);
            if (!symmetry)
                return [2 /*return*/, structure];
            spacegroup = symmetry.spacegroup;
            if (_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SpacegroupCell */ "f"].isZero(spacegroup.cell))
                return [2 /*return*/, structure];
            modelCenter = _model__WEBPACK_IMPORTED_MODULE_6__["Model"].getCenter(models[0]);
            operators = getOperatorsForRange(symmetry, ijkMin, ijkMax, modelCenter);
            return [2 /*return*/, assembleOperators(structure, operators)];
        });
    });
}
function findMatesRadius(ctx, structure, radius) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        function hash(unit, oper) {
            return unit.invariantId + "|" + oper.name;
        }
        var models, symmetry, spacegroup, modelCenter, operators, lookup, added, assembler, units, center, _i, operators_3, oper, _a, units_4, unit, boundingSphere, closeUnits, uI, _uI, closeUnit, h;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    models = structure.models;
                    if (models.length !== 1)
                        throw new Error('Can only build symmetries from structures based on 1 model.');
                    symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_10__[/* ModelSymmetry */ "a"].Provider.get(models[0]);
                    if (!symmetry)
                        return [2 /*return*/, structure];
                    spacegroup = symmetry.spacegroup;
                    if (_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SpacegroupCell */ "f"].isZero(spacegroup.cell))
                        return [2 /*return*/, structure];
                    if (!ctx.shouldUpdate) return [3 /*break*/, 2];
                    return [4 /*yield*/, ctx.update('Initialing...')];
                case 1:
                    _b.sent();
                    _b.label = 2;
                case 2:
                    modelCenter = _model__WEBPACK_IMPORTED_MODULE_6__["Model"].getCenter(models[0]);
                    operators = getOperatorsCached333(symmetry, modelCenter);
                    lookup = structure.lookup3d;
                    added = new Set();
                    assembler = _structure__WEBPACK_IMPORTED_MODULE_8__[/* default */ "a"].Builder({ label: structure.label });
                    units = structure.units;
                    center = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].zero();
                    _i = 0, operators_3 = operators;
                    _b.label = 3;
                case 3:
                    if (!(_i < operators_3.length)) return [3 /*break*/, 6];
                    oper = operators_3[_i];
                    for (_a = 0, units_4 = units; _a < units_4.length; _a++) {
                        unit = units_4[_a];
                        boundingSphere = unit.lookup3d.boundary.sphere;
                        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].transformMat4(center, boundingSphere.center, oper.matrix);
                        closeUnits = lookup.findUnitIndices(center[0], center[1], center[2], boundingSphere.radius + radius);
                        for (uI = 0, _uI = closeUnits.count; uI < _uI; uI++) {
                            closeUnit = units[closeUnits.indices[uI]];
                            if (!closeUnit.lookup3d.check(center[0], center[1], center[2], boundingSphere.radius + radius))
                                continue;
                            h = hash(unit, oper);
                            if (!added.has(h)) {
                                assembler.addWithOperator(unit, oper);
                                added.add(h);
                            }
                        }
                    }
                    if (!ctx.shouldUpdate) return [3 /*break*/, 5];
                    return [4 /*yield*/, ctx.update('Building symmetry...')];
                case 4:
                    _b.sent();
                    _b.label = 5;
                case 5:
                    _i++;
                    return [3 /*break*/, 3];
                case 6: return [2 /*return*/, assembler.getStructure()];
            }
        });
    });
}
/* harmony default export */ __webpack_exports__["a"] = (StructureSymmetry);
//# sourceMappingURL=symmetry.js.map

/***/ }),
/* 240 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concat; });
/* harmony import */ var _of__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(254);
/* harmony import */ var _operators_concatAll__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(345);
/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */


function concat() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    return Object(_operators_concatAll__WEBPACK_IMPORTED_MODULE_1__[/* concatAll */ "a"])()(_of__WEBPACK_IMPORTED_MODULE_0__[/* of */ "a"].apply(void 0, observables));
}
//# sourceMappingURL=concat.js.map


/***/ }),
/* 241 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createIsoValueParam; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IsoValueParam; });
/* unused harmony export VolumeIsosurfaceParams */
/* unused harmony export createVolumeIsosurfaceMesh */
/* unused harmony export IsosurfaceMeshParams */
/* unused harmony export IsosurfaceMeshVisual */
/* unused harmony export createVolumeIsosurfaceWireframe */
/* unused harmony export IsosurfaceWireframeParams */
/* unused harmony export IsosurfaceWireframeVisual */
/* unused harmony export IsosurfaceParams */
/* unused harmony export getIsosurfaceParams */
/* unused harmony export IsosurfaceRepresentation */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return IsosurfaceRepresentationProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(36);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(39);
/* harmony import */ var _mol_geo_util_marching_cubes_algorithm__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(210);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(237);
/* harmony import */ var _mol_geo_util_location_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(86);
/* harmony import */ var _mol_model_location__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(144);
/* harmony import */ var _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(74);
/* harmony import */ var _representation__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(40);
/* harmony import */ var _mol_util_number__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(174);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(23);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(6);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(1);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(29);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var defaultStats = { min: -1, max: 1, mean: 0, sigma: 0.1 };
function createIsoValueParam(defaultValue, stats) {
    var sts = stats || defaultStats;
    var min = sts.min, max = sts.max, mean = sts.mean, sigma = sts.sigma;
    // using ceil/floor could lead to "ouf of bounds" when converting
    var relMin = (min - mean) / sigma;
    var relMax = (max - mean) / sigma;
    var def = defaultValue;
    if (defaultValue.kind === 'absolute') {
        if (defaultValue.absoluteValue < min)
            def = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.absolute(min);
        else if (defaultValue.absoluteValue > max)
            def = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.absolute(max);
    }
    else {
        if (defaultValue.relativeValue < relMin)
            def = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.relative(relMin);
        else if (defaultValue.relativeValue > relMax)
            def = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.relative(relMax);
    }
    return _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Conditioned(def, {
        'absolute': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Converted(function (v) { return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toAbsolute(v, _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Grid */ "a"].One.stats).absoluteValue; }, function (v) { return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.absolute(v); }, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(mean, { min: min, max: max, step: Object(_mol_util_number__WEBPACK_IMPORTED_MODULE_10__[/* toPrecision */ "e"])(sigma / 100, 2) })),
        'relative': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Converted(function (v) { return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toRelative(v, _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Grid */ "a"].One.stats).relativeValue; }, function (v) { return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.relative(v); }, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(Math.min(1, relMax), { min: relMin, max: relMax, step: Object(_mol_util_number__WEBPACK_IMPORTED_MODULE_10__[/* toPrecision */ "e"])(Math.round(((max - min) / sigma)) / 100, 2) }))
    }, function (v) { return v.kind === 'absolute' ? 'absolute' : 'relative'; }, function (v, c) { return c === 'absolute' ? _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toAbsolute(v, sts) : _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toRelative(v, sts); }, { isEssential: true });
}
var IsoValueParam = createIsoValueParam(_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.relative(2));
var VolumeIsosurfaceParams = {
    isoValue: IsoValueParam
};
function getLoci(volume, props) {
    return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].Isosurface.Loci(volume, props.isoValue);
}
function getIsosurfaceLoci(pickingId, volume, props, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        return _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].Cell.Loci(volume, _mol_data_int__WEBPACK_IMPORTED_MODULE_12__["Interval"].ofSingleton(groupId));
    }
    return _mol_model_loci__WEBPACK_IMPORTED_MODULE_11__["EmptyLoci"];
}
function eachIsosurface(loci, volume, props, apply) {
    var changed = false;
    if (_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].isLoci(loci)) {
        if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].areEquivalent(loci.volume, volume))
            return false;
        if (apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_12__["Interval"].ofLength(volume.grid.cells.data.length)))
            changed = true;
    }
    else if (_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].Isosurface.isLoci(loci)) {
        if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].areEquivalent(loci.volume, volume))
            return false;
        if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.areSame(loci.isoValue, props.isoValue, volume.grid.stats))
            return false;
        if (apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_12__["Interval"].ofLength(volume.grid.cells.data.length)))
            changed = true;
    }
    else if (_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].Cell.isLoci(loci)) {
        if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].areEquivalent(loci.volume, volume))
            return false;
        if (_mol_data_int__WEBPACK_IMPORTED_MODULE_12__["Interval"].is(loci.indices)) {
            if (apply(loci.indices))
                changed = true;
        }
        else {
            _mol_data_int__WEBPACK_IMPORTED_MODULE_12__["OrderedSet"].forEach(loci.indices, function (v) {
                if (apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_12__["Interval"].ofSingleton(v)))
                    changed = true;
            });
        }
    }
    return changed;
}
//
function createVolumeIsosurfaceMesh(ctx, volume, theme, props, mesh) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var ids, surface, transform;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    ctx.runtime.update({ message: 'Marching cubes...' });
                    ids = Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_14__["fillSerial"])(new Int32Array(volume.grid.cells.data.length));
                    return [4 /*yield*/, Object(_mol_geo_util_marching_cubes_algorithm__WEBPACK_IMPORTED_MODULE_4__[/* computeMarchingCubesMesh */ "b"])({
                            isoLevel: _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
                            scalarField: volume.grid.cells,
                            idField: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_13__["Tensor"].create(volume.grid.cells.space, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_13__["Tensor"].Data1(ids))
                        }, mesh).runAsChild(ctx.runtime)];
                case 1:
                    surface = _a.sent();
                    transform = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Grid */ "a"].getGridToCartesianTransform(volume.grid);
                    ctx.runtime.update({ message: 'Transforming mesh...' });
                    _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__[/* Mesh */ "a"].transform(surface, transform);
                    return [2 /*return*/, surface];
            }
        });
    });
}
var IsosurfaceMeshParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__[/* Mesh */ "a"].Params), { quality: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__[/* Mesh */ "a"].Params.quality), { isEssential: false }) }), VolumeIsosurfaceParams);
function IsosurfaceMeshVisual(materialId) {
    return Object(_representation__WEBPACK_IMPORTED_MODULE_5__[/* VolumeVisual */ "c"])({
        defaultProps: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(IsosurfaceMeshParams),
        createGeometry: createVolumeIsosurfaceMesh,
        createLocationIterator: function (volume) { return Object(_mol_geo_util_location_iterator__WEBPACK_IMPORTED_MODULE_6__[/* LocationIterator */ "a"])(volume.grid.cells.data.length, 1, function () { return _mol_model_location__WEBPACK_IMPORTED_MODULE_7__[/* NullLocation */ "b"]; }); },
        getLoci: getIsosurfaceLoci,
        eachLocation: eachIsosurface,
        setUpdateState: function (state, volume, newProps, currentProps) {
            if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats))
                state.createGeometry = true;
        },
        geometryUtils: _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_3__[/* Mesh */ "a"].Utils
    }, materialId);
}
//
function createVolumeIsosurfaceWireframe(ctx, volume, theme, props, lines) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var ids, wireframe, transform;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    ctx.runtime.update({ message: 'Marching cubes...' });
                    ids = Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_14__["fillSerial"])(new Int32Array(volume.grid.cells.data.length));
                    return [4 /*yield*/, Object(_mol_geo_util_marching_cubes_algorithm__WEBPACK_IMPORTED_MODULE_4__[/* computeMarchingCubesLines */ "a"])({
                            isoLevel: _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
                            scalarField: volume.grid.cells,
                            idField: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_13__["Tensor"].create(volume.grid.cells.space, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_13__["Tensor"].Data1(ids))
                        }, lines).runAsChild(ctx.runtime)];
                case 1:
                    wireframe = _a.sent();
                    transform = _mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Grid */ "a"].getGridToCartesianTransform(volume.grid);
                    _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_8__[/* Lines */ "a"].transform(wireframe, transform);
                    return [2 /*return*/, wireframe];
            }
        });
    });
}
var IsosurfaceWireframeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_8__[/* Lines */ "a"].Params), { quality: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_8__[/* Lines */ "a"].Params.quality), { isEssential: false }), sizeFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Numeric(1.5, { min: 0, max: 10, step: 0.1 }) }), VolumeIsosurfaceParams);
function IsosurfaceWireframeVisual(materialId) {
    return Object(_representation__WEBPACK_IMPORTED_MODULE_5__[/* VolumeVisual */ "c"])({
        defaultProps: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(IsosurfaceWireframeParams),
        createGeometry: createVolumeIsosurfaceWireframe,
        createLocationIterator: function (volume) { return Object(_mol_geo_util_location_iterator__WEBPACK_IMPORTED_MODULE_6__[/* LocationIterator */ "a"])(volume.grid.cells.data.length, 1, function () { return _mol_model_location__WEBPACK_IMPORTED_MODULE_7__[/* NullLocation */ "b"]; }); },
        getLoci: getIsosurfaceLoci,
        eachLocation: eachIsosurface,
        setUpdateState: function (state, volume, newProps, currentProps) {
            if (!_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats))
                state.createGeometry = true;
        },
        geometryUtils: _mol_geo_geometry_lines_lines__WEBPACK_IMPORTED_MODULE_8__[/* Lines */ "a"].Utils
    }, materialId);
}
//
var IsosurfaceVisuals = {
    'solid': function (ctx, getParams) { return Object(_representation__WEBPACK_IMPORTED_MODULE_5__[/* VolumeRepresentation */ "a"])('Isosurface mesh', ctx, getParams, IsosurfaceMeshVisual, getLoci); },
    'wireframe': function (ctx, getParams) { return Object(_representation__WEBPACK_IMPORTED_MODULE_5__[/* VolumeRepresentation */ "a"])('Isosurface wireframe', ctx, getParams, IsosurfaceWireframeVisual, getLoci); },
};
var IsosurfaceParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, IsosurfaceMeshParams), IsosurfaceWireframeParams), { visuals: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].MultiSelect(['solid'], _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].objectToOptions(IsosurfaceVisuals)) });
function getIsosurfaceParams(ctx, volume) {
    var p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].clone(IsosurfaceParams);
    p.isoValue = createIsoValueParam(_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].IsoValue.relative(2), volume.grid.stats);
    return p;
}
function IsosurfaceRepresentation(ctx, getParams) {
    return _representation__WEBPACK_IMPORTED_MODULE_9__[/* Representation */ "a"].createMulti('Isosurface', ctx, getParams, _representation__WEBPACK_IMPORTED_MODULE_9__[/* Representation */ "a"].StateBuilder, IsosurfaceVisuals);
}
var IsosurfaceRepresentationProvider = Object(_representation__WEBPACK_IMPORTED_MODULE_5__[/* VolumeRepresentationProvider */ "b"])({
    name: 'isosurface',
    label: 'Isosurface',
    description: 'Displays an isosurface of volumetric data.',
    factory: IsosurfaceRepresentation,
    getParams: getIsosurfaceParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(IsosurfaceParams),
    defaultColorTheme: { name: 'uniform' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (volume) { return !_mol_model_volume__WEBPACK_IMPORTED_MODULE_2__[/* Volume */ "b"].isEmpty(volume); }
});
//# sourceMappingURL=isosurface.js.map

/***/ }),
/* 242 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Box; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return PerforatedBox; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return BoxCage; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _primitive__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(127);
/* harmony import */ var _polygon__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(149);
/* harmony import */ var _cage__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(184);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var a = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), b = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), c = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero(), d = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].zero();
var points = Object(_polygon__WEBPACK_IMPORTED_MODULE_2__[/* polygon */ "a"])(4, true);
/**
 * Create a box
 */
function createBox(perforated) {
    var builder = Object(_primitive__WEBPACK_IMPORTED_MODULE_1__[/* PrimitiveBuilder */ "a"])(12);
    // create sides
    for (var i = 0; i < 4; ++i) {
        var ni = (i + 1) % 4;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(a, points[i * 3], points[i * 3 + 1], -0.5);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(b, points[ni * 3], points[ni * 3 + 1], -0.5);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(c, points[ni * 3], points[ni * 3 + 1], 0.5);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(d, points[i * 3], points[i * 3 + 1], 0.5);
        builder.add(a, b, c);
        if (!perforated)
            builder.add(c, d, a);
    }
    // create bases
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(a, points[0], points[1], -0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(b, points[3], points[4], -0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(c, points[6], points[7], -0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(d, points[9], points[10], -0.5);
    builder.add(c, b, a);
    if (!perforated)
        builder.add(a, d, c);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(a, points[0], points[1], 0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(b, points[3], points[4], 0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(c, points[6], points[7], 0.5);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].set(d, points[9], points[10], 0.5);
    builder.add(a, b, c);
    if (!perforated)
        builder.add(c, d, a);
    return builder.getPrimitive();
}
var box;
function Box() {
    if (!box)
        box = createBox(false);
    return box;
}
var perforatedBox;
function PerforatedBox() {
    if (!perforatedBox)
        perforatedBox = createBox(true);
    return perforatedBox;
}
var boxCage;
function BoxCage() {
    if (!boxCage) {
        boxCage = Object(_cage__WEBPACK_IMPORTED_MODULE_3__[/* createCage */ "b"])([
            0.5, 0.5, -0.5,
            -0.5, 0.5, -0.5,
            -0.5, -0.5, -0.5,
            0.5, -0.5, -0.5,
            0.5, 0.5, 0.5,
            -0.5, 0.5, 0.5,
            -0.5, -0.5, 0.5,
            0.5, -0.5, 0.5
        ], [
            0, 4, 1, 5, 2, 6, 3, 7,
            0, 1, 1, 2, 2, 3, 3, 0,
            4, 5, 5, 6, 6, 7, 7, 4 // top base
        ]);
    }
    return boxCage;
}
//# sourceMappingURL=box.js.map

/***/ }),
/* 243 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _model_model__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(352);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Model", function() { return _model_model__WEBPACK_IMPORTED_MODULE_0__["a"]; });

/* harmony import */ var _model_types__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(22);
/* harmony reexport (module object) */ __webpack_require__.d(__webpack_exports__, "Types", function() { return _model_types__WEBPACK_IMPORTED_MODULE_1__; });
/* harmony import */ var _model_properties_symmetry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(291);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "Symmetry", function() { return _model_properties_symmetry__WEBPACK_IMPORTED_MODULE_2__["b"]; });

/* harmony import */ var _model_properties_sequence__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(343);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "StructureSequence", function() { return _model_properties_sequence__WEBPACK_IMPORTED_MODULE_3__["a"]; });

/* harmony import */ var _model_properties_custom_indexed__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(402);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "IndexedCustomProperty", function() { return _model_properties_custom_indexed__WEBPACK_IMPORTED_MODULE_4__["a"]; });

/* harmony import */ var _model_indexing__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(403);
/* harmony import */ var _model_indexing__WEBPACK_IMPORTED_MODULE_5___default = /*#__PURE__*/__webpack_require__.n(_model_indexing__WEBPACK_IMPORTED_MODULE_5__);
/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _model_indexing__WEBPACK_IMPORTED_MODULE_5__) if(["Model","Types","Symmetry","StructureSequence","IndexedCustomProperty","default"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _model_indexing__WEBPACK_IMPORTED_MODULE_5__[key]; }) }(__WEBPACK_IMPORT_KEY__));
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







//# sourceMappingURL=model.js.map

/***/ }),
/* 244 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InterUnitGraph; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_generic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(55);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var InterUnitGraph = /** @class */ (function () {
    function InterUnitGraph(map) {
        this.map = map;
        var count = 0;
        var edges = [];
        var edgeKeyIndex = new Map();
        var vertexKeyIndex = new Map();
        this.map.forEach(function (pairEdgesArray) {
            pairEdgesArray.forEach(function (pairEdges) {
                count += pairEdges.edgeCount;
                pairEdges.connectedIndices.forEach(function (indexA) {
                    pairEdges.getEdges(indexA).forEach(function (edgeInfo) {
                        var unitA = pairEdges.unitA, unitB = pairEdges.unitB;
                        var edgeKey = InterUnitGraph.getEdgeKey(indexA, unitA, edgeInfo.indexB, unitB);
                        edgeKeyIndex.set(edgeKey, edges.length);
                        var vertexKey = InterUnitGraph.getVertexKey(indexA, unitA);
                        var e = vertexKeyIndex.get(vertexKey);
                        if (e === undefined)
                            vertexKeyIndex.set(vertexKey, [edges.length]);
                        else
                            e.push(edges.length);
                        edges.push(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, edgeInfo), { indexA: indexA, unitA: unitA, unitB: unitB }));
                    });
                });
            });
        });
        this.edgeCount = count;
        this.edges = edges;
        this.edgeKeyIndex = edgeKeyIndex;
        this.vertexKeyIndex = vertexKeyIndex;
    }
    /** Get an array of unit-pair-edges that are connected to the given unit */
    InterUnitGraph.prototype.getConnectedUnits = function (unit) {
        if (!this.map.has(unit.id))
            return emptyArray;
        return this.map.get(unit.id);
    };
    /** Index into this.edges */
    InterUnitGraph.prototype.getEdgeIndex = function (indexA, unitA, indexB, unitB) {
        var edgeKey = InterUnitGraph.getEdgeKey(indexA, unitA, indexB, unitB);
        var index = this.edgeKeyIndex.get(edgeKey);
        return index !== undefined ? index : -1;
    };
    /** Check if edge exists */
    InterUnitGraph.prototype.hasEdge = function (indexA, unitA, indexB, unitB) {
        return this.getEdgeIndex(indexA, unitA, indexB, unitB) !== -1;
    };
    /** Get inter-unit edge given a pair of indices and units */
    InterUnitGraph.prototype.getEdge = function (indexA, unitA, indexB, unitB) {
        var index = this.getEdgeIndex(indexA, unitA, indexB, unitB);
        return index !== -1 ? this.edges[index] : undefined;
    };
    /** Indices into this.edges */
    InterUnitGraph.prototype.getEdgeIndices = function (index, unit) {
        return this.vertexKeyIndex.get(InterUnitGraph.getVertexKey(index, unit)) || [];
    };
    return InterUnitGraph;
}());
(function (InterUnitGraph) {
    var UnitPairEdges = /** @class */ (function () {
        function UnitPairEdges(unitA, unitB, edgeCount, connectedIndices, edgeMap) {
            this.unitA = unitA;
            this.unitB = unitB;
            this.edgeCount = edgeCount;
            this.connectedIndices = connectedIndices;
            this.edgeMap = edgeMap;
        }
        UnitPairEdges.prototype.hasEdges = function (indexA) {
            return this.edgeMap.has(indexA);
        };
        UnitPairEdges.prototype.getEdges = function (indexA) {
            if (!this.edgeMap.has(indexA))
                return emptyArray;
            return this.edgeMap.get(indexA);
        };
        Object.defineProperty(UnitPairEdges.prototype, "areUnitsOrdered", {
            get: function () {
                return this.unitA.id < this.unitB.id;
            },
            enumerable: false,
            configurable: true
        });
        return UnitPairEdges;
    }());
    InterUnitGraph.UnitPairEdges = UnitPairEdges;
    function getEdgeKey(indexA, unitA, indexB, unitB) {
        return indexA + "|" + unitA.id + "|" + indexB + "|" + unitB.id;
    }
    InterUnitGraph.getEdgeKey = getEdgeKey;
    function getVertexKey(index, unit) {
        return index + "|" + unit.id;
    }
    InterUnitGraph.getVertexKey = getVertexKey;
    //
    function addMapEntry(map, a, b) {
        if (map.has(a))
            map.get(a).push(b);
        else
            map.set(a, [b]);
    }
    var Builder = /** @class */ (function () {
        function Builder() {
            this.map = new Map();
        }
        Builder.prototype.startUnitPair = function (unitA, unitB) {
            this.uA = unitA;
            this.uB = unitB;
            this.mapAB = new Map();
            this.mapBA = new Map();
            this.linkedA = _mol_data_generic__WEBPACK_IMPORTED_MODULE_1__[/* UniqueArray */ "c"].create();
            this.linkedB = _mol_data_generic__WEBPACK_IMPORTED_MODULE_1__[/* UniqueArray */ "c"].create();
            this.linkCount = 0;
        };
        Builder.prototype.finishUnitPair = function () {
            if (this.linkCount === 0)
                return;
            addMapEntry(this.map, this.uA.id, new UnitPairEdges(this.uA, this.uB, this.linkCount, this.linkedA.array, this.mapAB));
            addMapEntry(this.map, this.uB.id, new UnitPairEdges(this.uB, this.uA, this.linkCount, this.linkedB.array, this.mapBA));
        };
        Builder.prototype.add = function (indexA, indexB, props) {
            addMapEntry(this.mapAB, indexA, { indexB: indexB, props: props });
            addMapEntry(this.mapBA, indexB, { indexB: indexA, props: props });
            _mol_data_generic__WEBPACK_IMPORTED_MODULE_1__[/* UniqueArray */ "c"].add(this.linkedA, indexA, indexA);
            _mol_data_generic__WEBPACK_IMPORTED_MODULE_1__[/* UniqueArray */ "c"].add(this.linkedB, indexB, indexB);
            this.linkCount += 1;
        };
        Builder.prototype.getMap = function () {
            return this.map;
        };
        return Builder;
    }());
    InterUnitGraph.Builder = Builder;
})(InterUnitGraph || (InterUnitGraph = {}));
var emptyArray = [];
//# sourceMappingURL=inter-unit-graph.js.map

/***/ }),
/* 245 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ElementNames; });
/* unused harmony export AlkaliMetals */
/* unused harmony export isAlkaliMetal */
/* unused harmony export AlkalineEarthMetals */
/* unused harmony export isAlkalineEarthMetal */
/* unused harmony export PolyatomicNonmetals */
/* unused harmony export isPolyatomicNonmetal */
/* unused harmony export DiatomicNonmetals */
/* unused harmony export isDiatomicNonmetal */
/* unused harmony export NobleGases */
/* unused harmony export isNobleGas */
/* unused harmony export PostTransitionMetals */
/* unused harmony export isPostTransitionMetal */
/* unused harmony export Metalloids */
/* unused harmony export isMetalloid */
/* unused harmony export Halogens */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return isHalogen; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isTransitionMetal; });
/* unused harmony export isLanthanide */
/* unused harmony export isActinide */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return isMetal; });
/* unused harmony export isNonmetal */
/* harmony import */ var _measures__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(305);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var ElementNames = {
    H: 'Hydrogen', HE: 'Helium', LI: 'Lithium', BE: 'Beryllium', B: 'Boron', C: 'Carbon', N: 'Nitrogen', O: 'Oxygen', F: 'Fluorine', NE: 'Neon', NA: 'Sodium', MG: 'Magnesium', AL: 'Aluminum', SI: 'Silicon', P: 'Phosphorus', S: 'Sulfur', CL: 'Chlorine', AR: 'Argon', K: 'Potassium', CA: 'Calcium', SC: 'Scandium', TI: 'Titanium', V: 'Vanadium', CR: 'Chromium', MN: 'Manganese', FE: 'Iron', CO: 'Cobalt', NI: 'Nickel', CU: 'Copper', ZN: 'Zinc', GA: 'Gallium', GE: 'Germanium', AS: 'Arsenic', SE: 'Selenium', BR: 'Bromine', KR: 'Krypton', RB: 'Rubidium', SR: 'Strontium', Y: 'Yttrium', ZR: 'Zirconium', NB: 'Niobium', MO: 'Molybdenum', TC: 'Technetium', RU: 'Ruthenium', RH: 'Rhodium', PD: 'Palladium', AG: 'Silver', CD: 'Cadmium', IN: 'Indium', SN: 'Tin', SB: 'Antimony', TE: 'Tellurium', I: 'Iodine', XE: 'Xenon', CS: 'Cesium', BA: 'Barium', LA: 'Lanthanum', CE: 'Cerium', PR: 'Praseodymium', ND: 'Neodymium', PM: 'Promethium', SM: 'Samarium', EU: 'Europium', GD: 'Gadolinium', TB: 'Terbium', DY: 'Dysprosium', HO: 'Holmium', ER: 'Erbium', TM: 'Thulium', YB: 'Ytterbium', LU: 'Lutetium', HF: 'Hafnium', TA: 'Tantalum', W: 'Wolfram', RE: 'Rhenium', OS: 'Osmium', IR: 'Iridium', PT: 'Platinum', AU: 'Gold', HG: 'Mercury', TL: 'Thallium', PB: 'Lead', BI: 'Bismuth', PO: 'Polonium', AT: 'Astatine', RN: 'Radon', FR: 'Francium', RA: 'Radium', AC: 'Actinium', TH: 'Thorium', PA: 'Protactinium', U: 'Uranium', NP: 'Neptunium', PU: 'Plutonium', AM: 'Americium', CM: 'Curium', BK: 'Berkelium', CF: 'Californium', ES: 'Einsteinium', FM: 'Fermium', MD: 'Mendelevium', NO: 'Nobelium', LR: 'Lawrencium', RF: 'Rutherfordium', DB: 'Dubnium', SG: 'Seaborgium', BH: 'Bohrium', HS: 'Hassium', MT: 'Meitnerium', DS: 'Darmstadtium', RG: 'Roentgenium', CN: 'Copernicium', NH: 'Nihonium', FL: 'Flerovium', MC: 'Moscovium', LV: 'Livermorium', TS: 'Tennessine', OG: 'Oganesson'
};
var AlkaliMetals = new Set(['LI', 'NA', 'K', 'RB', 'CS', 'FR']);
function isAlkaliMetal(element) { return AlkaliMetals.has(element); }
var AlkalineEarthMetals = new Set(['BE', 'MG', 'CA', 'SR', 'BA', 'RA']);
function isAlkalineEarthMetal(element) { return AlkalineEarthMetals.has(element); }
var PolyatomicNonmetals = new Set(['C', 'P', 'S', 'SE']);
function isPolyatomicNonmetal(element) { return PolyatomicNonmetals.has(element); }
var DiatomicNonmetals = new Set(['H', 'N', 'O', 'F', 'CL', 'BR', 'I']);
function isDiatomicNonmetal(element) { return DiatomicNonmetals.has(element); }
var NobleGases = new Set(['HE', 'NE', 'AR', 'KR', 'XE', 'RN']);
function isNobleGas(element) { return NobleGases.has(element); }
var PostTransitionMetals = new Set(['ZN', 'GA', 'CD', 'IN', 'SN', 'HG', 'TI', 'PB', 'BI', 'PO', 'CN']);
function isPostTransitionMetal(element) { return PostTransitionMetals.has(element); }
var Metalloids = new Set(['B', 'SI', 'GE', 'AS', 'SB', 'TE', 'AT']);
function isMetalloid(element) { return Metalloids.has(element); }
var Halogens = new Set(['F', 'CL', 'BR', 'I', 'AT']);
function isHalogen(element) { return Halogens.has(element); }
function isTransitionMetal(element) {
    var no = Object(_measures__WEBPACK_IMPORTED_MODULE_0__[/* AtomNumber */ "a"])(element);
    return ((no >= 21 && no <= 29) ||
        (no >= 39 && no <= 47) ||
        (no >= 72 && no <= 79) ||
        (no >= 104 && no <= 108));
}
function isLanthanide(element) {
    var no = Object(_measures__WEBPACK_IMPORTED_MODULE_0__[/* AtomNumber */ "a"])(element);
    return no >= 57 && no <= 71;
}
function isActinide(element) {
    var no = Object(_measures__WEBPACK_IMPORTED_MODULE_0__[/* AtomNumber */ "a"])(element);
    return no >= 89 && no <= 103;
}
function isMetal(element) {
    return (isAlkaliMetal(element) ||
        isAlkalineEarthMetal(element) ||
        isLanthanide(element) ||
        isActinide(element) ||
        isTransitionMetal(element) ||
        isPostTransitionMetal(element));
}
function isNonmetal(element) {
    return (isDiatomicNonmetal(element) ||
        isPolyatomicNonmetal(element) ||
        isNobleGas(element));
}
//# sourceMappingURL=types.js.map

/***/ }),
/* 246 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StructureComponentManager", function() { return /* binding */ component_StructureComponentManager; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/base.js
var base = __webpack_require__(33);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions.js
var interactions = __webpack_require__(108);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/query/utils/structure-set.js
var structure_set = __webpack_require__(156);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/state.js
var static_state = __webpack_require__(216);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/names.js
var names = __webpack_require__(47);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/component.js
var mol_plugin_state_component = __webpack_require__(118);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-overpaint.js
var structure_overpaint = __webpack_require__(368);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-representation-params.js
var structure_representation_params = __webpack_require__(162);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-selection-query.js
var structure_selection_query = __webpack_require__(80);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/representation.js + 13 modules
var representation = __webpack_require__(198);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/clipping.js
var mol_theme_clipping = __webpack_require__(77);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-clipping.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var ClippingManagerTag = 'clipping-controls';
function setStructureClipping(plugin, components, groups, lociGetter, types) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _this = this;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, eachRepr(plugin, components, function (update, repr, clippingCell) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        var structure, loci, layer, bundleLayers, filtered, filtered;
                        return Object(tslib_es6["__generator"])(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (types && types.length > 0 && !types.includes(repr.params.values.type.name))
                                        return [2 /*return*/];
                                    structure = repr.obj.data.source.data;
                                    return [4 /*yield*/, lociGetter(structure.root)];
                                case 1:
                                    loci = _a.sent();
                                    if (mol_model_loci["Loci"].isEmpty(loci))
                                        return [2 /*return*/];
                                    layer = {
                                        bundle: mol_model_structure["StructureElement"].Bundle.fromLoci(loci),
                                        groups: groups
                                    };
                                    if (clippingCell) {
                                        bundleLayers = Object(tslib_es6["__spreadArrays"])(clippingCell.params.values.layers, [layer]);
                                        filtered = getFilteredBundle(bundleLayers, structure);
                                        update.to(clippingCell).update(mol_theme_clipping["a" /* Clipping */].toBundle(filtered));
                                    }
                                    else {
                                        filtered = getFilteredBundle([layer], structure);
                                        update.to(repr.transform.ref)
                                            .apply(transforms["StateTransforms"].Representation.ClippingStructureRepresentation3DFromBundle, mol_theme_clipping["a" /* Clipping */].toBundle(filtered), { tags: ClippingManagerTag });
                                    }
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function eachRepr(plugin, components, callback) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var state, update, _i, components_1, c, _a, _b, r, clipping;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    state = plugin.state.data;
                    update = state.build();
                    _i = 0, components_1 = components;
                    _c.label = 1;
                case 1:
                    if (!(_i < components_1.length)) return [3 /*break*/, 6];
                    c = components_1[_i];
                    _a = 0, _b = c.representations;
                    _c.label = 2;
                case 2:
                    if (!(_a < _b.length)) return [3 /*break*/, 5];
                    r = _b[_a];
                    clipping = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.ClippingStructureRepresentation3DFromBundle, r.cell.transform.ref).withTag(ClippingManagerTag));
                    return [4 /*yield*/, callback(update, r.cell, clipping[0])];
                case 3:
                    _c.sent();
                    _c.label = 4;
                case 4:
                    _a++;
                    return [3 /*break*/, 2];
                case 5:
                    _i++;
                    return [3 /*break*/, 1];
                case 6: return [2 /*return*/, update.commit({ doNotUpdateCurrent: true })];
            }
        });
    });
}
/** filter clipping layers for given structure */
function getFilteredBundle(layers, structure) {
    var clipping = mol_theme_clipping["a" /* Clipping */].ofBundle(layers, structure.root);
    var merged = mol_theme_clipping["a" /* Clipping */].merge(clipping);
    return mol_theme_clipping["a" /* Clipping */].filter(merged, structure);
}
//# sourceMappingURL=structure-clipping.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/transparency.js
var mol_theme_transparency = __webpack_require__(131);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-transparency.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var TransparencyManagerTag = 'transparency-controls';
function setStructureTransparency(plugin, components, value, lociGetter, types) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _this = this;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, structure_transparency_eachRepr(plugin, components, function (update, repr, transparencyCell) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        var structure, loci, layer, bundleLayers, filtered, filtered;
                        return Object(tslib_es6["__generator"])(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (types && types.length > 0 && !types.includes(repr.params.values.type.name))
                                        return [2 /*return*/];
                                    structure = repr.obj.data.source.data;
                                    return [4 /*yield*/, lociGetter(structure.root)];
                                case 1:
                                    loci = _a.sent();
                                    if (mol_model_loci["Loci"].isEmpty(loci))
                                        return [2 /*return*/];
                                    layer = {
                                        bundle: mol_model_structure["StructureElement"].Bundle.fromLoci(loci),
                                        value: value,
                                    };
                                    if (transparencyCell) {
                                        bundleLayers = Object(tslib_es6["__spreadArrays"])(transparencyCell.params.values.layers, [layer]);
                                        filtered = structure_transparency_getFilteredBundle(bundleLayers, structure);
                                        update.to(transparencyCell).update(mol_theme_transparency["a" /* Transparency */].toBundle(filtered));
                                    }
                                    else {
                                        filtered = structure_transparency_getFilteredBundle([layer], structure);
                                        update.to(repr.transform.ref)
                                            .apply(transforms["StateTransforms"].Representation.TransparencyStructureRepresentation3DFromBundle, mol_theme_transparency["a" /* Transparency */].toBundle(filtered), { tags: TransparencyManagerTag });
                                    }
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function clearStructureTransparency(plugin, components, types) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _this = this;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, structure_transparency_eachRepr(plugin, components, function (update, repr, transparencyCell) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        return Object(tslib_es6["__generator"])(this, function (_a) {
                            if (types && types.length > 0 && !types.includes(repr.params.values.type.name))
                                return [2 /*return*/];
                            if (transparencyCell) {
                                update.delete(transparencyCell.transform.ref);
                            }
                            return [2 /*return*/];
                        });
                    }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function structure_transparency_eachRepr(plugin, components, callback) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var state, update, _i, components_1, c, _a, _b, r, transparency;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    state = plugin.state.data;
                    update = state.build();
                    _i = 0, components_1 = components;
                    _c.label = 1;
                case 1:
                    if (!(_i < components_1.length)) return [3 /*break*/, 6];
                    c = components_1[_i];
                    _a = 0, _b = c.representations;
                    _c.label = 2;
                case 2:
                    if (!(_a < _b.length)) return [3 /*break*/, 5];
                    r = _b[_a];
                    transparency = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.TransparencyStructureRepresentation3DFromBundle, r.cell.transform.ref).withTag(TransparencyManagerTag));
                    return [4 /*yield*/, callback(update, r.cell, transparency[0])];
                case 3:
                    _c.sent();
                    _c.label = 4;
                case 4:
                    _a++;
                    return [3 /*break*/, 2];
                case 5:
                    _i++;
                    return [3 /*break*/, 1];
                case 6: return [2 /*return*/, update.commit({ doNotUpdateCurrent: true })];
            }
        });
    });
}
/** filter transparency layers for given structure */
function structure_transparency_getFilteredBundle(layers, structure) {
    var transparency = mol_theme_transparency["a" /* Transparency */].ofBundle(layers, structure.root);
    var merged = mol_theme_transparency["a" /* Transparency */].merge(transparency);
    return mol_theme_transparency["a" /* Transparency */].filter(merged, structure);
}
//# sourceMappingURL=structure-transparency.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/selection/structure-focus-representation.js
var structure_focus_representation = __webpack_require__(320);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/component.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





















var component_StructureComponentManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureComponentManager, _super);
    function StructureComponentManager(plugin) {
        var _this = _super.call(this, { options: param_definition["ParamDefinition"].getDefaultValues(StructureComponentManager.OptionsParams) }) || this;
        _this.plugin = plugin;
        _this.events = {
            optionsUpdated: _this.ev()
        };
        return _this;
    }
    Object.defineProperty(StructureComponentManager.prototype, "currentStructures", {
        get: function () {
            return this.plugin.managers.structure.hierarchy.selection.structures;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureComponentManager.prototype, "pivotStructure", {
        get: function () {
            return this.currentStructures[0];
        },
        enumerable: false,
        configurable: true
    });
    StructureComponentManager.prototype.setOptions = function (options) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var interactionChanged, update, _i, _a, s, _b, _c, c;
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_d) {
                interactionChanged = options.interactions !== this.state.options.interactions;
                this.updateState({ options: options });
                this.events.optionsUpdated.next();
                update = this.dataState.build();
                for (_i = 0, _a = this.currentStructures; _i < _a.length; _i++) {
                    s = _a[_i];
                    for (_b = 0, _c = s.components; _b < _c.length; _b++) {
                        c = _c[_b];
                        this.updateReprParams(update, c);
                    }
                }
                return [2 /*return*/, this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        return Object(tslib_es6["__generator"])(this, function (_a) {
                            switch (_a.label) {
                                case 0: return [4 /*yield*/, update.commit()];
                                case 1:
                                    _a.sent();
                                    return [4 /*yield*/, this.plugin.state.updateBehavior(structure_focus_representation["StructureFocusRepresentation"], function (p) {
                                            p.ignoreHydrogens = !options.showHydrogens;
                                        })];
                                case 2:
                                    _a.sent();
                                    if (!interactionChanged) return [3 /*break*/, 4];
                                    return [4 /*yield*/, this.updateInterationProps()];
                                case 3:
                                    _a.sent();
                                    _a.label = 4;
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); })];
            });
        });
    };
    StructureComponentManager.prototype.updateReprParams = function (update, component) {
        var _a = this.state.options, showHydrogens = _a.showHydrogens, quality = _a.visualQuality;
        var ignoreHydrogens = !showHydrogens;
        for (var _i = 0, _b = component.representations; _i < _b.length; _i++) {
            var r = _b[_i];
            if (r.cell.transform.transformer !== representation["StructureRepresentation3D"])
                continue;
            var params = r.cell.transform.params;
            if (!!params.type.params.ignoreHydrogens !== ignoreHydrogens || params.type.params.quality !== quality) {
                update.to(r.cell).update(function (old) {
                    old.type.params.ignoreHydrogens = ignoreHydrogens;
                    old.type.params.quality = quality;
                });
            }
        }
    };
    StructureComponentManager.prototype.updateInterationProps = function () {
        var _a, _b, _c;
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var _i, _d, s, interactionParams, oldParams, pd, params;
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        _i = 0, _d = this.currentStructures;
                        _e.label = 1;
                    case 1:
                        if (!(_i < _d.length)) return [3 /*break*/, 6];
                        s = _d[_i];
                        interactionParams = interactions["a" /* InteractionsProvider */].getParams((_a = s.cell.obj) === null || _a === void 0 ? void 0 : _a.data);
                        if (!s.properties) return [3 /*break*/, 3];
                        oldParams = (_b = s.properties.cell.transform.params) === null || _b === void 0 ? void 0 : _b.properties[interactions["a" /* InteractionsProvider */].descriptor.name];
                        if (param_definition["ParamDefinition"].areEqual(interactionParams, oldParams, this.state.options.interactions))
                            return [3 /*break*/, 5];
                        return [4 /*yield*/, this.dataState.build().to(s.properties.cell)
                                .update(function (old) {
                                old.properties[interactions["a" /* InteractionsProvider */].descriptor.name] = _this.state.options.interactions;
                            })
                                .commit()];
                    case 2:
                        _e.sent();
                        return [3 /*break*/, 5];
                    case 3:
                        pd = this.plugin.customStructureProperties.getParams((_c = s.cell.obj) === null || _c === void 0 ? void 0 : _c.data);
                        params = param_definition["ParamDefinition"].getDefaultValues(pd);
                        if (param_definition["ParamDefinition"].areEqual(interactionParams, params.properties[interactions["a" /* InteractionsProvider */].descriptor.name], this.state.options.interactions))
                            return [3 /*break*/, 5];
                        params.properties[interactions["a" /* InteractionsProvider */].descriptor.name] = this.state.options.interactions;
                        return [4 /*yield*/, this.plugin.builders.structure.insertStructureProperties(s.cell, params)];
                    case 4:
                        _e.sent();
                        _e.label = 5;
                    case 5:
                        _i++;
                        return [3 /*break*/, 1];
                    case 6: return [2 /*return*/];
                }
            });
        });
    };
    StructureComponentManager.prototype.applyPreset = function (structures, provider, params) {
        var _this = this;
        return this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, structures_1, s, preset;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _i = 0, structures_1 = structures;
                        _a.label = 1;
                    case 1:
                        if (!(_i < structures_1.length)) return [3 /*break*/, 5];
                        s = structures_1[_i];
                        return [4 /*yield*/, this.plugin.builders.structure.representation.applyPreset(s.cell, provider, params)];
                    case 2:
                        preset = _a.sent();
                        return [4 /*yield*/, this.syncPreset(s, preset)];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 1];
                    case 5: return [2 /*return*/];
                }
            });
        }); }, { canUndo: 'Preset' });
    };
    StructureComponentManager.prototype.syncPreset = function (root, preset) {
        if (!preset || !preset.components)
            return this.clearComponents([root]);
        var keptRefs = new Set();
        Object(object["c" /* objectForEach */])(preset.components, function (c) {
            if (c)
                keptRefs.add(c.ref);
        });
        if (preset.representations) {
            Object(object["c" /* objectForEach */])(preset.representations, function (r) {
                if (r)
                    keptRefs.add(r.ref);
            });
        }
        if (keptRefs.size === 0)
            return this.clearComponents([root]);
        var changed = false;
        var update = this.dataState.build();
        var sync = function (r) {
            if (!keptRefs.has(r.cell.transform.ref)) {
                changed = true;
                update.delete(r.cell);
            }
        };
        for (var _i = 0, _a = root.components; _i < _a.length; _i++) {
            var c = _a[_i];
            sync(c);
            for (var _b = 0, _c = c.representations; _b < _c.length; _b++) {
                var r = _c[_b];
                sync(r);
            }
            if (c.genericRepresentations) {
                for (var _d = 0, _e = c.genericRepresentations; _d < _e.length; _d++) {
                    var r = _e[_d];
                    sync(r);
                }
            }
        }
        if (root.genericRepresentations) {
            for (var _f = 0, _g = root.genericRepresentations; _f < _g.length; _f++) {
                var r = _g[_f];
                sync(r);
            }
        }
        if (changed)
            return update.commit();
    };
    StructureComponentManager.prototype.clear = function (structures) {
        return this.clearComponents(structures);
    };
    StructureComponentManager.prototype.selectThis = function (components) {
        var _a;
        var mng = this.plugin.managers.structure.selection;
        mng.clear();
        for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
            var c = components_1[_i];
            var loci = mol_model_structure["Structure"].toSubStructureElementLoci(c.structure.cell.obj.data, (_a = c.cell.obj) === null || _a === void 0 ? void 0 : _a.data);
            mng.fromLoci('set', loci);
        }
    };
    StructureComponentManager.prototype.canBeModified = function (ref) {
        return this.plugin.builders.structure.isComponentTransform(ref.cell);
    };
    StructureComponentManager.prototype.modifyByCurrentSelection = function (components, action) {
        var _this = this;
        return this.plugin.runTask(mol_task["b" /* Task */].create('Modify Component', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var b, _i, components_2, c, selection;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        b = this.dataState.build();
                        for (_i = 0, components_2 = components; _i < components_2.length; _i++) {
                            c = components_2[_i];
                            if (!this.canBeModified(c))
                                continue;
                            selection = this.plugin.managers.structure.selection.getStructure(c.structure.cell.obj.data);
                            if (!selection || selection.elementCount === 0)
                                continue;
                            this.modifyComponent(b, c, selection, action);
                        }
                        return [4 /*yield*/, this.dataState.updateTree(b, { canUndo: 'Modify Selection' }).runInContext(taskCtx)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); }));
    };
    StructureComponentManager.prototype.toggleVisibility = function (components, reprPivot) {
        if (components.length === 0)
            return;
        if (!reprPivot) {
            var isHidden = !components[0].cell.state.isHidden;
            for (var _i = 0, components_3 = components; _i < components_3.length; _i++) {
                var c = components_3[_i];
                Object(static_state["setSubtreeVisibility"])(this.dataState, c.cell.transform.ref, isHidden);
            }
        }
        else {
            var index = components[0].representations.indexOf(reprPivot);
            var isHidden = !reprPivot.cell.state.isHidden;
            for (var _a = 0, components_4 = components; _a < components_4.length; _a++) {
                var c = components_4[_a];
                // TODO: is it ok to use just the index here? Could possible lead to ugly edge cases, but perhaps not worth the trouble to "fix".
                var repr = c.representations[index];
                if (!repr)
                    continue;
                Object(static_state["setSubtreeVisibility"])(this.dataState, repr.cell.transform.ref, isHidden);
            }
        }
    };
    StructureComponentManager.prototype.removeRepresentations = function (components, pivot) {
        if (components.length === 0)
            return;
        var toRemove = [];
        if (pivot) {
            var index = components[0].representations.indexOf(pivot);
            if (index < 0)
                return;
            for (var _i = 0, components_5 = components; _i < components_5.length; _i++) {
                var c = components_5[_i];
                if (c.representations[index])
                    toRemove.push(c.representations[index]);
            }
        }
        else {
            for (var _a = 0, components_6 = components; _a < components_6.length; _a++) {
                var c = components_6[_a];
                for (var _b = 0, _c = c.representations; _b < _c.length; _b++) {
                    var r = _c[_b];
                    toRemove.push(r);
                }
            }
        }
        return this.plugin.managers.structure.hierarchy.remove(toRemove, true);
    };
    StructureComponentManager.prototype.updateRepresentations = function (components, pivot, params) {
        if (components.length === 0)
            return Promise.resolve();
        var index = components[0].representations.indexOf(pivot);
        if (index < 0)
            return Promise.resolve();
        var update = this.dataState.build();
        for (var _i = 0, components_7 = components; _i < components_7.length; _i++) {
            var c = components_7[_i];
            // TODO: is it ok to use just the index here? Could possible lead to ugly edge cases, but perhaps not worth the trouble to "fix".
            var repr = c.representations[index];
            if (!repr)
                continue;
            if (repr.cell.transform.transformer !== pivot.cell.transform.transformer)
                continue;
            update.to(repr.cell).update(params);
        }
        return update.commit({ canUndo: 'Update Representation' });
    };
    StructureComponentManager.prototype.updateRepresentationsTheme = function (components, paramsOrProvider) {
        var _a, _b, _c, _d;
        if (components.length === 0)
            return;
        var update = this.dataState.build();
        for (var _i = 0, components_8 = components; _i < components_8.length; _i++) {
            var c = components_8[_i];
            var _loop_1 = function (repr) {
                var old = repr.cell.transform.params;
                var params = typeof paramsOrProvider === 'function' ? paramsOrProvider(c, repr) : paramsOrProvider;
                var colorTheme = params.color === 'default'
                    ? Object(structure_representation_params["createStructureColorThemeParams"])(this_1.plugin, (_a = c.structure.cell.obj) === null || _a === void 0 ? void 0 : _a.data, old === null || old === void 0 ? void 0 : old.type.name)
                    : params.color
                        ? Object(structure_representation_params["createStructureColorThemeParams"])(this_1.plugin, (_b = c.structure.cell.obj) === null || _b === void 0 ? void 0 : _b.data, old === null || old === void 0 ? void 0 : old.type.name, params.color, params.colorParams)
                        : void 0;
                var sizeTheme = params.size === 'default'
                    ? Object(structure_representation_params["createStructureSizeThemeParams"])(this_1.plugin, (_c = c.structure.cell.obj) === null || _c === void 0 ? void 0 : _c.data, old === null || old === void 0 ? void 0 : old.type.name)
                    : params.color
                        ? Object(structure_representation_params["createStructureSizeThemeParams"])(this_1.plugin, (_d = c.structure.cell.obj) === null || _d === void 0 ? void 0 : _d.data, old === null || old === void 0 ? void 0 : old.type.name, params.size, params.sizeParams)
                        : void 0;
                if (colorTheme || sizeTheme) {
                    update.to(repr.cell).update(function (prev) {
                        if (colorTheme)
                            prev.colorTheme = colorTheme;
                        if (sizeTheme)
                            prev.sizeTheme = sizeTheme;
                    });
                }
            };
            var this_1 = this;
            for (var _e = 0, _f = c.representations; _e < _f.length; _e++) {
                var repr = _f[_e];
                _loop_1(repr);
            }
        }
        return update.commit({ canUndo: 'Update Theme' });
    };
    StructureComponentManager.prototype.addRepresentation = function (components, type) {
        var _this = this;
        if (components.length === 0)
            return;
        var _a = this.state.options, showHydrogens = _a.showHydrogens, quality = _a.visualQuality;
        var ignoreHydrogens = !showHydrogens;
        var typeParams = { ignoreHydrogens: ignoreHydrogens, quality: quality };
        return this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, components_9, component;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _i = 0, components_9 = components;
                        _a.label = 1;
                    case 1:
                        if (!(_i < components_9.length)) return [3 /*break*/, 4];
                        component = components_9[_i];
                        return [4 /*yield*/, this.plugin.builders.structure.representation.addRepresentation(component.cell, {
                                type: this.plugin.representation.structure.registry.get(type),
                                typeParams: typeParams
                            })];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        }); }, { canUndo: 'Add Representation' });
    };
    StructureComponentManager.prototype.tryFindComponent = function (structure, selection) {
        var _this = this;
        if (structure.components.length === 0)
            return;
        return this.plugin.runTask(mol_task["b" /* Task */].create('Find Component', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var data, sel, _a, _b, _i, _c, c, comp;
            var _d, _e;
            return Object(tslib_es6["__generator"])(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        data = (_d = structure.cell.obj) === null || _d === void 0 ? void 0 : _d.data;
                        if (!data)
                            return [2 /*return*/];
                        _b = (_a = mol_model_structure["StructureSelection"]).unionStructure;
                        return [4 /*yield*/, selection.getSelection(this.plugin, taskCtx, data)];
                    case 1:
                        sel = _b.apply(_a, [_f.sent()]);
                        for (_i = 0, _c = structure.components; _i < _c.length; _i++) {
                            c = _c[_i];
                            comp = (_e = c.cell.obj) === null || _e === void 0 ? void 0 : _e.data;
                            if (!comp || !c.cell.parent)
                                continue;
                            if (Object(structure_set["a" /* structureAreEqual */])(sel, comp))
                                return [2 /*return*/, c.cell];
                        }
                        return [2 /*return*/];
                }
            });
        }); }));
    };
    StructureComponentManager.prototype.add = function (params, structures) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                return [2 /*return*/, this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        var xs, _a, showHydrogens, quality, ignoreHydrogens, typeParams, componentKey, _i, xs_1, s, component;
                        return Object(tslib_es6["__generator"])(this, function (_b) {
                            switch (_b.label) {
                                case 0:
                                    xs = structures || this.currentStructures;
                                    if (xs.length === 0)
                                        return [2 /*return*/];
                                    _a = this.state.options, showHydrogens = _a.showHydrogens, quality = _a.visualQuality;
                                    ignoreHydrogens = !showHydrogens;
                                    typeParams = { ignoreHydrogens: ignoreHydrogens, quality: quality };
                                    componentKey = mol_util["c" /* UUID */].create22();
                                    _i = 0, xs_1 = xs;
                                    _b.label = 1;
                                case 1:
                                    if (!(_i < xs_1.length)) return [3 /*break*/, 8];
                                    s = xs_1[_i];
                                    component = void 0;
                                    if (!params.options.checkExisting) return [3 /*break*/, 3];
                                    return [4 /*yield*/, this.tryFindComponent(s, params.selection)];
                                case 2:
                                    component = _b.sent();
                                    _b.label = 3;
                                case 3:
                                    if (!!component) return [3 /*break*/, 5];
                                    return [4 /*yield*/, this.plugin.builders.structure.tryCreateComponentFromSelection(s.cell, params.selection, componentKey, {
                                            label: params.options.label || (params.selection === structure_selection_query["b" /* StructureSelectionQueries */].current ? 'Custom Selection' : ''),
                                        })];
                                case 4:
                                    component = _b.sent();
                                    _b.label = 5;
                                case 5:
                                    if (params.representation === 'none' || !component)
                                        return [3 /*break*/, 7];
                                    return [4 /*yield*/, this.plugin.builders.structure.representation.addRepresentation(component, {
                                            type: this.plugin.representation.structure.registry.get(params.representation),
                                            typeParams: typeParams
                                        })];
                                case 6:
                                    _b.sent();
                                    _b.label = 7;
                                case 7:
                                    _i++;
                                    return [3 /*break*/, 1];
                                case 8: return [2 /*return*/];
                            }
                        });
                    }); }, { canUndo: 'Add Selection' })];
            });
        });
    };
    StructureComponentManager.prototype.applyTheme = function (params, structures) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                return [2 /*return*/, this.plugin.dataTransaction(function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                        var xs, getLoci, _i, xs_2, s, p, p, p;
                        var _this = this;
                        return Object(tslib_es6["__generator"])(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    xs = structures || this.currentStructures;
                                    if (xs.length === 0)
                                        return [2 /*return*/];
                                    getLoci = function (s) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () { var _a, _b; return Object(tslib_es6["__generator"])(this, function (_c) {
                                        switch (_c.label) {
                                            case 0:
                                                _b = (_a = mol_model_structure["StructureSelection"]).toLociWithSourceUnits;
                                                return [4 /*yield*/, params.selection.getSelection(this.plugin, ctx, s)];
                                            case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
                                        }
                                    }); }); };
                                    _i = 0, xs_2 = xs;
                                    _a.label = 1;
                                case 1:
                                    if (!(_i < xs_2.length)) return [3 /*break*/, 10];
                                    s = xs_2[_i];
                                    if (!(params.action.name === 'reset')) return [3 /*break*/, 3];
                                    return [4 /*yield*/, Object(structure_overpaint["setStructureOverpaint"])(this.plugin, s.components, -1, getLoci, params.representations)];
                                case 2:
                                    _a.sent();
                                    return [3 /*break*/, 9];
                                case 3:
                                    if (!(params.action.name === 'color')) return [3 /*break*/, 5];
                                    p = params.action.params;
                                    return [4 /*yield*/, Object(structure_overpaint["setStructureOverpaint"])(this.plugin, s.components, p.color, getLoci, params.representations)];
                                case 4:
                                    _a.sent();
                                    return [3 /*break*/, 9];
                                case 5:
                                    if (!(params.action.name === 'transparency')) return [3 /*break*/, 7];
                                    p = params.action.params;
                                    return [4 /*yield*/, setStructureTransparency(this.plugin, s.components, p.value, getLoci, params.representations)];
                                case 6:
                                    _a.sent();
                                    return [3 /*break*/, 9];
                                case 7:
                                    if (!(params.action.name === 'clipping')) return [3 /*break*/, 9];
                                    p = params.action.params;
                                    return [4 /*yield*/, setStructureClipping(this.plugin, s.components, mol_theme_clipping["a" /* Clipping */].Groups.fromNames(p.excludeGroups), getLoci, params.representations)];
                                case 8:
                                    _a.sent();
                                    _a.label = 9;
                                case 9:
                                    _i++;
                                    return [3 /*break*/, 1];
                                case 10: return [2 /*return*/];
                            }
                        });
                    }); }, { canUndo: 'Apply Theme' })];
            });
        });
    };
    StructureComponentManager.prototype.modifyComponent = function (builder, component, by, action) {
        var _a, _b, _c;
        var structure = (_a = component.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
        if (!structure)
            return;
        if ((action === 'subtract' || action === 'intersect') && !Object(structure_set["b" /* structureAreIntersecting */])(structure, by))
            return;
        var parent = (_b = component.structure.cell.obj) === null || _b === void 0 ? void 0 : _b.data;
        var modified = action === 'union'
            ? Object(structure_set["e" /* structureUnion */])(parent, [structure, by])
            : action === 'intersect'
                ? Object(structure_set["c" /* structureIntersect */])(structure, by)
                : Object(structure_set["d" /* structureSubtract */])(structure, by);
        if (modified.elementCount === 0) {
            builder.delete(component.cell.transform.ref);
        }
        else {
            var bundle = mol_model_structure["StructureElement"].Bundle.fromSubStructure(parent, modified);
            var params = {
                type: { name: 'bundle', params: bundle },
                nullIfEmpty: true,
                label: (_c = component.cell.obj) === null || _c === void 0 ? void 0 : _c.label
            };
            builder.to(component.cell).update(params);
        }
    };
    StructureComponentManager.prototype.updateLabel = function (component, label) {
        var _a, _b;
        var params = {
            type: (_a = component.cell.params) === null || _a === void 0 ? void 0 : _a.values.type,
            nullIfEmpty: (_b = component.cell.params) === null || _b === void 0 ? void 0 : _b.values.nullIfEmpty,
            label: label
        };
        this.dataState.build().to(component.cell).update(params).commit();
    };
    Object.defineProperty(StructureComponentManager.prototype, "dataState", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    StructureComponentManager.prototype.clearComponents = function (structures) {
        var deletes = this.dataState.build();
        for (var _i = 0, structures_2 = structures; _i < structures_2.length; _i++) {
            var s = structures_2[_i];
            for (var _a = 0, _b = s.components; _a < _b.length; _a++) {
                var c = _b[_a];
                deletes.delete(c.cell.transform.ref);
            }
        }
        return deletes.commit({ canUndo: 'Clear Selections' });
    };
    return StructureComponentManager;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));
(function (StructureComponentManager) {
    StructureComponentManager.OptionsParams = {
        showHydrogens: param_definition["ParamDefinition"].Boolean(true, { description: 'Toggle display of hydrogen atoms in representations' }),
        visualQuality: param_definition["ParamDefinition"].Select('auto', base["b" /* VisualQualityOptions */], { description: 'Control the visual/rendering quality of representations' }),
        interactions: param_definition["ParamDefinition"].Group(interactions["a" /* InteractionsProvider */].defaultParams, { label: 'Non-covalent Interactions' }),
    };
    function getAddParams(plugin, params) {
        var options = plugin.query.structure.registry.options;
        params = Object(tslib_es6["__assign"])({ pivot: plugin.managers.structure.component.pivotStructure, allowNone: true, hideSelection: false, checkExisting: false }, params);
        return {
            selection: param_definition["ParamDefinition"].Select(options[1][0], options, { isHidden: params === null || params === void 0 ? void 0 : params.hideSelection }),
            representation: getRepresentationTypesSelect(plugin, params === null || params === void 0 ? void 0 : params.pivot, (params === null || params === void 0 ? void 0 : params.allowNone) ? [['none', '< Create Later >']] : []),
            options: param_definition["ParamDefinition"].Group({
                label: param_definition["ParamDefinition"].Text(''),
                checkExisting: param_definition["ParamDefinition"].Boolean(!!(params === null || params === void 0 ? void 0 : params.checkExisting), { help: function () { return ({ description: 'Checks if a selection with the specifield elements already exists to avoid creating duplicate components.' }); } }),
            })
        };
    }
    StructureComponentManager.getAddParams = getAddParams;
    function getThemeParams(plugin, pivot) {
        var options = plugin.query.structure.registry.options;
        return {
            selection: param_definition["ParamDefinition"].Select(options[1][0], options, { isHidden: false }),
            action: param_definition["ParamDefinition"].MappedStatic('color', {
                color: param_definition["ParamDefinition"].Group({
                    color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].blue, { isExpanded: true }),
                }, { isFlat: true }),
                reset: param_definition["ParamDefinition"].EmptyGroup({ label: 'Reset Color' }),
                transparency: param_definition["ParamDefinition"].Group({
                    value: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.01 }),
                }, { isFlat: true }),
                clipping: param_definition["ParamDefinition"].Group({
                    excludeGroups: param_definition["ParamDefinition"].MultiSelect([], param_definition["ParamDefinition"].objectToOptions(mol_theme_clipping["a" /* Clipping */].Groups.Names)),
                }, { isFlat: true }),
            }),
            representations: param_definition["ParamDefinition"].MultiSelect([], getRepresentationTypes(plugin, pivot), { emptyValue: 'All' })
        };
    }
    StructureComponentManager.getThemeParams = getThemeParams;
    function getRepresentationTypes(plugin, pivot) {
        var _a, _b;
        return ((_a = pivot === null || pivot === void 0 ? void 0 : pivot.cell.obj) === null || _a === void 0 ? void 0 : _a.data) ? plugin.representation.structure.registry.getApplicableTypes((_b = pivot.cell.obj) === null || _b === void 0 ? void 0 : _b.data)
            : plugin.representation.structure.registry.types;
    }
    StructureComponentManager.getRepresentationTypes = getRepresentationTypes;
    function getRepresentationTypesSelect(plugin, pivot, custom, label) {
        var types = Object(tslib_es6["__spreadArrays"])(custom, getRepresentationTypes(plugin, pivot));
        return param_definition["ParamDefinition"].Select(types[0][0], types, { label: label });
    }
})(component_StructureComponentManager || (component_StructureComponentManager = {}));
//# sourceMappingURL=component.js.map

/***/ }),
/* 247 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "GaussianDensitySchema", function() { return /* binding */ GaussianDensitySchema; });
__webpack_require__.d(__webpack_exports__, "GaussianDensityShaderCode", function() { return /* binding */ GaussianDensityShaderCode; });
__webpack_require__.d(__webpack_exports__, "GaussianDensityGPU", function() { return /* binding */ GaussianDensityGPU; });
__webpack_require__.d(__webpack_exports__, "GaussianDensityTexture", function() { return /* binding */ GaussianDensityTexture; });
__webpack_require__.d(__webpack_exports__, "GaussianDensityTexture2d", function() { return /* binding */ GaussianDensityTexture2d; });
__webpack_require__.d(__webpack_exports__, "GaussianDensityTexture3d", function() { return /* binding */ GaussianDensityTexture3d; });
__webpack_require__.d(__webpack_exports__, "fieldFromTexture2d", function() { return /* binding */ fieldFromTexture2d; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable.js
var mol_gl_renderable = __webpack_require__(98);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/float-packing.js
var float_packing = __webpack_require__(217);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-item.js
var render_item = __webpack_require__(99);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/schema.js
var renderable_schema = __webpack_require__(17);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/gaussian-density.vert.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */
/* harmony default export */ var gaussian_density_vert = ("\nprecision highp float;\n\nattribute vec3 aPosition;\nattribute float aRadius;\n\nvarying vec3 vPosition;\nvarying float vRadiusSqInv;\n\n#if defined(dCalcType_groupId)\n    attribute float aGroup;\n    varying float vGroup;\n#endif\n\nuniform vec3 uBboxSize;\nuniform vec3 uBboxMin;\nuniform float uCurrentSlice;\nuniform float uResolution;\n\nvoid main() {\n    vRadiusSqInv = 1.0 / (aRadius * aRadius);\n    #if defined(dCalcType_groupId)\n        vGroup = aGroup;\n    #endif\n    gl_PointSize = floor(((aRadius * 4.0) / uResolution) + 0.5);\n    vPosition = (aPosition - uBboxMin) / uResolution;\n    gl_Position = vec4(((aPosition - uBboxMin) / uBboxSize) * 2.0 - 1.0, 1.0);\n}\n");
//# sourceMappingURL=gaussian-density.vert.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/gaussian-density.frag.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */
/* harmony default export */ var gaussian_density_frag = ("\nprecision highp float;\n\nvarying vec3 vPosition;\nvarying float vRadiusSqInv;\n#if defined(dCalcType_groupId)\n    precision highp sampler2D;\n    uniform sampler2D tMinDistanceTex;\n    uniform vec3 uGridTexDim;\n    varying float vGroup;\n#endif\n\n#include common\n\nuniform vec3 uGridDim;\nuniform vec2 uGridTexScale;\nuniform float uCurrentSlice;\nuniform float uCurrentX;\nuniform float uCurrentY;\nuniform float uAlpha;\nuniform float uResolution;\n\nvoid main() {\n    vec2 v = gl_FragCoord.xy - vec2(uCurrentX, uCurrentY) - 0.5;\n    vec3 fragPos = vec3(v.x, v.y, uCurrentSlice);\n    float dist = distance(fragPos, vPosition) * uResolution;\n\n    #if defined(dCalcType_density)\n        float density = exp(-uAlpha * ((dist * dist) * vRadiusSqInv));\n        gl_FragColor.a = density;\n    #elif defined(dCalcType_minDistance)\n        gl_FragColor.a = 10000.0 - dist;\n    #elif defined(dCalcType_groupId)\n        float minDistance = 10000.0 - texture2D(tMinDistanceTex, (gl_FragCoord.xy) / (uGridTexDim.xy / uGridTexScale)).a;\n        if (dist > minDistance + uResolution * 0.05)\n            discard;\n        gl_FragColor.rgb = encodeFloatRGB(vGroup);\n    #endif\n}\n");
//# sourceMappingURL=gaussian-density.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/gaussian-density/gpu.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author Michael Krone <michael.krone@uni-tuebingen.de>
 */












var GaussianDensitySchema = {
    drawCount: Object(renderable_schema["j" /* ValueSpec */])('number'),
    instanceCount: Object(renderable_schema["j" /* ValueSpec */])('number'),
    aRadius: Object(renderable_schema["a" /* AttributeSpec */])('float32', 1, 0),
    aPosition: Object(renderable_schema["a" /* AttributeSpec */])('float32', 3, 0),
    aGroup: Object(renderable_schema["a" /* AttributeSpec */])('float32', 1, 0),
    uCurrentSlice: Object(renderable_schema["i" /* UniformSpec */])('f'),
    uCurrentX: Object(renderable_schema["i" /* UniformSpec */])('f'),
    uCurrentY: Object(renderable_schema["i" /* UniformSpec */])('f'),
    uBboxMin: Object(renderable_schema["i" /* UniformSpec */])('v3', true),
    uBboxSize: Object(renderable_schema["i" /* UniformSpec */])('v3', true),
    uGridDim: Object(renderable_schema["i" /* UniformSpec */])('v3', true),
    uGridTexDim: Object(renderable_schema["i" /* UniformSpec */])('v3', true),
    uGridTexScale: Object(renderable_schema["i" /* UniformSpec */])('v2', true),
    uAlpha: Object(renderable_schema["i" /* UniformSpec */])('f', true),
    uResolution: Object(renderable_schema["i" /* UniformSpec */])('f', true),
    tMinDistanceTex: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'),
    dGridTexType: Object(renderable_schema["c" /* DefineSpec */])('string', ['2d', '3d']),
    dCalcType: Object(renderable_schema["c" /* DefineSpec */])('string', ['density', 'minDistance', 'groupId']),
};
var GaussianDensityShaderCode = Object(shader_code["f" /* ShaderCode */])('gaussian-density', gaussian_density_vert, gaussian_density_frag, { standardDerivatives: false, fragDepth: false });
function GaussianDensityGPU(position, box, radius, props, webgl) {
    // always use texture2d when the gaussian density needs to be downloaded from the GPU,
    // it's faster than texture3d
    // console.time('GaussianDensityTexture2d')
    var _a = calcGaussianDensityTexture2d(webgl, position, box, radius, props), scale = _a.scale, bbox = _a.bbox, texture = _a.texture, gridDim = _a.gridDim, gridTexDim = _a.gridTexDim;
    // webgl.waitForGpuCommandsCompleteSync()
    // console.timeEnd('GaussianDensityTexture2d')
    var _b = fieldFromTexture2d(webgl, texture, gridDim, gridTexDim), field = _b.field, idField = _b.idField;
    return { field: field, idField: idField, transform: getTransform(scale, bbox) };
}
function GaussianDensityTexture(webgl, position, box, radius, props, oldTexture) {
    return webgl.isWebGL2 ?
        GaussianDensityTexture3d(webgl, position, box, radius, props, oldTexture) :
        GaussianDensityTexture2d(webgl, position, box, radius, props, oldTexture);
}
function GaussianDensityTexture2d(webgl, position, box, radius, props, oldTexture) {
    return finalizeGaussianDensityTexture(calcGaussianDensityTexture2d(webgl, position, box, radius, props, oldTexture));
}
function GaussianDensityTexture3d(webgl, position, box, radius, props, oldTexture) {
    return finalizeGaussianDensityTexture(calcGaussianDensityTexture3d(webgl, position, box, radius, props, oldTexture));
}
function finalizeGaussianDensityTexture(_a) {
    var texture = _a.texture, scale = _a.scale, bbox = _a.bbox, gridDim = _a.gridDim, gridTexDim = _a.gridTexDim, gridTexScale = _a.gridTexScale;
    return { transform: getTransform(scale, bbox), texture: texture, bbox: bbox, gridDim: gridDim, gridTexDim: gridTexDim, gridTexScale: gridTexScale };
}
function getTransform(scale, bbox) {
    var transform = linear_algebra["Mat4"].identity();
    linear_algebra["Mat4"].fromScaling(transform, scale);
    linear_algebra["Mat4"].setTranslation(transform, bbox.min);
    return transform;
}
function calcGaussianDensityTexture2d(webgl, position, box, radius, props, texture) {
    var smoothness = props.smoothness;
    var _a = prepareGaussianDensityData(position, box, radius, props), drawCount = _a.drawCount, positions = _a.positions, radii = _a.radii, groups = _a.groups, scale = _a.scale, expandedBox = _a.expandedBox, dim = _a.dim;
    var dx = dim[0], dy = dim[1], dz = dim[2];
    var _b = getTexture2dSize(dim), texDimX = _b.texDimX, texDimY = _b.texDimY, texCols = _b.texCols, powerOfTwoSize = _b.powerOfTwoSize;
    // console.log({ texDimX, texDimY, texCols, powerOfTwoSize, dim })
    var gridTexDim = linear_algebra["Vec3"].create(texDimX, texDimY, 0);
    var gridTexScale = linear_algebra["Vec2"].create(texDimX / powerOfTwoSize, texDimY / powerOfTwoSize);
    var minDistanceTexture = webgl.resources.texture('image-float32', 'rgba', 'float', 'nearest');
    minDistanceTexture.define(powerOfTwoSize, powerOfTwoSize);
    var renderable = getGaussianDensityRenderable(webgl, drawCount, positions, radii, groups, minDistanceTexture, expandedBox, dim, gridTexDim, gridTexScale, smoothness, props.resolution);
    //
    var gl = webgl.gl, resources = webgl.resources, state = webgl.state;
    var _c = renderable.values, uCurrentSlice = _c.uCurrentSlice, uCurrentX = _c.uCurrentX, uCurrentY = _c.uCurrentY;
    var framebuffer = resources.framebuffer();
    framebuffer.bind();
    setRenderingDefaults(webgl);
    if (!texture) {
        texture = resources.texture('image-float32', 'rgba', 'float', 'nearest');
        texture.define(powerOfTwoSize, powerOfTwoSize);
    }
    else if (texture.getWidth() !== powerOfTwoSize || texture.getHeight() !== powerOfTwoSize) {
        texture.define(powerOfTwoSize, powerOfTwoSize);
    }
    // console.log(renderable)
    function render(fbTex, clear) {
        state.currentRenderItemId = -1;
        fbTex.attachFramebuffer(framebuffer, 0);
        if (clear)
            gl.clear(gl.COLOR_BUFFER_BIT);
        var currCol = 0;
        var currY = 0;
        var currX = 0;
        for (var i = 0; i < dz; ++i) {
            if (currCol >= texCols) {
                currCol -= texCols;
                currY += dy;
                currX = 0;
                mol_util["e" /* ValueCell */].update(uCurrentY, currY);
            }
            // console.log({ i, currX, currY })
            mol_util["e" /* ValueCell */].update(uCurrentX, currX);
            mol_util["e" /* ValueCell */].update(uCurrentSlice, i);
            gl.viewport(currX, currY, dx, dy);
            renderable.render();
            ++currCol;
            currX += dx;
        }
        gl.finish();
    }
    setupDensityRendering(webgl, renderable);
    render(texture, true);
    setupMinDistanceRendering(webgl, renderable);
    render(minDistanceTexture, true);
    setupGroupIdRendering(webgl, renderable);
    render(texture, false);
    // printTexture(webgl, texture, 1)
    return { texture: texture, scale: scale, bbox: expandedBox, gridDim: dim, gridTexDim: gridTexDim, gridTexScale: gridTexScale };
}
function calcGaussianDensityTexture3d(webgl, position, box, radius, props, texture) {
    var gl = webgl.gl, resources = webgl.resources;
    var smoothness = props.smoothness;
    var _a = prepareGaussianDensityData(position, box, radius, props), drawCount = _a.drawCount, positions = _a.positions, radii = _a.radii, groups = _a.groups, scale = _a.scale, expandedBox = _a.expandedBox, dim = _a.dim;
    var dx = dim[0], dy = dim[1], dz = dim[2];
    var minDistanceTexture = resources.texture('volume-float32', 'rgba', 'float', 'nearest');
    minDistanceTexture.define(dx, dy, dz);
    var gridTexScale = linear_algebra["Vec2"].create(1, 1);
    var renderable = getGaussianDensityRenderable(webgl, drawCount, positions, radii, groups, minDistanceTexture, expandedBox, dim, dim, gridTexScale, smoothness, props.resolution);
    //
    var uCurrentSlice = renderable.values.uCurrentSlice;
    var framebuffer = resources.framebuffer();
    framebuffer.bind();
    setRenderingDefaults(webgl);
    gl.viewport(0, 0, dx, dy);
    if (!texture)
        texture = resources.texture('volume-float32', 'rgba', 'float', 'nearest');
    texture.define(dx, dy, dz);
    function render(fbTex) {
        for (var i = 0; i < dz; ++i) {
            mol_util["e" /* ValueCell */].update(uCurrentSlice, i);
            fbTex.attachFramebuffer(framebuffer, 0, i);
            renderable.render();
        }
    }
    setupMinDistanceRendering(webgl, renderable);
    render(minDistanceTexture);
    setupDensityRendering(webgl, renderable);
    render(texture);
    setupGroupIdRendering(webgl, renderable);
    render(texture);
    return { texture: texture, scale: scale, bbox: expandedBox, gridDim: dim, gridTexDim: dim, gridTexScale: gridTexScale };
}
//
function prepareGaussianDensityData(position, box, radius, props) {
    var resolution = props.resolution, radiusOffset = props.radiusOffset;
    var scaleFactor = 1 / resolution;
    var indices = position.indices, x = position.x, y = position.y, z = position.z, id = position.id;
    var n = mol_data_int["OrderedSet"].size(indices);
    var positions = new Float32Array(n * 3);
    var radii = new Float32Array(n);
    var groups = new Float32Array(n);
    var maxRadius = 0;
    for (var i = 0; i < n; ++i) {
        var j = mol_data_int["OrderedSet"].getAt(indices, i);
        positions[i * 3] = x[j];
        positions[i * 3 + 1] = y[j];
        positions[i * 3 + 2] = z[j];
        var r = radius(j) + radiusOffset;
        if (maxRadius < r)
            maxRadius = r;
        radii[i] = r;
        groups[i] = id ? id[i] : i;
    }
    var pad = maxRadius * 2 + resolution * 4;
    var expandedBox = geometry["b" /* Box3D */].expand(Object(geometry["b" /* Box3D */])(), box, linear_algebra["Vec3"].create(pad, pad, pad));
    var scaledBox = geometry["b" /* Box3D */].scale(Object(geometry["b" /* Box3D */])(), expandedBox, scaleFactor);
    var dim = geometry["b" /* Box3D */].size(Object(linear_algebra["Vec3"])(), scaledBox);
    linear_algebra["Vec3"].ceil(dim, dim);
    var scale = linear_algebra["Vec3"].create(resolution, resolution, resolution);
    return { drawCount: n, positions: positions, radii: radii, groups: groups, scale: scale, expandedBox: expandedBox, dim: dim };
}
function getGaussianDensityRenderable(webgl, drawCount, positions, radii, groups, minDistanceTexture, box, gridDim, gridTexDim, gridTexScale, smoothness, resolution) {
    var extent = linear_algebra["Vec3"].sub(linear_algebra["Vec3"].zero(), box.max, box.min);
    var values = {
        drawCount: mol_util["e" /* ValueCell */].create(drawCount),
        instanceCount: mol_util["e" /* ValueCell */].create(1),
        aRadius: mol_util["e" /* ValueCell */].create(radii),
        aPosition: mol_util["e" /* ValueCell */].create(positions),
        aGroup: mol_util["e" /* ValueCell */].create(groups),
        uCurrentSlice: mol_util["e" /* ValueCell */].create(0),
        uCurrentX: mol_util["e" /* ValueCell */].create(0),
        uCurrentY: mol_util["e" /* ValueCell */].create(0),
        uBboxMin: mol_util["e" /* ValueCell */].create(box.min),
        uBboxSize: mol_util["e" /* ValueCell */].create(extent),
        uGridDim: mol_util["e" /* ValueCell */].create(gridDim),
        uGridTexDim: mol_util["e" /* ValueCell */].create(gridTexDim),
        uGridTexScale: mol_util["e" /* ValueCell */].create(gridTexScale),
        uAlpha: mol_util["e" /* ValueCell */].create(smoothness),
        uResolution: mol_util["e" /* ValueCell */].create(resolution),
        tMinDistanceTex: mol_util["e" /* ValueCell */].create(minDistanceTexture),
        dGridTexType: mol_util["e" /* ValueCell */].create(minDistanceTexture.getDepth() > 0 ? '3d' : '2d'),
        dCalcType: mol_util["e" /* ValueCell */].create('minDistance'),
    };
    var schema = Object(tslib_es6["__assign"])({}, GaussianDensitySchema);
    var shaderCode = GaussianDensityShaderCode;
    var renderItem = Object(render_item["a" /* createComputeRenderItem */])(webgl, 'points', shaderCode, schema, values);
    return Object(mol_gl_renderable["a" /* createComputeRenderable */])(renderItem, values);
}
function setRenderingDefaults(ctx) {
    var gl = ctx.gl, state = ctx.state;
    state.disable(gl.CULL_FACE);
    state.enable(gl.BLEND);
    state.disable(gl.DEPTH_TEST);
    state.disable(gl.SCISSOR_TEST);
    state.depthMask(false);
    state.clearColor(0, 0, 0, 0);
}
function setupMinDistanceRendering(webgl, renderable) {
    var gl = webgl.gl, state = webgl.state;
    mol_util["e" /* ValueCell */].update(renderable.values.dCalcType, 'minDistance');
    renderable.update();
    state.colorMask(false, false, false, true);
    state.blendFunc(gl.ONE, gl.ONE);
    // the shader writes 1 - dist so we set blending to MAX
    if (!webgl.extensions.blendMinMax) {
        throw new Error('GPU gaussian surface calculation requires EXT_blend_minmax');
    }
    state.blendEquation(webgl.extensions.blendMinMax.MAX);
}
function setupDensityRendering(webgl, renderable) {
    var gl = webgl.gl, state = webgl.state;
    mol_util["e" /* ValueCell */].update(renderable.values.dCalcType, 'density');
    renderable.update();
    state.colorMask(false, false, false, true);
    state.blendFunc(gl.ONE, gl.ONE);
    // state.colorMask(true, true, true, true)
    // state.blendFuncSeparate(gl.ONE, gl.ZERO, gl.ONE, gl.ONE)
    state.blendEquation(gl.FUNC_ADD);
}
function setupGroupIdRendering(webgl, renderable) {
    var gl = webgl.gl, state = webgl.state;
    mol_util["e" /* ValueCell */].update(renderable.values.dCalcType, 'groupId');
    renderable.update();
    // overwrite color, don't change alpha
    state.colorMask(true, true, true, false);
    state.blendFunc(gl.ONE, gl.ZERO);
    state.blendEquation(gl.FUNC_ADD);
}
function getTexture2dSize(gridDim) {
    var area = gridDim[0] * gridDim[1] * gridDim[2];
    var squareDim = Math.sqrt(area);
    var powerOfTwoSize = Math.pow(2, Math.ceil(Math.log(squareDim) / Math.log(2)));
    var texDimX = 0;
    var texDimY = gridDim[1];
    var texRows = 1;
    var texCols = gridDim[2];
    if (powerOfTwoSize < gridDim[0] * gridDim[2]) {
        texCols = Math.floor(powerOfTwoSize / gridDim[0]);
        texRows = Math.ceil(gridDim[2] / texCols);
        texDimX = texCols * gridDim[0];
        texDimY *= texRows;
    }
    else {
        texDimX = gridDim[0] * gridDim[2];
    }
    return { texDimX: texDimX, texDimY: texDimY, texRows: texRows, texCols: texCols, powerOfTwoSize: texDimY < powerOfTwoSize ? powerOfTwoSize : powerOfTwoSize * 2 };
}
function fieldFromTexture2d(ctx, texture, dim, texDim) {
    // console.time('fieldFromTexture2d')
    var resources = ctx.resources;
    var dx = dim[0], dy = dim[1], dz = dim[2];
    // const { width, height } = texture
    var width = texDim[0], height = texDim[1];
    var fboTexCols = Math.floor(width / dx);
    var space = linear_algebra["Tensor"].Space(dim, [2, 1, 0], Float32Array);
    var data = space.create();
    var field = linear_algebra["Tensor"].create(space, data);
    var idData = space.create();
    var idField = linear_algebra["Tensor"].create(space, idData);
    // const image = new Uint8Array(width * height * 4)
    var image = new Float32Array(width * height * 4);
    var framebuffer = resources.framebuffer();
    framebuffer.bind();
    texture.attachFramebuffer(framebuffer, 0);
    ctx.readPixels(0, 0, width, height, image);
    // printImageData(createImageData(image, width, height), 1/3)
    var j = 0;
    var tmpCol = 0;
    var tmpRow = 0;
    for (var iz = 0; iz < dz; ++iz) {
        if (tmpCol >= fboTexCols) {
            tmpCol = 0;
            tmpRow += dy;
        }
        for (var iy = 0; iy < dy; ++iy) {
            for (var ix = 0; ix < dx; ++ix) {
                var idx = 4 * (tmpCol * dx + (iy + tmpRow) * width + ix);
                data[j] = image[idx + 3]; // / 255
                idData[j] = Object(float_packing["b" /* decodeFloatRGB */])(image[idx] * 255, image[idx + 1] * 255, image[idx + 2] * 255);
                j++;
            }
        }
        tmpCol++;
    }
    // console.timeEnd('fieldFromTexture2d')
    return { field: field, idField: idField };
}
//# sourceMappingURL=gpu.js.map

/***/ }),
/* 248 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return hostReportError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function hostReportError(err) {
    setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map


/***/ }),
/* 249 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Grid; });
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var Grid;
(function (Grid) {
    Grid.One = {
        transform: { kind: 'matrix', matrix: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].identity() },
        cells: _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].Space([1, 1, 1], [0, 1, 2]), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].Data1([0])),
        stats: { min: 0, max: 0, mean: 0, sigma: 0 },
    };
    var _scale = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].zero(), _translate = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].zero();
    function getGridToCartesianTransform(grid) {
        if (grid.transform.kind === 'matrix') {
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].copy(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])(), grid.transform.matrix);
        }
        if (grid.transform.kind === 'spacegroup') {
            var space = grid.cells.space;
            var scale = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].fromScaling(_scale, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].div(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].zero(), _mol_math_geometry__WEBPACK_IMPORTED_MODULE_0__[/* Box3D */ "b"].size(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].zero(), grid.transform.fractionalBox), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].ofArray(space.dimensions)));
            var translate = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].fromTranslation(_translate, grid.transform.fractionalBox.min);
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mul3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].zero(), grid.transform.cell.fromFractional, translate, scale);
        }
        return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].identity();
    }
    Grid.getGridToCartesianTransform = getGridToCartesianTransform;
    function areEquivalent(gridA, gridB) {
        return gridA === gridB;
    }
    Grid.areEquivalent = areEquivalent;
    function isEmpty(grid) {
        return grid.cells.data.length === 0;
    }
    Grid.isEmpty = isEmpty;
})(Grid || (Grid = {}));

//# sourceMappingURL=grid.js.map

/***/ }),
/* 250 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Encoding; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * From CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var VERSION = '0.3.0';
var Encoding;
(function (Encoding) {
    function getDataType(data) {
        var srcType;
        if (data instanceof Int8Array)
            srcType = 1 /* Int8 */;
        else if (data instanceof Int16Array)
            srcType = 2 /* Int16 */;
        else if (data instanceof Int32Array)
            srcType = 3 /* Int32 */;
        else if (data instanceof Uint8Array)
            srcType = 4 /* Uint8 */;
        else if (data instanceof Uint16Array)
            srcType = 5 /* Uint16 */;
        else if (data instanceof Uint32Array)
            srcType = 6 /* Uint32 */;
        else if (data instanceof Float32Array)
            srcType = 32 /* Float32 */;
        else if (data instanceof Float64Array)
            srcType = 33 /* Float64 */;
        else
            srcType = 3 /* Int32 */; // throw new Error('Unsupported integer data type.');
        return srcType;
    }
    Encoding.getDataType = getDataType;
    function isSignedIntegerDataType(data) {
        if (data instanceof Int8Array || data instanceof Int16Array || data instanceof Int32Array)
            return true;
        for (var i = 0, _i = data.length; i < _i; i++) {
            if (i < 0)
                return false;
        }
        return true;
    }
    Encoding.isSignedIntegerDataType = isSignedIntegerDataType;
})(Encoding || (Encoding = {}));
//# sourceMappingURL=encoding.js.map

/***/ }),
/* 251 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _atom_site; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return residueIdFields; });
/* unused harmony export chainIdFields */
/* unused harmony export entityIdFields */
/* unused harmony export atomIdFields */
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(62);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(27);
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var CifField = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].Field;
var E = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].Encodings;
var _label_asym_id = _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_asym_id;
function atom_site_label_asym_id(e) {
    var l = _label_asym_id(e);
    var suffix = e.unit.conformation.operator.suffix;
    if (!suffix)
        return l;
    return l + suffix;
}
var _auth_asym_id = _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.auth_asym_id;
function atom_site_auth_asym_id(e) {
    var l = _auth_asym_id(e);
    var suffix = e.unit.conformation.operator.suffix;
    if (!suffix)
        return l;
    return l + suffix;
}
var atom_site_fields = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].fields()
    .str('group_PDB', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.group_PDB)
    .index('id')
    .str('type_symbol', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.type_symbol)
    .str('label_atom_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_atom_id)
    .str('label_comp_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_comp_id)
    .int('label_seq_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.label_seq_id, {
    encoder: E.deltaRLE,
    valueKind: function (k, d) {
        var m = k.unit.model;
        return m.atomicHierarchy.residues.label_seq_id.valueKind(m.atomicHierarchy.residueAtomSegments.index[k.element]);
    }
})
    .str('label_alt_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_alt_id)
    .str('pdbx_PDB_ins_code', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.pdbx_PDB_ins_code)
    .str('label_asym_id', atom_site_label_asym_id)
    .str('label_entity_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_entity_id)
    .float('Cartn_x', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.x, { digitCount: 3, encoder: E.fixedPoint3 })
    .float('Cartn_y', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.y, { digitCount: 3, encoder: E.fixedPoint3 })
    .float('Cartn_z', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.z, { digitCount: 3, encoder: E.fixedPoint3 })
    .float('occupancy', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.occupancy, { digitCount: 2, encoder: E.fixedPoint2 })
    .int('pdbx_formal_charge', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.pdbx_formal_charge, {
    encoder: E.deltaRLE,
    valueKind: function (k, d) { return k.unit.model.atomicHierarchy.atoms.pdbx_formal_charge.valueKind(k.element); }
})
    .str('auth_atom_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.auth_atom_id)
    .str('auth_comp_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.auth_comp_id)
    .int('auth_seq_id', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.auth_seq_id, { encoder: E.deltaRLE })
    .str('auth_asym_id', atom_site_auth_asym_id)
    .int('pdbx_PDB_model_num', _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].unit.model_num, { encoder: E.deltaRLE })
    // .str('operator_name', P.unit.operator_name, {
    //     shouldInclude: structure => structure.units.some(u => !u.conformation.operator.isIdentity)
    // })
    .getFields();
var _atom_site = {
    name: 'atom_site',
    instance: function (_a) {
        var structures = _a.structures;
        return {
            fields: atom_site_fields,
            source: structures.map(function (s) { return ({
                data: s,
                rowCount: s.elementCount,
                keys: function () { return s.elementLocations(); }
            }); })
        };
    }
};
function prepostfixed(prefix, postfix, name) {
    if (prefix && postfix)
        return prefix + "_" + name + "_" + postfix;
    if (prefix)
        return prefix + "_" + name;
    if (postfix)
        return name + "_" + postfix;
    return name;
}
function mappedProp(loc, prop) {
    return function (k, d) { return prop(loc(k, d)); };
}
function addModelNum(fields, getLocation, options) {
    if (options && options.includeModelNum) {
        fields.int('pdbx_PDB_model_num', mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].unit.model_num));
    }
}
function residueIdFields(getLocation, options) {
    var prefix = options && options.prefix, postfix = options && options.postfix;
    var ret = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].fields()
        .str(prepostfixed(prefix, postfix, "label_comp_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_comp_id))
        .int(prepostfixed(prefix, postfix, "label_seq_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.label_seq_id), {
        encoder: E.deltaRLE,
        valueKind: function (k, d) {
            var e = getLocation(k, d);
            var m = e.unit.model;
            return m.atomicHierarchy.residues.label_seq_id.valueKind(m.atomicHierarchy.residueAtomSegments.index[e.element]);
        }
    })
        .str(prepostfixed(prefix, postfix, "pdbx_PDB_ins_code"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.pdbx_PDB_ins_code))
        .str(prepostfixed(prefix, postfix, "label_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_asym_id))
        .str(prepostfixed(prefix, postfix, "label_entity_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_entity_id))
        .str(prepostfixed(prefix, postfix, "auth_comp_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.auth_comp_id))
        .int(prepostfixed(prefix, postfix, "auth_seq_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.auth_seq_id), { encoder: E.deltaRLE })
        .str(prepostfixed(prefix, postfix, "auth_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.auth_asym_id));
    addModelNum(ret, getLocation, options);
    return ret.getFields();
}
function chainIdFields(getLocation, options) {
    var prefix = options && options.prefix, postfix = options && options.postfix;
    var ret = CifField.build()
        .str(prepostfixed(prefix, postfix, "label_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_asym_id))
        .str(prepostfixed(prefix, postfix, "label_entity_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_entity_id))
        .str(prepostfixed(prefix, postfix, "auth_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.auth_asym_id));
    addModelNum(ret, getLocation, options);
    return ret.getFields();
}
function entityIdFields(getLocation, options) {
    var prefix = options && options.prefix, postfix = options && options.postfix;
    var ret = CifField.build()
        .str(prepostfixed(prefix, postfix, "label_entity_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_entity_id));
    addModelNum(ret, getLocation, options);
    return ret.getFields();
}
function atomIdFields(getLocation, options) {
    var prefix = options && options.prefix, postfix = options && options.postfix;
    var ret = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_0__[/* CifWriter */ "a"].fields()
        .str(prepostfixed(prefix, postfix, "label_atom_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_atom_id))
        .str(prepostfixed(prefix, postfix, "label_comp_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_comp_id))
        .int(prepostfixed(prefix, postfix, "label_seq_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.label_seq_id), {
        encoder: E.deltaRLE,
        valueKind: function (k, d) {
            var e = getLocation(k, d);
            var m = e.unit.model;
            return m.atomicHierarchy.residues.label_seq_id.valueKind(m.atomicHierarchy.residueAtomSegments.index[e.element]);
        }
    })
        .str(prepostfixed(prefix, postfix, "label_alt_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.label_alt_id))
        .str(prepostfixed(prefix, postfix, "pdbx_PDB_ins_code"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.pdbx_PDB_ins_code))
        .str(prepostfixed(prefix, postfix, "label_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_asym_id))
        .str(prepostfixed(prefix, postfix, "label_entity_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.label_entity_id))
        .str(prepostfixed(prefix, postfix, "auth_atom_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.auth_atom_id))
        .str(prepostfixed(prefix, postfix, "auth_comp_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].atom.auth_comp_id))
        .int(prepostfixed(prefix, postfix, "auth_seq_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].residue.auth_seq_id), { encoder: E.deltaRLE })
        .str(prepostfixed(prefix, postfix, "auth_asym_id"), mappedProp(getLocation, _structure__WEBPACK_IMPORTED_MODULE_1__[/* StructureProperties */ "e"].chain.auth_asym_id));
    addModelNum(ret, getLocation, options);
    return ret.getFields();
}
//# sourceMappingURL=atom_site.js.map

/***/ }),
/* 252 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return InteractionsIntraContacts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InteractionsInterContacts; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return interactionTypeLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return featureTypeLabel; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return featureGroupLabel; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_math_graph_inter_unit_graph__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(244);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var InteractionsIntraContacts;
(function (InteractionsIntraContacts) {
    /**
     * Note: assumes that feature members of a contact are non-overlapping
     */
    function createElementsIndex(contacts, features, elementsCount) {
        var offsets = new Int32Array(elementsCount + 1);
        var bucketFill = new Int32Array(elementsCount);
        var bucketSizes = new Int32Array(elementsCount);
        var members = features.members, featureOffsets = features.offsets;
        for (var i = 0, il = contacts.edgeCount * 2; i < il; ++i) {
            var aI = contacts.a[i];
            var bI = contacts.b[i];
            if (aI > bI)
                continue;
            for (var j = featureOffsets[aI], jl = featureOffsets[aI + 1]; j < jl; ++j) {
                ++bucketSizes[members[j]];
            }
            for (var j = featureOffsets[bI], jl = featureOffsets[bI + 1]; j < jl; ++j) {
                ++bucketSizes[members[j]];
            }
        }
        var offset = 0;
        for (var i = 0; i < elementsCount; i++) {
            offsets[i] = offset;
            offset += bucketSizes[i];
        }
        offsets[elementsCount] = offset;
        var indices = new Int32Array(offset);
        for (var i = 0, il = contacts.edgeCount * 2; i < il; ++i) {
            var aI = contacts.a[i];
            var bI = contacts.b[i];
            if (aI > bI)
                continue;
            for (var j = featureOffsets[aI], jl = featureOffsets[aI + 1]; j < jl; ++j) {
                var m = members[j];
                var om = offsets[m] + bucketFill[m];
                indices[om] = i;
                ++bucketFill[m];
            }
            for (var j = featureOffsets[bI], jl = featureOffsets[bI + 1]; j < jl; ++j) {
                var m = members[j];
                var om = offsets[m] + bucketFill[m];
                indices[om] = i;
                ++bucketFill[m];
            }
        }
        return { indices: indices, offsets: offsets };
    }
    InteractionsIntraContacts.createElementsIndex = createElementsIndex;
})(InteractionsIntraContacts || (InteractionsIntraContacts = {}));

var InteractionsInterContacts = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InteractionsInterContacts, _super);
    function InteractionsInterContacts(map, unitsFeatures) {
        var _this = _super.call(this, map) || this;
        var count = 0;
        var elementKeyIndex = new Map();
        var add = function (index, unit) {
            var vertexKey = _this.getElementKey(index, unit);
            var e = elementKeyIndex.get(vertexKey);
            if (e === undefined)
                elementKeyIndex.set(vertexKey, [count]);
            else
                e.push(count);
        };
        _this.map.forEach(function (pairEdgesArray) {
            pairEdgesArray.forEach(function (pairEdges) {
                pairEdges.connectedIndices.forEach(function (indexA) {
                    pairEdges.getEdges(indexA).forEach(function (edgeInfo) {
                        var unitA = pairEdges.unitA, unitB = pairEdges.unitB;
                        var _a = unitsFeatures.get(unitA.id), offsetsA = _a.offsets, membersA = _a.members;
                        for (var j = offsetsA[indexA], jl = offsetsA[indexA + 1]; j < jl; ++j) {
                            add(membersA[j], unitA);
                        }
                        var indexB = edgeInfo.indexB;
                        var _b = unitsFeatures.get(unitB.id), offsetsB = _b.offsets, membersB = _b.members;
                        for (var j = offsetsB[indexB], jl = offsetsB[indexB + 1]; j < jl; ++j) {
                            add(membersB[j], unitB);
                        }
                        count += 1;
                    });
                });
            });
        });
        _this.elementKeyIndex = elementKeyIndex;
        return _this;
    }
    InteractionsInterContacts.prototype.getContactIndicesForElement = function (index, unit) {
        return this.elementKeyIndex.get(this.getElementKey(index, unit)) || [];
    };
    InteractionsInterContacts.prototype.getElementKey = function (index, unit) {
        return index + "|" + unit.id;
    };
    return InteractionsInterContacts;
}(_mol_math_graph_inter_unit_graph__WEBPACK_IMPORTED_MODULE_1__[/* InterUnitGraph */ "a"]));
function interactionTypeLabel(type) {
    switch (type) {
        case 4 /* HydrogenBond */:
            return 'Hydrogen Bond';
        case 6 /* Hydrophobic */:
            return 'Hydrophobic Contact';
        case 5 /* HalogenBond */:
            return 'Halogen Bond';
        case 1 /* Ionic */:
            return 'Ionic Interaction';
        case 7 /* MetalCoordination */:
            return 'Metal Coordination';
        case 2 /* CationPi */:
            return 'Cation-Pi Interaction';
        case 3 /* PiStacking */:
            return 'Pi Stacking';
        case 8 /* WeakHydrogenBond */:
            return 'Weak Hydrogen Bond';
        case 0 /* Unknown */:
            return 'Unknown Interaction';
    }
}
function featureTypeLabel(type) {
    switch (type) {
        case 0 /* None */:
            return 'None';
        case 1 /* PositiveCharge */:
            return 'Positive Charge';
        case 2 /* NegativeCharge */:
            return 'Negative Charge';
        case 3 /* AromaticRing */:
            return 'Aromatic Ring';
        case 4 /* HydrogenDonor */:
            return 'Hydrogen Donor';
        case 5 /* HydrogenAcceptor */:
            return 'Hydrogen Acceptor';
        case 6 /* HalogenDonor */:
            return 'Halogen Donor';
        case 7 /* HalogenAcceptor */:
            return 'Halogen Acceptor';
        case 8 /* HydrophobicAtom */:
            return 'HydrophobicAtom';
        case 9 /* WeakHydrogenDonor */:
            return 'Weak Hydrogen Donor';
        case 10 /* IonicTypePartner */:
            return 'Ionic Type Partner';
        case 11 /* DativeBondPartner */:
            return 'Dative Bond Partner';
        case 12 /* TransitionMetal */:
            return 'Transition Metal';
        case 13 /* IonicTypeMetal */:
            return 'Ionic Type Metal';
    }
}
function featureGroupLabel(group) {
    switch (group) {
        case 0 /* None */:
            return 'None';
        case 1 /* QuaternaryAmine */:
            return 'Quaternary Amine';
        case 2 /* TertiaryAmine */:
            return 'Tertiary Amine';
        case 3 /* Sulfonium */:
            return 'Sulfonium';
        case 4 /* SulfonicAcid */:
            return 'Sulfonic Acid';
        case 5 /* Sulfate */:
            return 'Sulfate';
        case 6 /* Phosphate */:
            return 'Phosphate';
        case 7 /* Halocarbon */:
            return 'Halocarbon';
        case 8 /* Guanidine */:
            return 'Guanidine';
        case 9 /* Acetamidine */:
            return 'Acetamidine';
        case 10 /* Carboxylate */:
            return 'Carboxylate';
    }
}
//# sourceMappingURL=common.js.map

/***/ }),
/* 253 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return LogEntry; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var LogEntry;
(function (LogEntry) {
    function message(msg) { return { type: 'message', timestamp: new Date(), message: msg }; }
    LogEntry.message = message;
    function error(msg) { return { type: 'error', timestamp: new Date(), message: msg }; }
    LogEntry.error = error;
    function warning(msg) { return { type: 'warning', timestamp: new Date(), message: msg }; }
    LogEntry.warning = warning;
    function info(msg) { return { type: 'info', timestamp: new Date(), message: msg }; }
    LogEntry.info = info;
})(LogEntry || (LogEntry = {}));
//# sourceMappingURL=log-entry.js.map

/***/ }),
/* 254 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return of; });
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(122);
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(224);
/* harmony import */ var _scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(311);
/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */



function of() {
    var args = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        args[_i] = arguments[_i];
    }
    var scheduler = args[args.length - 1];
    if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_0__[/* isScheduler */ "a"])(scheduler)) {
        args.pop();
        return Object(_scheduled_scheduleArray__WEBPACK_IMPORTED_MODULE_2__[/* scheduleArray */ "a"])(args, scheduler);
    }
    else {
        return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__[/* fromArray */ "a"])(args);
    }
}
//# sourceMappingURL=of.js.map


/***/ }),
/* 255 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StructureHierarchyManager", function() { return /* binding */ hierarchy_StructureHierarchyManager; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/state.js
var static_state = __webpack_require__(216);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var mol_util_set = __webpack_require__(90);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/component.js
var component = __webpack_require__(118);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/behavior.js + 1 modules
var behavior = __webpack_require__(160);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/hierarchy-state.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function buildStructureHierarchy(state, previous) {
    var build = BuildState(state, previous || StructureHierarchy());
    doPreOrder(state.tree, build);
    if (previous)
        previous.refs.forEach(isRemoved, build);
    return { hierarchy: build.hierarchy, added: build.added, changed: build.changed };
}
function StructureHierarchy() {
    return { trajectories: [], models: [], structures: [], refs: new Map() };
}
function TrajectoryRef(cell) {
    return { kind: 'trajectory', cell: cell, version: cell.transform.version, models: [] };
}
function ModelRef(cell, trajectory) {
    return { kind: 'model', cell: cell, version: cell.transform.version, trajectory: trajectory, structures: [] };
}
function ModelPropertiesRef(cell, model) {
    return { kind: 'model-properties', cell: cell, version: cell.transform.version, model: model };
}
function ModelUnitcellRef(cell, model) {
    return { kind: 'model-unitcell', cell: cell, version: cell.transform.version, model: model };
}
function StructureRef(cell, model) {
    return { kind: 'structure', cell: cell, version: cell.transform.version, model: model, components: [] };
}
function StructurePropertiesRef(cell, structure) {
    return { kind: 'structure-properties', cell: cell, version: cell.transform.version, structure: structure };
}
function StructureTransformRef(cell, structure) {
    return { kind: 'structure-transform', cell: cell, version: cell.transform.version, structure: structure };
}
function StructureVolumeStreamingRef(cell, structure) {
    return { kind: 'structure-volume-streaming', cell: cell, version: cell.transform.version, structure: structure };
}
function componentKey(cell) {
    if (!cell.transform.tags)
        return cell.transform.ref;
    return Object(tslib_es6["__spreadArrays"])(cell.transform.tags).sort().join();
}
function StructureComponentRef(cell, structure) {
    return { kind: 'structure-component', cell: cell, version: cell.transform.version, structure: structure, key: componentKey(cell), representations: [] };
}
function StructureRepresentationRef(cell, component) {
    return { kind: 'structure-representation', cell: cell, version: cell.transform.version, component: component };
}
function GenericRepresentationRef(cell, parent) {
    return { kind: 'generic-representation', cell: cell, version: cell.transform.version, parent: parent };
}
function BuildState(state, oldHierarchy) {
    return { state: state, oldHierarchy: oldHierarchy, hierarchy: StructureHierarchy(), changed: false, added: new Set() };
}
function createOrUpdateRefList(state, cell, list, ctor) {
    var args = [];
    for (var _i = 4; _i < arguments.length; _i++) {
        args[_i - 4] = arguments[_i];
    }
    var ref = ctor.apply(void 0, args);
    list.push(ref);
    state.hierarchy.refs.set(cell.transform.ref, ref);
    var old = state.oldHierarchy.refs.get(cell.transform.ref);
    if (old) {
        if (old.version !== cell.transform.version)
            state.changed = true;
    }
    else {
        state.added.add(ref.cell.transform.ref);
        state.changed = true;
    }
    return ref;
}
function createOrUpdateRef(state, cell, ctor) {
    var args = [];
    for (var _i = 3; _i < arguments.length; _i++) {
        args[_i - 3] = arguments[_i];
    }
    var ref = ctor.apply(void 0, args);
    state.hierarchy.refs.set(cell.transform.ref, ref);
    var old = state.oldHierarchy.refs.get(cell.transform.ref);
    if (old) {
        if (old.version !== cell.transform.version)
            state.changed = true;
    }
    else {
        state.added.add(ref.cell.transform.ref);
        state.changed = true;
    }
    return ref;
}
function isType(t) {
    return function (cell) { return t.is(cell.obj); };
}
function isTypeRoot(t, target) {
    return function (cell, state) { return !target(state) && t.is(cell.obj); };
}
function isTransformer(t) {
    return function (cell) { return cell.transform.transformer === t; };
}
function noop() { }
var Mapping = [
    // Trajectory
    [isType(objects["a" /* PluginStateObject */].Molecule.Trajectory), function (state, cell) {
            state.currentTrajectory = createOrUpdateRefList(state, cell, state.hierarchy.trajectories, TrajectoryRef, cell);
        }, function (state) { return state.currentTrajectory = void 0; }],
    // Model
    [isTypeRoot(objects["a" /* PluginStateObject */].Molecule.Model, function (s) { return s.currentModel; }), function (state, cell) {
            if (state.currentTrajectory) {
                state.currentModel = createOrUpdateRefList(state, cell, state.currentTrajectory.models, ModelRef, cell, state.currentTrajectory);
            }
            else {
                state.currentModel = createOrUpdateRef(state, cell, ModelRef, cell);
            }
            state.hierarchy.models.push(state.currentModel);
        }, function (state) { return state.currentModel = void 0; }],
    [isTransformer(transforms["StateTransforms"].Model.CustomModelProperties), function (state, cell) {
            if (!state.currentModel)
                return false;
            state.currentModel.properties = createOrUpdateRef(state, cell, ModelPropertiesRef, cell, state.currentModel);
        }, noop],
    [isTransformer(transforms["StateTransforms"].Representation.ModelUnitcell3D), function (state, cell) {
            if (!state.currentModel)
                return false;
            state.currentModel.unitcell = createOrUpdateRef(state, cell, ModelUnitcellRef, cell, state.currentModel);
        }, noop],
    // Structure
    [isTypeRoot(objects["a" /* PluginStateObject */].Molecule.Structure, function (s) { return s.currentStructure; }), function (state, cell) {
            if (state.currentModel) {
                state.currentStructure = createOrUpdateRefList(state, cell, state.currentModel.structures, StructureRef, cell, state.currentModel);
            }
            else {
                state.currentStructure = createOrUpdateRef(state, cell, StructureRef, cell);
            }
            state.hierarchy.structures.push(state.currentStructure);
        }, function (state) { return state.currentStructure = void 0; }],
    [isTransformer(transforms["StateTransforms"].Model.CustomStructureProperties), function (state, cell) {
            if (!state.currentStructure)
                return false;
            state.currentStructure.properties = createOrUpdateRef(state, cell, StructurePropertiesRef, cell, state.currentStructure);
        }, noop],
    [isTransformer(transforms["StateTransforms"].Model.TransformStructureConformation), function (state, cell) {
            if (!state.currentStructure)
                return false;
            state.currentStructure.transform = createOrUpdateRef(state, cell, StructureTransformRef, cell, state.currentStructure);
        }, noop],
    // Volume Streaming
    [isType(behavior["a" /* VolumeStreaming */]), function (state, cell) {
            if (!state.currentStructure)
                return false;
            state.currentStructure.volumeStreaming = createOrUpdateRef(state, cell, StructureVolumeStreamingRef, cell, state.currentStructure);
            // Do not continue into VolumeStreaming subtree.
            return false;
        }, noop],
    // Component
    [function (cell, state) {
            if (state.currentComponent || !state.currentStructure || cell.transform.transformer.definition.isDecorator)
                return false;
            return objects["a" /* PluginStateObject */].Molecule.Structure.is(cell.obj);
        }, function (state, cell) {
            if (state.currentStructure) {
                state.currentComponent = createOrUpdateRefList(state, cell, state.currentStructure.components, StructureComponentRef, cell, state.currentStructure);
            }
        }, function (state) { return state.currentComponent = void 0; }],
    // Component Representation
    [function (cell, state) {
            return !cell.state.isGhost && !!state.currentComponent && objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D.is(cell.obj);
        }, function (state, cell) {
            if (state.currentComponent) {
                createOrUpdateRefList(state, cell, state.currentComponent.representations, StructureRepresentationRef, cell, state.currentComponent);
            }
            // Nothing useful down the line
            return false;
        }, noop],
    // Generic Representation
    [function (cell) { return !cell.state.isGhost && objects["a" /* PluginStateObject */].isRepresentation3D(cell.obj); }, function (state, cell) {
            var genericTarget = state.currentComponent || state.currentStructure || state.currentModel;
            if (genericTarget) {
                if (!genericTarget.genericRepresentations)
                    genericTarget.genericRepresentations = [];
                createOrUpdateRefList(state, cell, genericTarget.genericRepresentations, GenericRepresentationRef, cell, genericTarget);
            }
        }, noop],
];
function isValidCell(cell) {
    if (!cell || !(cell === null || cell === void 0 ? void 0 : cell.parent) || !cell.parent.cells.has(cell.transform.ref))
        return false;
    var obj = cell.obj;
    if (!obj || obj === mol_state["StateObject"].Null || (cell.status !== 'ok' && cell.status !== 'error'))
        return false;
    return true;
}
function isRemoved(ref) {
    var cell = ref.cell;
    if (isValidCell(cell))
        return;
    this.changed = true;
}
function _preOrderFunc(c) { _doPreOrder(this, this.tree.transforms.get(c)); }
function _doPreOrder(ctx, root) {
    var state = ctx.state;
    var cell = state.state.cells.get(root.ref);
    if (!isValidCell(cell))
        return;
    var onLeave = void 0;
    var end = false;
    for (var _i = 0, Mapping_1 = Mapping; _i < Mapping_1.length; _i++) {
        var _a = Mapping_1[_i], test_1 = _a[0], f = _a[1], l = _a[2];
        if (test_1(cell, state)) {
            var cont = f(state, cell);
            if (cont === false) {
                end = true;
                break;
            }
            onLeave = l;
            break;
        }
    }
    // TODO: might be needed in the future
    // const { currentComponent, currentModel, currentStructure, currentTrajectory } = ctx.state;
    // const inTrackedSubtree = currentComponent || currentModel || currentStructure || currentTrajectory;
    // if (inTrackedSubtree && cell.transform.transformer.definition.isDecorator) {
    //     const ref = cell.transform.ref;
    //     const old = ctx.state.oldHierarchy.decorators.get(ref);
    //     if (old && old.version !== cell.transform.version) {
    //         ctx.state.changed = true;
    //     }
    //     ctx.state.hierarchy.decorators.set(cell.transform.ref, cell.transform);
    // }
    if (end)
        return;
    var children = ctx.tree.children.get(root.ref);
    if (children && children.size) {
        children.forEach(_preOrderFunc, ctx);
    }
    if (onLeave)
        onLeave(state);
}
function doPreOrder(tree, state) {
    var ctx = { tree: tree, state: state };
    _doPreOrder(ctx, tree.root);
    return ctx.state;
}
//# sourceMappingURL=hierarchy-state.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/hierarchy.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var hierarchy_StructureHierarchyManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureHierarchyManager, _super);
    function StructureHierarchyManager(plugin) {
        var _this = _super.call(this) || this;
        _this.plugin = plugin;
        _this.state = {
            syncedTree: _this.dataState.tree,
            notified: false,
            hierarchy: StructureHierarchy(),
            selection: {
                trajectories: [],
                models: [],
                structures: []
            }
        };
        _this.behaviors = {
            selection: _this.ev.behavior({
                hierarchy: _this.current,
                trajectories: _this.selection.trajectories,
                models: _this.selection.models,
                structures: _this.selection.structures
            })
        };
        _this._currentComponentGroups = void 0;
        _this._currentSelectionSet = void 0;
        _this.subscribe(plugin.state.data.events.changed, function (e) {
            if (e.inTransaction || plugin.behaviors.state.isAnimating.value)
                return;
            _this.sync(true);
        });
        _this.subscribe(plugin.behaviors.state.isAnimating, function (isAnimating) {
            if (!isAnimating && !plugin.behaviors.state.isUpdating.value)
                _this.sync(true);
        });
        return _this;
    }
    Object.defineProperty(StructureHierarchyManager.prototype, "dataState", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureHierarchyManager.prototype, "currentComponentGroups", {
        get: function () {
            if (this._currentComponentGroups)
                return this._currentComponentGroups;
            this._currentComponentGroups = StructureHierarchyManager.getComponentGroups(this.selection.structures);
            return this._currentComponentGroups;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureHierarchyManager.prototype, "seletionSet", {
        get: function () {
            if (this._currentSelectionSet)
                return this._currentSelectionSet;
            this._currentSelectionSet = new Set();
            for (var _i = 0, _a = this.selection.trajectories; _i < _a.length; _i++) {
                var r = _a[_i];
                this._currentSelectionSet.add(r.cell.transform.ref);
            }
            for (var _b = 0, _c = this.selection.models; _b < _c.length; _b++) {
                var r = _c[_b];
                this._currentSelectionSet.add(r.cell.transform.ref);
            }
            for (var _d = 0, _e = this.selection.structures; _d < _e.length; _d++) {
                var r = _e[_d];
                this._currentSelectionSet.add(r.cell.transform.ref);
            }
            return this._currentSelectionSet;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureHierarchyManager.prototype, "current", {
        get: function () {
            this.sync(false);
            return this.state.hierarchy;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureHierarchyManager.prototype, "selection", {
        get: function () {
            this.sync(false);
            return this.state.selection;
        },
        enumerable: false,
        configurable: true
    });
    StructureHierarchyManager.prototype.getStructuresWithSelection = function () {
        var xs = this.plugin.managers.structure.hierarchy.current.structures;
        var ret = [];
        for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
            var s = xs_1[_i];
            if (this.plugin.managers.structure.selection.structureHasSelection(s)) {
                ret.push(s);
            }
        }
        return ret;
    };
    StructureHierarchyManager.prototype.syncCurrent = function (all, added) {
        var current = this.seletionSet;
        var newCurrent = [];
        for (var _i = 0, all_1 = all; _i < all_1.length; _i++) {
            var r = all_1[_i];
            var ref = r.cell.transform.ref;
            if (current.has(ref) || added.has(ref))
                newCurrent.push(r);
        }
        if (newCurrent.length === 0)
            return all.length > 0 ? [all[0]] : [];
        return newCurrent;
    };
    StructureHierarchyManager.prototype.sync = function (notify) {
        if (!notify && this.dataState.inUpdate)
            return;
        if (this.state.syncedTree === this.dataState.tree) {
            if (notify && !this.state.notified) {
                this.state.notified = true;
                this.behaviors.selection.next(Object(tslib_es6["__assign"])({ hierarchy: this.state.hierarchy }, this.state.selection));
            }
            return;
        }
        this.state.syncedTree = this.dataState.tree;
        var update = buildStructureHierarchy(this.plugin.state.data, this.current);
        if (!update.changed) {
            return;
        }
        var hierarchy = update.hierarchy;
        var trajectories = this.syncCurrent(hierarchy.trajectories, update.added);
        var models = this.syncCurrent(hierarchy.models, update.added);
        var structures = this.syncCurrent(hierarchy.structures, update.added);
        this._currentComponentGroups = void 0;
        this._currentSelectionSet = void 0;
        this.state.hierarchy = hierarchy;
        this.state.selection.trajectories = trajectories;
        this.state.selection.models = models;
        this.state.selection.structures = structures;
        if (notify) {
            this.state.notified = true;
            this.behaviors.selection.next({ hierarchy: hierarchy, trajectories: trajectories, models: models, structures: structures });
        }
        else {
            this.state.notified = false;
        }
    };
    StructureHierarchyManager.prototype.updateCurrent = function (refs, action) {
        var hierarchy = this.current;
        var set = action === 'add'
            ? mol_util_set["a" /* SetUtils */].union(this.seletionSet, new Set(refs.map(function (r) { return r.cell.transform.ref; })))
            : mol_util_set["a" /* SetUtils */].difference(this.seletionSet, new Set(refs.map(function (r) { return r.cell.transform.ref; })));
        var trajectories = [];
        var models = [];
        var structures = [];
        for (var _i = 0, _a = hierarchy.trajectories; _i < _a.length; _i++) {
            var t = _a[_i];
            if (set.has(t.cell.transform.ref))
                trajectories.push(t);
        }
        for (var _b = 0, _c = hierarchy.models; _b < _c.length; _b++) {
            var m = _c[_b];
            if (set.has(m.cell.transform.ref))
                models.push(m);
        }
        for (var _d = 0, _e = hierarchy.structures; _d < _e.length; _d++) {
            var s = _e[_d];
            if (set.has(s.cell.transform.ref))
                structures.push(s);
        }
        this._currentComponentGroups = void 0;
        this._currentSelectionSet = void 0;
        this.state.selection.trajectories = trajectories;
        this.state.selection.models = models;
        this.state.selection.structures = structures;
        this.behaviors.selection.next({ hierarchy: hierarchy, trajectories: trajectories, models: models, structures: structures });
    };
    StructureHierarchyManager.prototype.remove = function (refs, canUndo) {
        if (refs.length === 0)
            return;
        var deletes = this.plugin.state.data.build();
        for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
            var r = refs_1[_i];
            deletes.delete(typeof r === 'string' ? r : r.cell.transform.ref);
        }
        return deletes.commit({ canUndo: canUndo ? 'Remove' : false });
    };
    StructureHierarchyManager.prototype.toggleVisibility = function (refs, action) {
        if (refs.length === 0)
            return;
        var isHidden = action !== void 0
            ? (action === 'show' ? false : true)
            : !refs[0].cell.state.isHidden;
        for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) {
            var c = refs_2[_i];
            Object(static_state["setSubtreeVisibility"])(this.dataState, c.cell.transform.ref, isHidden);
        }
    };
    StructureHierarchyManager.prototype.applyPreset = function (trajectories, provider, params) {
        var _this = this;
        return this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, trajectories_1, t;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _i = 0, trajectories_1 = trajectories;
                        _a.label = 1;
                    case 1:
                        if (!(_i < trajectories_1.length)) return [3 /*break*/, 6];
                        t = trajectories_1[_i];
                        if (!(t.models.length > 0)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.clearTrajectory(t)];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [4 /*yield*/, this.plugin.builders.structure.hierarchy.applyPreset(t.cell, provider, params)];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5:
                        _i++;
                        return [3 /*break*/, 1];
                    case 6: return [2 /*return*/];
                }
            });
        }); });
    };
    StructureHierarchyManager.prototype.updateStructure = function (s, params) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.plugin.dataTransaction(function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
                            var root, children;
                            return Object(tslib_es6["__generator"])(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        root = mol_state["StateTree"].getDecoratorRoot(this.dataState.tree, s.cell.transform.ref);
                                        children = this.dataState.tree.children.get(root).toArray();
                                        return [4 /*yield*/, this.remove(children, false)];
                                    case 1:
                                        _a.sent();
                                        return [4 /*yield*/, this.plugin.state.updateTransform(this.plugin.state.data, s.cell.transform.ref, params, 'Structure Type')];
                                    case 2:
                                        _a.sent();
                                        return [4 /*yield*/, this.plugin.builders.structure.representation.applyPreset(s.cell.transform.ref, 'auto')];
                                    case 3:
                                        _a.sent();
                                        return [2 /*return*/];
                                }
                            });
                        }); }, { canUndo: 'Structure Type' })];
                    case 1:
                        _a.sent();
                        commands["PluginCommands"].Camera.Reset(this.plugin);
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureHierarchyManager.prototype.clearTrajectory = function (trajectory) {
        var builder = this.dataState.build();
        for (var _i = 0, _a = trajectory.models; _i < _a.length; _i++) {
            var m = _a[_i];
            builder.delete(m.cell);
        }
        return builder.commit();
    };
    return StructureHierarchyManager;
}(component["a" /* PluginComponent */]));

(function (StructureHierarchyManager) {
    function getComponentGroups(structures) {
        if (!structures.length)
            return [];
        if (structures.length === 1)
            return structures[0].components.map(function (c) { return [c]; });
        var groups = [];
        var map = new Map();
        for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
            var s = structures_1[_i];
            for (var _a = 0, _b = s.components; _a < _b.length; _a++) {
                var c = _b[_a];
                var key = c.key;
                if (!key)
                    continue;
                var component = map.get(key);
                if (!component) {
                    component = [];
                    map.set(key, component);
                    groups.push(component);
                }
                component.push(c);
            }
        }
        return groups;
    }
    StructureHierarchyManager.getComponentGroups = getComponentGroups;
    function getSelectedStructuresDescription(plugin) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j;
        var structures = plugin.managers.structure.hierarchy.selection.structures;
        if (structures.length === 0)
            return '';
        if (structures.length === 1) {
            var s = structures[0];
            var data = (_a = s.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
            if (!data)
                return ((_b = s.cell.obj) === null || _b === void 0 ? void 0 : _b.label) || 'Structure';
            var model = data.models[0] || data.representativeModel || data.masterModel;
            if (!model)
                return ((_c = s.cell.obj) === null || _c === void 0 ? void 0 : _c.label) || 'Structure';
            var entryId = model.entryId;
            if (((_e = (_d = s.model) === null || _d === void 0 ? void 0 : _d.trajectory) === null || _e === void 0 ? void 0 : _e.models) && s.model.trajectory.models.length === 1)
                return entryId;
            if (s.model)
                return ((_f = s.model.cell.obj) === null || _f === void 0 ? void 0 : _f.label) + " | " + entryId;
            return entryId;
        }
        var p = structures[0];
        var t = (_g = p === null || p === void 0 ? void 0 : p.model) === null || _g === void 0 ? void 0 : _g.trajectory;
        var sameTraj = true;
        for (var _i = 0, structures_2 = structures; _i < structures_2.length; _i++) {
            var s = structures_2[_i];
            if (((_h = s === null || s === void 0 ? void 0 : s.model) === null || _h === void 0 ? void 0 : _h.trajectory) !== t) {
                sameTraj = false;
                break;
            }
        }
        return sameTraj && t ? ((_j = t.cell.obj) === null || _j === void 0 ? void 0 : _j.label) + " | " + structures.length + " structures" : structures.length + " structures";
    }
    StructureHierarchyManager.getSelectedStructuresDescription = getSelectedStructuresDescription;
})(hierarchy_StructureHierarchyManager || (hierarchy_StructureHierarchyManager = {}));
//# sourceMappingURL=hierarchy.js.map

/***/ }),
/* 256 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Task; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _execution_observable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(289);
/* harmony import */ var _execution_synchronous__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(266);
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(96);
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var Task;
(function (Task) {
    var Impl = /** @class */ (function () {
        function Impl(name, f, onAbort) {
            this.name = name;
            this.f = f;
            this.onAbort = onAbort;
            this.id = getNextId();
        }
        Impl.prototype.run = function (observer, updateRateMs) {
            if (updateRateMs === void 0) { updateRateMs = 250; }
            if (observer)
                return Object(_execution_observable__WEBPACK_IMPORTED_MODULE_1__[/* ExecuteObservable */ "c"])(this, observer, updateRateMs);
            return this.f(_execution_synchronous__WEBPACK_IMPORTED_MODULE_2__[/* SyncRuntimeContext */ "a"]);
        };
        Impl.prototype.runAsChild = function (ctx, progress) {
            if (ctx.isSynchronous)
                return this.f(_execution_synchronous__WEBPACK_IMPORTED_MODULE_2__[/* SyncRuntimeContext */ "a"]);
            return Object(_execution_observable__WEBPACK_IMPORTED_MODULE_1__[/* ExecuteObservableChild */ "d"])(ctx, this, progress);
        };
        Impl.prototype.runInContext = function (ctx) {
            if (ctx.isSynchronous)
                return this.f(_execution_synchronous__WEBPACK_IMPORTED_MODULE_2__[/* SyncRuntimeContext */ "a"]);
            return Object(_execution_observable__WEBPACK_IMPORTED_MODULE_1__[/* ExecuteInContext */ "b"])(ctx, this);
        };
        return Impl;
    }());
    function is(t) {
        var _t = t;
        return !!t && typeof _t.id === 'number' && typeof _t.name === 'string' && !!_t.run;
    }
    Task.is = is;
    function isAbort(e) { return !!e && !!e.isAborted; }
    Task.isAbort = isAbort;
    function Aborted(reason) { return { isAborted: true, reason: reason, toString: function () { return "Aborted" + (reason ? ': ' + reason : ''); } }; }
    Task.Aborted = Aborted;
    function create(name, f, onAbort) {
        return new Impl(name, f, onAbort);
    }
    Task.create = create;
    function constant(name, value) {
        var _this = this;
        return create(name, function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            return [2 /*return*/, value];
        }); }); });
    }
    Task.constant = constant;
    function empty() {
        var _this = this;
        return create('', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            return [2 /*return*/];
        }); }); });
    }
    Task.empty = empty;
    function fail(name, reason) {
        var _this = this;
        return create(name, function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            throw new Error(reason);
        }); }); });
    }
    Task.fail = fail;
    var getNextId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_3__[/* idFactory */ "a"])(0, 0x3fffffff);
})(Task || (Task = {}));

//# sourceMappingURL=task.js.map

/***/ }),
/* 257 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Points; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(124);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(117);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(125);
/* harmony import */ var _size_data__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(146);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(2);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(53);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(11);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(142);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(9);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(143);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var Points;
(function (Points) {
    function create(centers, groups, pointCount, points) {
        return points ?
            update(centers, groups, pointCount, points) :
            fromArrays(centers, groups, pointCount);
    }
    Points.create = create;
    function createEmpty(points) {
        var cb = points ? points.centerBuffer.ref.value : new Float32Array(0);
        var gb = points ? points.groupBuffer.ref.value : new Float32Array(0);
        return create(cb, gb, 0, points);
    }
    Points.createEmpty = createEmpty;
    function hashCode(points) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_13__[/* hashFnv32a */ "l"])([
            points.pointCount, points.centerBuffer.ref.version, points.groupBuffer.ref.version,
        ]);
    }
    function fromArrays(centers, groups, pointCount) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"])();
        var groupMapping;
        var currentHash = -1;
        var currentGroup = -1;
        var points = {
            kind: 'points',
            pointCount: pointCount,
            centerBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(centers),
            groupBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(groups),
            get boundingSphere() {
                var newHash = hashCode(points);
                if (newHash !== currentHash) {
                    var b = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateInvariantBoundingSphere */ "a"])(points.centerBuffer.ref.value, points.pointCount, 1);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
            get groupMapping() {
                if (points.groupBuffer.ref.version !== currentGroup) {
                    groupMapping = Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* createGroupMapping */ "c"])(points.groupBuffer.ref.value, points.pointCount);
                    currentGroup = points.groupBuffer.ref.version;
                }
                return groupMapping;
            },
            setBoundingSphere: function (sphere) {
                _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].copy(boundingSphere, sphere);
                currentHash = hashCode(points);
            }
        };
        return points;
    }
    function update(centers, groups, pointCount, points) {
        points.pointCount = pointCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(points.centerBuffer, centers);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(points.groupBuffer, groups);
        return points;
    }
    function transform(points, t) {
        var c = points.centerBuffer.ref.value;
        Object(_util__WEBPACK_IMPORTED_MODULE_3__[/* transformPositionArray */ "e"])(t, c, 0, points.pointCount);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(points.centerBuffer, c);
    }
    Points.transform = transform;
    //
    Points.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].Params), { sizeFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), pointSizeAttenuation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].Boolean(false), pointFilledCircle: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].Boolean(false), pointEdgeBleach: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].Numeric(0.2, { min: 0, max: 1, step: 0.05 }) });
    Points.Utils = {
        Params: Points.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: createRenderableState,
        updateRenderableState: updateRenderableState
    };
    function createValues(points, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_4__[/* createColors */ "a"])(locationIt, theme.color);
        var size = Object(_size_data__WEBPACK_IMPORTED_MODULE_6__[/* createSizes */ "a"])(locationIt, theme.size);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_5__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_11__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_12__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_14__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: points.pointCount, groupCount: groupCount, instanceCount: instanceCount };
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].clone(points.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ aPosition: points.centerBuffer, aGroup: points.groupBuffer, boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].ofSphere(invariantBoundingSphere)) }, color), size), marker), overpaint), transparency), clipping), transform), _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createValues(props, counts)), { uSizeFactor: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.sizeFactor), dPointSizeAttenuation: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.pointSizeAttenuation), dPointFilledCircle: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.pointFilledCircle), uPointEdgeBleach: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.pointEdgeBleach) });
    }
    function createValuesSimple(points, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].getDefaultValues(Points.Params)), props);
        return createValues(points, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.uSizeFactor, props.sizeFactor);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dPointSizeAttenuation, props.pointSizeAttenuation);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dPointFilledCircle, props.pointFilledCircle);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.uPointEdgeBleach, props.pointEdgeBleach);
    }
    function updateBoundingSphere(values, points) {
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].clone(points.boundingSphere);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_8__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
    function createRenderableState(props) {
        var state = _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].createRenderableState(props);
        updateRenderableState(state, props);
        return state;
    }
    function updateRenderableState(state, props) {
        _base__WEBPACK_IMPORTED_MODULE_10__[/* BaseGeometry */ "a"].updateRenderableState(state, props);
        state.opaque = state.opaque && (!props.pointFilledCircle ||
            (props.pointFilledCircle && props.pointEdgeBleach === 0));
        state.writeDepth = state.opaque;
    }
})(Points || (Points = {}));
//# sourceMappingURL=points.js.map

/***/ }),
/* 258 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Spheres; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(117);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(125);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(53);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(11);
/* harmony import */ var _size_data__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(146);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(142);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(9);
/* harmony import */ var _util__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(124);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(143);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(1);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var Spheres;
(function (Spheres) {
    function create(centers, mappings, indices, groups, sphereCount, spheres) {
        return spheres ?
            update(centers, mappings, indices, groups, sphereCount, spheres) :
            fromArrays(centers, mappings, indices, groups, sphereCount);
    }
    Spheres.create = create;
    function createEmpty(spheres) {
        var cb = spheres ? spheres.centerBuffer.ref.value : new Float32Array(0);
        var mb = spheres ? spheres.mappingBuffer.ref.value : new Float32Array(0);
        var ib = spheres ? spheres.indexBuffer.ref.value : new Uint32Array(0);
        var gb = spheres ? spheres.groupBuffer.ref.value : new Float32Array(0);
        return create(cb, mb, ib, gb, 0, spheres);
    }
    Spheres.createEmpty = createEmpty;
    function hashCode(spheres) {
        return Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_11__[/* hashFnv32a */ "l"])([
            spheres.sphereCount,
            spheres.centerBuffer.ref.version, spheres.mappingBuffer.ref.version,
            spheres.indexBuffer.ref.version, spheres.groupBuffer.ref.version
        ]);
    }
    function fromArrays(centers, mappings, indices, groups, sphereCount) {
        var boundingSphere = Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"])();
        var groupMapping;
        var currentHash = -1;
        var currentGroup = -1;
        var spheres = {
            kind: 'spheres',
            sphereCount: sphereCount,
            centerBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(centers),
            mappingBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(mappings),
            indexBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(indices),
            groupBuffer: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(groups),
            get boundingSphere() {
                var newHash = hashCode(spheres);
                if (newHash !== currentHash) {
                    var b = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_5__[/* calculateInvariantBoundingSphere */ "a"])(spheres.centerBuffer.ref.value, spheres.sphereCount * 4, 4);
                    _mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
            get groupMapping() {
                if (spheres.groupBuffer.ref.version !== currentGroup) {
                    groupMapping = Object(_util__WEBPACK_IMPORTED_MODULE_12__[/* createGroupMapping */ "c"])(spheres.groupBuffer.ref.value, spheres.sphereCount, 4);
                    currentGroup = spheres.groupBuffer.ref.version;
                }
                return groupMapping;
            },
            setBoundingSphere: function (sphere) {
                _mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].copy(boundingSphere, sphere);
                currentHash = hashCode(spheres);
            }
        };
        return spheres;
    }
    function update(centers, mappings, indices, groups, sphereCount, spheres) {
        spheres.sphereCount = sphereCount;
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(spheres.centerBuffer, centers);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(spheres.mappingBuffer, mappings);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(spheres.indexBuffer, indices);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(spheres.groupBuffer, groups);
        return spheres;
    }
    Spheres.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].Params), { sizeFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), doubleSided: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].CustomQualityParamInfo), ignoreLight: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].ShadingCategory) });
    Spheres.Utils = {
        Params: Spheres.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].createRenderableState,
        updateRenderableState: _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].updateRenderableState
    };
    function createValues(spheres, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        if (instanceCount !== transform.instanceCount.ref.value) {
            throw new Error('instanceCount values in TransformData and LocationIterator differ');
        }
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_3__[/* createColors */ "a"])(locationIt, theme.color);
        var size = Object(_size_data__WEBPACK_IMPORTED_MODULE_7__[/* createSizes */ "a"])(locationIt, theme.size);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_4__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_9__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_10__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_13__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: spheres.sphereCount * 2 * 3, groupCount: groupCount, instanceCount: instanceCount };
        var padding = Object(_size_data__WEBPACK_IMPORTED_MODULE_7__[/* getMaxSize */ "b"])(size);
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].expand(Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"])(), spheres.boundingSphere, padding);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_5__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ aPosition: spheres.centerBuffer, aMapping: spheres.mappingBuffer, aGroup: spheres.groupBuffer, elements: spheres.indexBuffer, boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(boundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(invariantBoundingSphere), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_14__["Vec4"].ofSphere(invariantBoundingSphere)) }, color), size), marker), overpaint), transparency), clipping), transform), { padding: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(padding) }), _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].createValues(props, counts)), { uSizeFactor: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.sizeFactor), dDoubleSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.doubleSided), dIgnoreLight: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.ignoreLight) });
    }
    function createValuesSimple(spheres, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(Spheres.Params)), props);
        return createValues(spheres, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _base__WEBPACK_IMPORTED_MODULE_8__[/* BaseGeometry */ "a"].updateValues(values, props);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.uSizeFactor, props.sizeFactor);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dDoubleSided, props.doubleSided);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dIgnoreLight, props.ignoreLight);
    }
    function updateBoundingSphere(values, spheres) {
        var padding = Object(_size_data__WEBPACK_IMPORTED_MODULE_7__[/* getMaxSize */ "b"])(values);
        var invariantBoundingSphere = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].expand(Object(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"])(), spheres.boundingSphere, padding);
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_5__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_6__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_14__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.padding, padding);
    }
})(Spheres || (Spheres = {}));
//# sourceMappingURL=spheres.js.map

/***/ }),
/* 259 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TextureMesh; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _color_data__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(117);
/* harmony import */ var _marker_data__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(125);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(33);
/* harmony import */ var _overpaint_data__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(134);
/* harmony import */ var _transparency_data__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(142);
/* harmony import */ var _mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(53);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(1);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(29);
/* harmony import */ var _clipping_data__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(143);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var TextureMesh;
(function (TextureMesh) {
    function create(vertexCount, groupCount, vertexGroupTexture, normalTexture, boundingSphere, textureMesh) {
        var width = vertexGroupTexture.getWidth();
        var height = vertexGroupTexture.getHeight();
        if (textureMesh) {
            textureMesh.vertexCount = vertexCount;
            textureMesh.groupCount = groupCount;
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(textureMesh.geoTextureDim, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec2"].set(textureMesh.geoTextureDim.ref.value, width, height));
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(textureMesh.vertexGroupTexture, vertexGroupTexture);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(textureMesh.normalTexture, normalTexture);
            _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].copy(textureMesh.boundingSphere, boundingSphere);
            return textureMesh;
        }
        else {
            return {
                kind: 'texture-mesh',
                vertexCount: vertexCount,
                groupCount: groupCount,
                geoTextureDim: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec2"].create(width, height)),
                vertexGroupTexture: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(vertexGroupTexture),
                normalTexture: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(normalTexture),
                boundingSphere: _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].clone(boundingSphere),
            };
        }
    }
    TextureMesh.create = create;
    function createEmpty(textureMesh) {
        return {}; // TODO
    }
    TextureMesh.createEmpty = createEmpty;
    TextureMesh.Params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].Params), { doubleSided: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].CustomQualityParamInfo), flipSided: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].ShadingCategory), flatShaded: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].Boolean(false, _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].ShadingCategory) });
    TextureMesh.Utils = {
        Params: TextureMesh.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].createRenderableState,
        updateRenderableState: _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].updateRenderableState
    };
    function createValues(textureMesh, transform, locationIt, theme, props) {
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        var color = Object(_color_data__WEBPACK_IMPORTED_MODULE_4__[/* createColors */ "a"])(locationIt, theme.color);
        var marker = Object(_marker_data__WEBPACK_IMPORTED_MODULE_5__[/* createMarkers */ "a"])(instanceCount * groupCount);
        var overpaint = Object(_overpaint_data__WEBPACK_IMPORTED_MODULE_7__[/* createEmptyOverpaint */ "c"])();
        var transparency = Object(_transparency_data__WEBPACK_IMPORTED_MODULE_8__[/* createEmptyTransparency */ "c"])();
        var clipping = Object(_clipping_data__WEBPACK_IMPORTED_MODULE_12__[/* createEmptyClipping */ "d"])();
        var counts = { drawCount: textureMesh.vertexCount, groupCount: groupCount, instanceCount: instanceCount };
        var transformBoundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(textureMesh.boundingSphere, transform.aTransform.ref.value, transform.instanceCount.ref.value);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ uGeoTexDim: textureMesh.geoTextureDim, tPositionGroup: textureMesh.vertexGroupTexture, tNormal: textureMesh.normalTexture,
            // aGroup is used as a vertex index here and the group id is retirieved from tPositionGroup
            aGroup: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_11__["fillSerial"])(new Float32Array(textureMesh.vertexCount))), boundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(transformBoundingSphere), invariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].clone(textureMesh.boundingSphere)), uInvariantBoundingSphere: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec4"].ofSphere(textureMesh.boundingSphere)) }, color), marker), overpaint), transparency), clipping), transform), _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].createValues(props, counts)), { dDoubleSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.doubleSided), dFlatShaded: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.flatShaded), dFlipSided: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(props.flipSided), dGeoTexture: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].create(true) });
    }
    function createValuesSimple(textureMesh, props, colorValue, sizeValue, transform) {
        var s = _base__WEBPACK_IMPORTED_MODULE_6__[/* BaseGeometry */ "a"].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].getDefaultValues(TextureMesh.Params)), props);
        return createValues(textureMesh, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.alpha, props.alpha); // `uAlpha` is set in renderable.render
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dDoubleSided, props.doubleSided);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dFlatShaded, props.flatShaded);
        _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].updateIfChanged(values.dFlipSided, props.flipSided);
        if (values.drawCount.ref.value > values.aGroup.ref.value.length) {
            // console.log('updating vertex ids in aGroup to handle larger drawCount')
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.aGroup, Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_11__["fillSerial"])(new Float32Array(values.drawCount.ref.value)));
        }
    }
    function updateBoundingSphere(values, textureMesh) {
        var invariantBoundingSphere = textureMesh.boundingSphere;
        var boundingSphere = Object(_mol_gl_renderable_util__WEBPACK_IMPORTED_MODULE_9__[/* calculateTransformBoundingSphere */ "b"])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].equals(boundingSphere, values.boundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.boundingSphere, boundingSphere);
        }
        if (!_mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Sphere3D */ "g"].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.invariantBoundingSphere, invariantBoundingSphere);
            _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* ValueCell */ "e"].update(values.uInvariantBoundingSphere, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_10__["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
})(TextureMesh || (TextureMesh = {}));
//# sourceMappingURL=texture-mesh.js.map

/***/ }),
/* 260 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return classifyIntArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return classifyFloatArray; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _array_encoder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(107);
/* harmony import */ var _mol_util_number__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(174);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



function classifyIntArray(xs) {
    return IntClassifier.classify(xs);
}
function classifyFloatArray(xs) {
    return FloatClassifier.classify(xs);
}
var IntClassifier;
(function (IntClassifier) {
    function packSize(value, upperLimit) {
        return value >= 0
            ? Math.ceil((value + 1) / upperLimit)
            : Math.ceil((value + 1) / (-upperLimit - 1));
    }
    function getInfo(data) {
        var signed = false;
        for (var i = 0, n = data.length; i < n; i++) {
            if (data[i] < 0) {
                signed = true;
                break;
            }
        }
        return signed ? { signed: signed, limit8: 0x7F, limit16: 0x7FFF } : { signed: signed, limit8: 0xFF, limit16: 0xFFFF };
    }
    function SizeInfo() { return { pack8: 0, pack16: 0, count: 0 }; }
    ;
    function incSize(_a, info, value) {
        var limit8 = _a.limit8, limit16 = _a.limit16;
        info.pack8 += packSize(value, limit8);
        info.pack16 += packSize(value, limit16);
        info.count += 1;
    }
    function incSizeSigned(info, value) {
        info.pack8 += packSize(value, 0x7F);
        info.pack16 += packSize(value, 0x7FFF);
        info.count += 1;
    }
    function byteSize(info) {
        if (info.count * 4 < info.pack16 * 2)
            return { length: info.count * 4, elem: 4 };
        if (info.pack16 * 2 < info.pack8)
            return { length: info.pack16 * 2, elem: 2 };
        return { length: info.pack8, elem: 1 };
    }
    function packingSize(data, info) {
        var size = SizeInfo();
        for (var i = 0, n = data.length; i < n; i++) {
            incSize(info, size, data[i]);
        }
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, byteSize(size)), { kind: 'pack' });
    }
    function deltaSize(data, info) {
        var size = SizeInfo();
        var prev = data[0];
        for (var i = 1, n = data.length; i < n; i++) {
            incSizeSigned(size, data[i] - prev);
            prev = data[i];
        }
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, byteSize(size)), { kind: 'delta' });
    }
    function rleSize(data, info) {
        var size = SizeInfo();
        var run = 1;
        for (var i = 1, n = data.length; i < n; i++) {
            if (data[i - 1] !== data[i]) {
                incSize(info, size, data[i - 1]);
                incSize(info, size, run);
                run = 1;
            }
            else {
                run++;
            }
        }
        incSize(info, size, data[data.length - 1]);
        incSize(info, size, run);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, byteSize(size)), { kind: 'rle' });
    }
    function deltaRleSize(data, info) {
        var size = SizeInfo();
        var run = 1, prev = 0, prevValue = 0;
        for (var i = 1, n = data.length; i < n; i++) {
            var v = data[i] - prev;
            if (prevValue !== v) {
                incSizeSigned(size, prevValue);
                incSizeSigned(size, run);
                run = 1;
            }
            else {
                run++;
            }
            prevValue = v;
            prev = data[i];
        }
        incSizeSigned(size, prevValue);
        incSizeSigned(size, run);
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, byteSize(size)), { kind: 'delta-rle' });
    }
    function getSize(data) {
        var info = getInfo(data);
        var sizes = [packingSize(data, info), rleSize(data, info), deltaSize(data, info), deltaRleSize(data, info)];
        sizes.sort(function (a, b) { return a.length - b.length; });
        return sizes;
    }
    IntClassifier.getSize = getSize;
    function classify(data) {
        if (data.length < 2)
            return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].byteArray);
        var sizes = getSize(data);
        var size = sizes[0];
        switch (size.kind) {
            case 'pack': return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'rle': return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].runLength).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'delta': return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].delta).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'delta-rle': return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].delta).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].runLength).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
        }
        throw new Error('should not happen :)');
    }
    IntClassifier.classify = classify;
})(IntClassifier || (IntClassifier = {}));
var FloatClassifier;
(function (FloatClassifier) {
    var delta = 1e-6;
    function classify(data) {
        var maxDigits = 4;
        var _a = Object(_mol_util_number__WEBPACK_IMPORTED_MODULE_2__[/* getArrayDigitCount */ "a"])(data, maxDigits, delta), mantissaDigits = _a.mantissaDigits, integerDigits = _a.integerDigits;
        // TODO: better check for overflows here?
        if (mantissaDigits < 0 || mantissaDigits + integerDigits > 10)
            return _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].byteArray);
        // TODO: this needs a conversion to Int?Array?
        if (mantissaDigits === 0)
            return IntClassifier.classify(data);
        var multiplier = getMultiplier(mantissaDigits);
        var intArray = new Int32Array(data.length);
        for (var i = 0, n = data.length; i < n; i++) {
            intArray[i] = Math.round(multiplier * data[i]);
            // TODO: enable this again?
            // const v = Math.round(multiplier * data[i]);
            // if (Math.abs(Math.round(v) / multiplier - intArray[i] / multiplier) > delta) {
            //     return E.by(E.byteArray);
            // }
        }
        var sizes = IntClassifier.getSize(intArray);
        var size = sizes[0];
        var fp = _array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].by(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].fixedPoint(multiplier));
        switch (size.kind) {
            case 'pack': return fp.and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'rle': return fp.and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].runLength).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'delta': return fp.and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].delta).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
            case 'delta-rle': return fp.and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].delta).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].runLength).and(_array_encoder__WEBPACK_IMPORTED_MODULE_1__[/* ArrayEncoding */ "b"].integerPacking);
        }
        throw new Error('should not happen :)');
    }
    FloatClassifier.classify = classify;
    function getMultiplier(mantissaDigits) {
        var m = 1;
        for (var i = 0; i < mantissaDigits; i++)
            m *= 10;
        return m;
    }
})(FloatClassifier || (FloatClassifier = {}));
//# sourceMappingURL=classifier.js.map

/***/ }),
/* 261 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return checkFramebufferStatus; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createFramebuffer; });
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96);
/* harmony import */ var _compat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(91);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var getNextFramebufferId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_0__[/* idFactory */ "a"])();
function getFramebufferStatusDescription(gl, status) {
    switch (status) {
        case gl.FRAMEBUFFER_COMPLETE: return 'complete';
        case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: return 'incomplete attachment';
        case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: return 'incomplete missing attachment';
        case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: return 'incomplete dimensions';
        case gl.FRAMEBUFFER_UNSUPPORTED: return 'unsupported';
    }
    if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl)) {
        switch (status) {
            case gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE: return 'incomplete multisample';
            case gl.RENDERBUFFER_SAMPLES: return 'renderbuffer samples';
        }
    }
    return 'unknown error';
}
function checkFramebufferStatus(gl) {
    var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
    if (status !== gl.FRAMEBUFFER_COMPLETE) {
        var description = getFramebufferStatusDescription(gl, status);
        throw new Error("Framebuffer status: " + description);
    }
}
function getFramebuffer(gl) {
    var framebuffer = gl.createFramebuffer();
    if (framebuffer === null) {
        throw new Error('Could not create WebGL framebuffer');
    }
    return framebuffer;
}
function createFramebuffer(gl) {
    var _framebuffer = getFramebuffer(gl);
    var destroyed = false;
    return {
        id: getNextFramebufferId(),
        bind: function () { return gl.bindFramebuffer(gl.FRAMEBUFFER, _framebuffer); },
        reset: function () {
            _framebuffer = getFramebuffer(gl);
        },
        destroy: function () {
            if (destroyed)
                return;
            gl.deleteFramebuffer(_framebuffer);
            destroyed = true;
        }
    };
}
//# sourceMappingURL=framebuffer.js.map

/***/ }),
/* 262 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export urlQueryParameter */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return urlCombine; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function urlQueryParameter(id) {
    if (typeof window === 'undefined')
        return undefined;
    var a = new RegExp(id + "=([^&#=]*)");
    var m = a.exec(window.location.search);
    return m ? decodeURIComponent(m[1]) : undefined;
}
function urlCombine(base, query) {
    return "" + base + (base[base.length - 1] === '/' || query[0] === '/' ? '' : '/') + query;
}
//# sourceMappingURL=url.js.map

/***/ }),
/* 263 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/render-object.js + 8 modules
var render_object = __webpack_require__(115);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/object3d.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var object3d_Object3D;
(function (Object3D) {
    function create() {
        return {
            view: linear_algebra["Mat4"].identity(),
            position: linear_algebra["Vec3"].create(0, 0, 0),
            direction: linear_algebra["Vec3"].create(0, 0, -1),
            up: linear_algebra["Vec3"].create(0, 1, 0),
        };
    }
    Object3D.create = create;
    var center = linear_algebra["Vec3"].zero();
    function update(object3d) {
        linear_algebra["Vec3"].add(center, object3d.position, object3d.direction);
        linear_algebra["Mat4"].lookAt(object3d.view, object3d.position, center, object3d.up);
    }
    Object3D.update = update;
})(object3d_Object3D || (object3d_Object3D = {}));
//# sourceMappingURL=object3d.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/generic.js + 3 modules
var generic = __webpack_require__(55);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/commit-queue.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var commit_queue_CommitQueue = /** @class */ (function () {
    function CommitQueue() {
        this.removeList = Object(generic["b" /* LinkedList */])();
        this.removeMap = new Map();
        this.addList = Object(generic["b" /* LinkedList */])();
        this.addMap = new Map();
    }
    Object.defineProperty(CommitQueue.prototype, "isEmpty", {
        get: function () {
            return this.removeList.count === 0 && this.addList.count === 0;
        },
        enumerable: false,
        configurable: true
    });
    CommitQueue.prototype.add = function (o) {
        if (this.removeMap.has(o)) {
            var a = this.removeMap.get(o);
            this.removeMap.delete(o);
            this.removeList.remove(a);
        }
        if (this.addMap.has(o))
            return;
        var b = this.addList.addLast(o);
        this.addMap.set(o, b);
    };
    CommitQueue.prototype.remove = function (o) {
        if (this.addMap.has(o)) {
            var a = this.addMap.get(o);
            this.addMap.delete(o);
            this.addList.remove(a);
        }
        if (this.removeMap.has(o))
            return;
        var b = this.removeList.addLast(o);
        this.removeMap.set(o, b);
    };
    CommitQueue.prototype.tryGetRemove = function () {
        var o = this.removeList.removeFirst();
        if (o)
            this.removeMap.delete(o);
        return o;
    };
    CommitQueue.prototype.tryGetAdd = function () {
        var o = this.addList.removeFirst();
        if (o)
            this.addMap.delete(o);
        return o;
    };
    return CommitQueue;
}());

//# sourceMappingURL=commit-queue.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary-helper.js
var boundary_helper = __webpack_require__(126);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/scene.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var boundaryHelper = new boundary_helper["a" /* BoundaryHelper */]('98');
function calculateBoundingSphere(renderables, boundingSphere, onlyVisible) {
    boundaryHelper.reset();
    for (var i = 0, il = renderables.length; i < il; ++i) {
        if (onlyVisible && !renderables[i].state.visible)
            continue;
        var boundingSphere_1 = renderables[i].values.boundingSphere.ref.value;
        if (!boundingSphere_1.radius)
            continue;
        boundaryHelper.includeSphere(boundingSphere_1);
    }
    boundaryHelper.finishedIncludeStep();
    for (var i = 0, il = renderables.length; i < il; ++i) {
        if (onlyVisible && !renderables[i].state.visible)
            continue;
        var boundingSphere_2 = renderables[i].values.boundingSphere.ref.value;
        if (!boundingSphere_2.radius)
            continue;
        boundaryHelper.radiusSphere(boundingSphere_2);
    }
    return boundaryHelper.getSphere(boundingSphere);
}
function renderableSort(a, b) {
    var drawProgramIdA = a.getProgram('color').id;
    var drawProgramIdB = b.getProgram('color').id;
    var materialIdA = a.materialId;
    var materialIdB = b.materialId;
    if (drawProgramIdA !== drawProgramIdB) {
        // sort by program id to minimize gl state changes
        return drawProgramIdA - drawProgramIdB;
    }
    else if (materialIdA !== materialIdB) {
        // sort by material id to minimize gl state changes
        return materialIdA - materialIdB;
    }
    else {
        return a.id - b.id;
    }
}
var scene_Scene;
(function (Scene) {
    function create(ctx) {
        var renderableMap = new Map();
        var renderables = [];
        var boundingSphere = Object(geometry["g" /* Sphere3D */])();
        var boundingSphereVisible = Object(geometry["g" /* Sphere3D */])();
        var boundingSphereDirty = true;
        var boundingSphereVisibleDirty = true;
        var object3d = object3d_Object3D.create();
        function add(o) {
            if (!renderableMap.has(o)) {
                var renderable = Object(render_object["b" /* createRenderable */])(ctx, o);
                renderables.push(renderable);
                renderableMap.set(o, renderable);
                boundingSphereDirty = true;
                boundingSphereVisibleDirty = true;
                return renderable;
            }
            else {
                console.warn("RenderObject with id '" + o.id + "' already present");
                return renderableMap.get(o);
            }
        }
        function remove(o) {
            var renderable = renderableMap.get(o);
            if (renderable) {
                renderable.dispose();
                Object(array["arraySetRemove"])(renderables, renderable);
                renderableMap.delete(o);
                boundingSphereDirty = true;
                boundingSphereVisibleDirty = true;
            }
        }
        var commitBulkSize = 100;
        function commit(maxTimeMs) {
            var start = Object(now["b" /* now */])();
            var i = 0;
            while (true) {
                var o = commitQueue.tryGetRemove();
                if (!o)
                    break;
                remove(o);
                if (++i % commitBulkSize === 0 && Object(now["b" /* now */])() - start > maxTimeMs)
                    return false;
            }
            while (true) {
                var o = commitQueue.tryGetAdd();
                if (!o)
                    break;
                add(o);
                if (++i % commitBulkSize === 0 && Object(now["b" /* now */])() - start > maxTimeMs)
                    return false;
            }
            renderables.sort(renderableSort);
            return true;
        }
        var commitQueue = new commit_queue_CommitQueue();
        var visibleHash = -1;
        function computeVisibleHash() {
            var hash = 23;
            for (var i = 0, il = renderables.length; i < il; ++i) {
                if (!renderables[i].state.visible)
                    continue;
                hash = (31 * hash + renderables[i].id) | 0;
            }
            hash = Object(util["h" /* hash1 */])(hash);
            if (hash === -1)
                hash = 0;
            return hash;
        }
        function syncVisibility() {
            var newVisibleHash = computeVisibleHash();
            if (newVisibleHash !== visibleHash) {
                boundingSphereVisibleDirty = true;
                return true;
            }
            else {
                return false;
            }
        }
        return {
            get view() { return object3d.view; },
            get position() { return object3d.position; },
            get direction() { return object3d.direction; },
            get up() { return object3d.up; },
            syncVisibility: syncVisibility,
            update: function (objects, keepBoundingSphere, isRemoving) {
                object3d_Object3D.update(object3d);
                if (objects) {
                    for (var i = 0, il = objects.length; i < il; ++i) {
                        var o = renderableMap.get(objects[i]);
                        if (!o)
                            continue;
                        o.update();
                    }
                }
                else if (!isRemoving) {
                    for (var i = 0, il = renderables.length; i < il; ++i) {
                        renderables[i].update();
                    }
                }
                if (!keepBoundingSphere) {
                    boundingSphereDirty = true;
                    boundingSphereVisibleDirty = true;
                }
                else {
                    syncVisibility();
                }
            },
            add: function (o) { return commitQueue.add(o); },
            remove: function (o) { return commitQueue.remove(o); },
            commit: function (maxTime) {
                if (maxTime === void 0) { maxTime = Number.MAX_VALUE; }
                return commit(maxTime);
            },
            get needsCommit() { return !commitQueue.isEmpty; },
            has: function (o) {
                return renderableMap.has(o);
            },
            clear: function () {
                for (var i = 0, il = renderables.length; i < il; ++i) {
                    renderables[i].dispose();
                }
                renderables.length = 0;
                renderableMap.clear();
                boundingSphereDirty = true;
                boundingSphereVisibleDirty = true;
            },
            forEach: function (callbackFn) {
                renderableMap.forEach(callbackFn);
            },
            get count() {
                return renderables.length;
            },
            renderables: renderables,
            get boundingSphere() {
                if (boundingSphereDirty) {
                    calculateBoundingSphere(renderables, boundingSphere, false);
                    boundingSphereDirty = false;
                }
                return boundingSphere;
            },
            get boundingSphereVisible() {
                if (boundingSphereVisibleDirty) {
                    calculateBoundingSphere(renderables, boundingSphereVisible, true);
                    boundingSphereVisibleDirty = false;
                    visibleHash = computeVisibleHash();
                }
                return boundingSphereVisible;
            }
        };
    }
    Scene.create = create;
})(scene_Scene || (scene_Scene = {}));
/* harmony default export */ var scene = __webpack_exports__["a"] = (scene_Scene);
//# sourceMappingURL=scene.js.map

/***/ }),
/* 264 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ sphereVertexCount; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ Sphere; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util.js
var util = __webpack_require__(124);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/polyhedron.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

// adapted from three.js, MIT License Copyright 2010-2018 three.js authors


var DefaultPolyhedronProps = {
    radius: 1,
    detail: 0
};
function Polyhedron(_vertices, _indices, props) {
    var _a = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultPolyhedronProps), props), radius = _a.radius, detail = _a.detail;
    var builder = createBuilder();
    var vertices = builder.vertices, indices = builder.indices;
    // the subdivision creates the vertex buffer data
    subdivide(detail);
    // all vertices should lie on a conceptual sphere with a given radius
    Object(util["a" /* appplyRadius */])(vertices, radius);
    var normals = new Float32Array(vertices.length);
    Object(util["b" /* computeIndexedVertexNormals */])(vertices, indices, normals, vertices.length / 3, indices.length / 3);
    return {
        vertices: new Float32Array(vertices),
        normals: new Float32Array(normals),
        indices: new Uint32Array(indices)
    };
    // helper functions
    function subdivide(detail) {
        var a = Object(linear_algebra["Vec3"])();
        var b = Object(linear_algebra["Vec3"])();
        var c = Object(linear_algebra["Vec3"])();
        // iterate over all faces and apply a subdivison with the given detail value
        for (var i = 0; i < _indices.length; i += 3) {
            // get the vertices of the face
            linear_algebra["Vec3"].fromArray(a, _vertices, _indices[i + 0] * 3);
            linear_algebra["Vec3"].fromArray(b, _vertices, _indices[i + 1] * 3);
            linear_algebra["Vec3"].fromArray(c, _vertices, _indices[i + 2] * 3);
            // perform subdivision
            subdivideFace(a, b, c, detail);
        }
    }
    function subdivideFace(a, b, c, detail) {
        var cols = Math.pow(2, detail);
        // we use this multidimensional array as a data structure for creating the subdivision
        var v = [];
        // construct all of the vertices for this subdivision
        for (var i = 0; i <= cols; ++i) {
            v[i] = [];
            var aj = Object(linear_algebra["Vec3"])();
            linear_algebra["Vec3"].lerp(aj, a, c, i / cols);
            var bj = Object(linear_algebra["Vec3"])();
            linear_algebra["Vec3"].lerp(bj, b, c, i / cols);
            var rows = cols - i;
            for (var j = 0; j <= rows; ++j) {
                if (j === 0 && i === cols) {
                    v[i][j] = aj;
                }
                else {
                    var abj = Object(linear_algebra["Vec3"])();
                    linear_algebra["Vec3"].lerp(abj, aj, bj, j / rows);
                    v[i][j] = abj;
                }
            }
        }
        // construct all of the faces
        for (var i = 0; i < cols; ++i) {
            for (var j = 0; j < 2 * (cols - i) - 1; ++j) {
                var k = Math.floor(j / 2);
                if (j % 2 === 0) {
                    builder.add(v[i][k + 1], v[i + 1][k], v[i][k]);
                }
                else {
                    builder.add(v[i][k + 1], v[i + 1][k + 1], v[i + 1][k]);
                }
            }
        }
    }
}
function createBuilder() {
    var vertices = [];
    var indices = [];
    var vertexMap = new Map();
    function addVertex(v) {
        var key = v[0].toFixed(5) + "|" + v[1].toFixed(5) + "|" + v[2].toFixed(5);
        var idx = vertexMap.get(key);
        if (idx === undefined) {
            idx = vertices.length / 3;
            vertexMap.set(key, idx);
            vertices.push.apply(vertices, v);
        }
        return idx;
    }
    return {
        vertices: vertices,
        indices: indices,
        add: function (v1, v2, v3) {
            indices.push(addVertex(v1), addVertex(v2), addVertex(v3));
        }
    };
}
//# sourceMappingURL=polyhedron.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/primitive.js
var primitive = __webpack_require__(127);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/cage.js
var cage = __webpack_require__(184);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/icosahedron.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var t = (1 + Math.sqrt(5)) / 2;
var icosahedronVertices = [
    -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0,
    0, -1, t, 0, 1, t, 0, -1, -t, 0, 1, -t,
    t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1
];
var icosahedronIndices = [
    0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
    1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
    3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
    4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1
];
var icosahedronEdges = [
    0, 11, 5, 11, 0, 5, 1, 5, 0, 1, 1, 7, 0, 7, 7, 10, 0, 10, 10, 11,
    5, 9, 4, 11, 2, 10, 6, 7, 1, 8, 3, 9, 4, 9, 3, 4, 2, 4, 2, 3,
    2, 6, 3, 6, 6, 8, 3, 8, 8, 9, 4, 5, 2, 11, 6, 10, 7, 8, 1, 9
];
var icosahedron;
function Icosahedron() {
    if (!icosahedron)
        icosahedron = Object(primitive["b" /* createPrimitive */])(icosahedronVertices, icosahedronIndices);
    return icosahedron;
}
var icosahedronCage = Object(cage["b" /* createCage */])(icosahedronVertices, icosahedronEdges);
function IcosahedronCage() {
    return icosahedronCage;
}
//# sourceMappingURL=icosahedron.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/sphere.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var sphere_a = Icosahedron(), sphere_vertices = sphere_a.vertices, sphere_indices = sphere_a.indices;
/** Calculate vertex count for subdived icosahedron */
function sphereVertexCount(detail) {
    return 10 * Math.pow(Math.pow(2, detail), 2) + 2;
}
/** Create sphere by subdividing an icosahedron */
function Sphere(detail) {
    return Polyhedron(sphere_vertices, sphere_indices, { detail: detail, radius: 1 });
}
//# sourceMappingURL=sphere.js.map

/***/ }),
/* 265 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ direct_volume_DirectVolume; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util.js
var mol_geo_util = __webpack_require__(124);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/util.js
var renderable_util = __webpack_require__(53);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/box.js
var box = __webpack_require__(242);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/base.js
var base = __webpack_require__(33);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/color-data.js
var color_data = __webpack_require__(117);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/marker-data.js
var marker_data = __webpack_require__(125);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/overpaint-data.js
var overpaint_data = __webpack_require__(134);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/transparency-data.js
var transparency_data = __webpack_require__(142);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/interpolate.js
var interpolate = __webpack_require__(78);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/direct-volume/transfer-function.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getControlPointsFromString(s) {
    return s.split(/\s*,\s*/).map(function (p) {
        var ps = p.split(/\s*:\s*/);
        return { x: parseFloat(ps[0]), alpha: parseFloat(ps[1]) };
    });
}
function getControlPointsFromVec2Array(array) {
    return array.map(function (v) { return ({ x: v[0], alpha: v[1] }); });
}
function createTransferFunctionTexture(controlPoints, listOrName, texture) {
    var cp = Object(tslib_es6["__spreadArrays"])([
        { x: 0, alpha: 0 },
        { x: 0, alpha: 0 }
    ], controlPoints, [
        { x: 1, alpha: 0 },
        { x: 1, alpha: 0 },
    ]);
    var scale = mol_util_color["ColorScale"].create({ domain: [0, 1], listOrName: listOrName });
    var n = 256;
    var array = texture ? texture.ref.value.array : new Uint8Array(n * 4);
    var k = 0;
    var x1, x2;
    var a0, a1, a2, a3;
    var il = controlPoints.length + 1;
    for (var i = 0; i < il; ++i) {
        x1 = cp[i + 1].x;
        x2 = cp[i + 2].x;
        a0 = cp[i].alpha;
        a1 = cp[i + 1].alpha;
        a2 = cp[i + 2].alpha;
        a3 = cp[i + 3].alpha;
        var jl = Math.round((x2 - x1) * n);
        for (var j = 0; j < jl; ++j) {
            var t = j / jl;
            array[k * 4 + 3] = Math.max(0, Object(interpolate["d" /* spline */])(a0, a1, a2, a3, t, 0.5) * 255);
            scale.colorToArray(k / 255, array, k * 4);
            ++k;
        }
    }
    var textureImage = { array: array, width: 256, height: 1 };
    if (texture) {
        mol_util["e" /* ValueCell */].update(texture, textureImage);
        return texture;
    }
    else {
        return mol_util["e" /* ValueCell */].create(textureImage);
    }
}
//# sourceMappingURL=transfer-function.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/clipping-data.js
var clipping_data = __webpack_require__(143);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/direct-volume/direct-volume.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var VolumeBox = Object(box["a" /* Box */])();
var RenderModeOptions = [['isosurface', 'Isosurface'], ['volume', 'Volume']];
var direct_volume_DirectVolume;
(function (DirectVolume) {
    function create(bbox, gridDimension, transform, texture, directVolume) {
        return directVolume ?
            update(bbox, gridDimension, transform, texture, directVolume) :
            fromData(bbox, gridDimension, transform, texture);
    }
    DirectVolume.create = create;
    function hashCode(directVolume) {
        return Object(util["l" /* hashFnv32a */])([
            directVolume.bboxSize.ref.version, directVolume.gridDimension.ref.version,
            directVolume.gridTexture.ref.version, directVolume.transform.ref.version,
        ]);
    }
    function fromData(bbox, gridDimension, transform, texture) {
        var boundingSphere = Object(geometry["g" /* Sphere3D */])();
        var currentHash = -1;
        var width = texture.getWidth();
        var height = texture.getHeight();
        var depth = texture.getDepth();
        var directVolume = {
            kind: 'direct-volume',
            gridDimension: mol_util["e" /* ValueCell */].create(gridDimension),
            gridTexture: mol_util["e" /* ValueCell */].create(texture),
            gridTextureDim: mol_util["e" /* ValueCell */].create(linear_algebra["Vec3"].create(width, height, depth)),
            bboxMin: mol_util["e" /* ValueCell */].create(bbox.min),
            bboxMax: mol_util["e" /* ValueCell */].create(bbox.max),
            bboxSize: mol_util["e" /* ValueCell */].create(linear_algebra["Vec3"].sub(linear_algebra["Vec3"].zero(), bbox.max, bbox.min)),
            transform: mol_util["e" /* ValueCell */].create(transform),
            get boundingSphere() {
                var newHash = hashCode(directVolume);
                if (newHash !== currentHash) {
                    var b = getBoundingSphere(directVolume.gridDimension.ref.value, directVolume.transform.ref.value);
                    geometry["g" /* Sphere3D */].copy(boundingSphere, b);
                    currentHash = newHash;
                }
                return boundingSphere;
            },
        };
        return directVolume;
    }
    function update(bbox, gridDimension, transform, texture, directVolume) {
        var width = texture.getWidth();
        var height = texture.getHeight();
        var depth = texture.getDepth();
        mol_util["e" /* ValueCell */].update(directVolume.gridDimension, gridDimension);
        mol_util["e" /* ValueCell */].update(directVolume.gridTexture, texture);
        mol_util["e" /* ValueCell */].update(directVolume.gridTextureDim, linear_algebra["Vec3"].set(directVolume.gridTextureDim.ref.value, width, height, depth));
        mol_util["e" /* ValueCell */].update(directVolume.bboxMin, bbox.min);
        mol_util["e" /* ValueCell */].update(directVolume.bboxMax, bbox.max);
        mol_util["e" /* ValueCell */].update(directVolume.bboxSize, linear_algebra["Vec3"].sub(directVolume.bboxSize.ref.value, bbox.max, bbox.min));
        mol_util["e" /* ValueCell */].update(directVolume.transform, transform);
        return directVolume;
    }
    function createEmpty(directVolume) {
        return {}; // TODO
    }
    DirectVolume.createEmpty = createEmpty;
    DirectVolume.Params = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, base["a" /* BaseGeometry */].Params), { isoValueNorm: param_definition["ParamDefinition"].Numeric(0.22, { min: 0, max: 1, step: 0.01 }, { description: 'Normalized Isolevel Value' }), renderMode: param_definition["ParamDefinition"].Select('volume', RenderModeOptions), controlPoints: param_definition["ParamDefinition"].LineGraph([
            linear_algebra["Vec2"].create(0.19, 0.0), linear_algebra["Vec2"].create(0.2, 0.05), linear_algebra["Vec2"].create(0.25, 0.05), linear_algebra["Vec2"].create(0.26, 0.0),
            linear_algebra["Vec2"].create(0.79, 0.0), linear_algebra["Vec2"].create(0.8, 0.05), linear_algebra["Vec2"].create(0.85, 0.05), linear_algebra["Vec2"].create(0.86, 0.0),
        ]), list: param_definition["ParamDefinition"].ColorList('red-yellow-blue') });
    DirectVolume.Utils = {
        Params: DirectVolume.Params,
        createEmpty: createEmpty,
        createValues: createValues,
        createValuesSimple: createValuesSimple,
        updateValues: updateValues,
        updateBoundingSphere: updateBoundingSphere,
        createRenderableState: createRenderableState,
        updateRenderableState: updateRenderableState
    };
    function createValues(directVolume, transform, locationIt, theme, props) {
        var gridTexture = directVolume.gridTexture, gridTextureDim = directVolume.gridTextureDim;
        var bboxSize = directVolume.bboxSize, bboxMin = directVolume.bboxMin, bboxMax = directVolume.bboxMax, gridDimension = directVolume.gridDimension, gridTransform = directVolume.transform;
        var instanceCount = locationIt.instanceCount, groupCount = locationIt.groupCount;
        var color = Object(color_data["a" /* createColors */])(locationIt, theme.color);
        var marker = Object(marker_data["a" /* createMarkers */])(instanceCount * groupCount);
        var overpaint = Object(overpaint_data["c" /* createEmptyOverpaint */])();
        var transparency = Object(transparency_data["c" /* createEmptyTransparency */])();
        var clipping = Object(clipping_data["d" /* createEmptyClipping */])();
        var counts = { drawCount: VolumeBox.indices.length, groupCount: groupCount, instanceCount: instanceCount };
        var invariantBoundingSphere = geometry["g" /* Sphere3D */].clone(directVolume.boundingSphere);
        var boundingSphere = Object(renderable_util["b" /* calculateTransformBoundingSphere */])(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount);
        var controlPoints = getControlPointsFromVec2Array(props.controlPoints);
        var transferTex = createTransferFunctionTexture(controlPoints, props.list.colors);
        var maxSteps = Math.ceil(linear_algebra["Vec3"].magnitude(gridDimension.ref.value)) * 2 * 5;
        return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, color), marker), overpaint), transparency), clipping), transform), base["a" /* BaseGeometry */].createValues(props, counts)), { aPosition: mol_util["e" /* ValueCell */].create(VolumeBox.vertices), elements: mol_util["e" /* ValueCell */].create(VolumeBox.indices), boundingSphere: mol_util["e" /* ValueCell */].create(boundingSphere), invariantBoundingSphere: mol_util["e" /* ValueCell */].create(invariantBoundingSphere), uInvariantBoundingSphere: mol_util["e" /* ValueCell */].create(linear_algebra["Vec4"].ofSphere(invariantBoundingSphere)), uIsoValue: mol_util["e" /* ValueCell */].create(props.isoValueNorm), uBboxMin: bboxMin, uBboxMax: bboxMax, uBboxSize: bboxSize, dMaxSteps: mol_util["e" /* ValueCell */].create(maxSteps), uTransform: gridTransform, uGridDim: gridDimension, dRenderMode: mol_util["e" /* ValueCell */].create(props.renderMode), tTransferTex: transferTex, dGridTexType: mol_util["e" /* ValueCell */].create(gridTexture.ref.value.getDepth() > 0 ? '3d' : '2d'), uGridTexDim: gridTextureDim, tGridTex: gridTexture });
    }
    function createValuesSimple(directVolume, props, colorValue, sizeValue, transform) {
        var s = base["a" /* BaseGeometry */].createSimple(colorValue, sizeValue, transform);
        var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(DirectVolume.Params)), props);
        return createValues(directVolume, s.transform, s.locationIterator, s.theme, p);
    }
    function updateValues(values, props) {
        mol_util["e" /* ValueCell */].updateIfChanged(values.uIsoValue, props.isoValueNorm);
        mol_util["e" /* ValueCell */].updateIfChanged(values.uAlpha, props.alpha);
        mol_util["e" /* ValueCell */].updateIfChanged(values.dRenderMode, props.renderMode);
        var controlPoints = getControlPointsFromVec2Array(props.controlPoints);
        createTransferFunctionTexture(controlPoints, props.list.colors, values.tTransferTex);
    }
    function updateBoundingSphere(values, directVolume) {
        var invariantBoundingSphere = geometry["g" /* Sphere3D */].clone(directVolume.boundingSphere);
        var boundingSphere = Object(renderable_util["b" /* calculateTransformBoundingSphere */])(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value);
        if (!geometry["g" /* Sphere3D */].equals(boundingSphere, values.boundingSphere.ref.value)) {
            mol_util["e" /* ValueCell */].update(values.boundingSphere, boundingSphere);
        }
        if (!geometry["g" /* Sphere3D */].equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
            mol_util["e" /* ValueCell */].update(values.invariantBoundingSphere, invariantBoundingSphere);
            mol_util["e" /* ValueCell */].update(values.uInvariantBoundingSphere, linear_algebra["Vec4"].fromSphere(values.uInvariantBoundingSphere.ref.value, invariantBoundingSphere));
        }
    }
    function createRenderableState(props) {
        var state = base["a" /* BaseGeometry */].createRenderableState(props);
        state.opaque = false;
        return state;
    }
    function updateRenderableState(state, props) {
        base["a" /* BaseGeometry */].updateRenderableState(state, props);
        state.opaque = false;
    }
})(direct_volume_DirectVolume || (direct_volume_DirectVolume = {}));
//
var mTmp = linear_algebra["Mat4"].identity();
var mTmp2 = linear_algebra["Mat4"].identity();
var vHalfUnit = linear_algebra["Vec3"].create(0.5, 0.5, 0.5);
var tmpVertices = new Float32Array(VolumeBox.vertices.length);
function getBoundingSphere(gridDimension, gridTransform) {
    tmpVertices.set(VolumeBox.vertices);
    linear_algebra["Mat4"].fromTranslation(mTmp, vHalfUnit);
    linear_algebra["Mat4"].mul(mTmp, linear_algebra["Mat4"].fromScaling(mTmp2, gridDimension), mTmp);
    linear_algebra["Mat4"].mul(mTmp, gridTransform, mTmp);
    Object(mol_geo_util["e" /* transformPositionArray */])(mTmp, tmpVertices, 0, tmpVertices.length / 3);
    return Object(renderable_util["a" /* calculateInvariantBoundingSphere */])(tmpVertices, tmpVertices.length / 3, 1);
    // return calculateBoundingSphere(tmpVertices, tmpVertices.length / 3, transform, transformCount)
}
//# sourceMappingURL=direct-volume.js.map

/***/ }),
/* 266 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export SynchronousRuntimeContext */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SyncRuntimeContext; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var SynchronousRuntimeContext = /** @class */ (function () {
    function SynchronousRuntimeContext() {
        this.shouldUpdate = false;
        this.isSynchronous = true;
    }
    SynchronousRuntimeContext.prototype.update = function (progress, dontNotify) { };
    return SynchronousRuntimeContext;
}());

var SyncRuntimeContext = new SynchronousRuntimeContext();
//# sourceMappingURL=synchronous.js.map

/***/ }),
/* 267 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructConn; });
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(62);
/* harmony import */ var _mol_model_structure_model_properties_atomic_bonds__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(306);
/* harmony import */ var _common_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(188);
/**
 * Copyright (c) 2017-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var StructConn;
(function (StructConn) {
    StructConn.Descriptor = {
        name: 'struct_conn',
        cifExport: {
            prefix: '',
            categories: [{
                    name: 'struct_conn',
                    instance: function (ctx) {
                        var p = StructConn.Provider.get(ctx.firstModel);
                        if (!p || p.entries.length === 0)
                            return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.Empty;
                        var structure = ctx.structures[0];
                        var indices = [];
                        for (var _a = 0, _b = p.entries; _a < _b.length; _a++) {
                            var e = _b[_a];
                            if (hasAtom(structure, e.partnerA.atomIndex) &&
                                hasAtom(structure, e.partnerB.atomIndex)) {
                                indices[indices.length] = e.rowIndex;
                            }
                        }
                        return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.ofTable(p.data, indices);
                    }
                }]
        }
    };
    StructConn.Provider = _common_property__WEBPACK_IMPORTED_MODULE_3__[/* FormatPropertyProvider */ "a"].create(StructConn.Descriptor);
    function hasAtom(_a, element) {
        var units = _a.units;
        for (var i = 0, _i = units.length; i < _i; i++) {
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].indexOf(units[i].elements, element) >= 0)
                return true;
        }
        return false;
    }
    function getAtomIndexFromEntries(entries) {
        var m = new Map();
        for (var _a = 0, entries_1 = entries; _a < entries_1.length; _a++) {
            var e = entries_1[_a];
            var iA = e.partnerA.atomIndex, iB = e.partnerB.atomIndex;
            if (m.has(iA))
                m.get(iA).push(e);
            else
                m.set(iA, [e]);
            if (m.has(iB))
                m.get(iB).push(e);
            else
                m.set(iB, [e]);
        }
        return m;
    }
    StructConn.getAtomIndexFromEntries = getAtomIndexFromEntries;
    function getEntriesFromStructConn(struct_conn, model) {
        var conn_type_id = struct_conn.conn_type_id, pdbx_dist_value = struct_conn.pdbx_dist_value, pdbx_value_order = struct_conn.pdbx_value_order;
        var p1 = {
            label_asym_id: struct_conn.ptnr1_label_asym_id,
            label_seq_id: struct_conn.ptnr1_label_seq_id,
            auth_seq_id: struct_conn.ptnr1_auth_seq_id,
            label_atom_id: struct_conn.ptnr1_label_atom_id,
            label_alt_id: struct_conn.pdbx_ptnr1_label_alt_id,
            ins_code: struct_conn.pdbx_ptnr1_PDB_ins_code,
            symmetry: struct_conn.ptnr1_symmetry
        };
        var p2 = {
            label_asym_id: struct_conn.ptnr2_label_asym_id,
            label_seq_id: struct_conn.ptnr2_label_seq_id,
            auth_seq_id: struct_conn.ptnr2_auth_seq_id,
            label_atom_id: struct_conn.ptnr2_label_atom_id,
            label_alt_id: struct_conn.pdbx_ptnr2_label_alt_id,
            ins_code: struct_conn.pdbx_ptnr2_PDB_ins_code,
            symmetry: struct_conn.ptnr2_symmetry
        };
        var _p = function (row, ps) {
            if (ps.label_asym_id.valueKind(row) !== 0 /* Present */)
                return void 0;
            var asymId = ps.label_asym_id.value(row);
            var entityIndex = model.atomicHierarchy.index.findEntity(asymId);
            if (entityIndex < 0)
                return void 0;
            var residueIndex = model.atomicHierarchy.index.findResidue(model.entities.data.id.value(entityIndex), asymId, ps.auth_seq_id.value(row), ps.ins_code.value(row));
            if (residueIndex < 0)
                return void 0;
            var atomName = ps.label_atom_id.value(row);
            // turns out "mismat" records might not have atom name value
            if (!atomName)
                return void 0;
            var atomIndex = model.atomicHierarchy.index.findAtomOnResidue(residueIndex, atomName, ps.label_alt_id.value(row));
            if (atomIndex < 0)
                return void 0;
            return { residueIndex: residueIndex, atomIndex: atomIndex, symmetry: ps.symmetry.value(row) };
        };
        var entries = [];
        for (var i = 0; i < struct_conn._rowCount; i++) {
            var partnerA = _p(i, p1);
            var partnerB = _p(i, p2);
            if (partnerA === undefined || partnerB === undefined)
                continue;
            var type = conn_type_id.value(i);
            var orderType = (pdbx_value_order.value(i) || '').toLowerCase();
            var flags = 0 /* None */;
            var order = 1;
            switch (orderType) {
                case 'sing':
                    order = 1;
                    break;
                case 'doub':
                    order = 2;
                    break;
                case 'trip':
                    order = 3;
                    break;
                case 'quad':
                    order = 4;
                    break;
                default:
                    order = Object(_mol_model_structure_model_properties_atomic_bonds__WEBPACK_IMPORTED_MODULE_2__[/* getInterBondOrderFromTable */ "a"])(struct_conn.ptnr1_label_comp_id.value(i), struct_conn.ptnr1_label_atom_id.value(i), struct_conn.ptnr2_label_comp_id.value(i), struct_conn.ptnr2_label_atom_id.value(i));
            }
            switch (type) {
                case 'covale':
                    flags = 1 /* Covalent */;
                    break;
                case 'disulf':
                    flags = 1 /* Covalent */ | 8 /* Disulfide */;
                    break;
                case 'hydrog':
                    flags = 4 /* HydrogenBond */;
                    break;
                case 'metalc':
                    flags = 2 /* MetallicCoordination */;
                    break;
            }
            entries.push({
                rowIndex: i,
                flags: flags, order: order,
                distance: pdbx_dist_value.value(i),
                partnerA: partnerA, partnerB: partnerB
            });
        }
        return entries;
    }
    StructConn.getEntriesFromStructConn = getEntriesFromStructConn;
})(StructConn || (StructConn = {}));
//# sourceMappingURL=struct_conn.js.map

/***/ }),
/* 268 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "defaultBondTest", function() { return defaultBondTest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atomicSequence", function() { return atomicSequence; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "water", function() { return water; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "atomicHet", function() { return atomicHet; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "spheres", function() { return spheres; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bundleElementImpl", function() { return bundleElementImpl; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "bundleGenerator", function() { return bundleGenerator; });
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _mol_model_structure_structure_element__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(129);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(27);
/* harmony import */ var _structure_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(112);
/* harmony import */ var _selection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(38);
/* harmony import */ var _model_types__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(22);
/* harmony import */ var _structure_element_bundle__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(342);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







function defaultBondTest(ctx) {
    return _model_types__WEBPACK_IMPORTED_MODULE_5__["BondType"].isCovalent(ctx.atomicBond.type);
}
function atomicSequence() {
    return function query_atomicSequence(ctx) {
        var inputStructure = ctx.inputStructure;
        var l = _mol_model_structure_structure_element__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].Location.create(inputStructure);
        var units = [];
        for (var _i = 0, _a = inputStructure.units; _i < _a.length; _i++) {
            var unit = _a[_i];
            if (unit.kind !== 0 /* Atomic */)
                continue;
            l.unit = unit;
            var elements = unit.elements;
            l.element = elements[0];
            if (_structure__WEBPACK_IMPORTED_MODULE_2__[/* StructureProperties */ "e"].entity.type(l) !== 'polymer')
                continue;
            var residuesIt = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements);
            var residueCount = 0;
            while (residuesIt.hasNext) {
                residueCount++;
                residuesIt.move();
            }
            if (residueCount < 8)
                continue;
            units.push(unit);
        }
        return _selection__WEBPACK_IMPORTED_MODULE_4__[/* StructureSelection */ "a"].Singletons(inputStructure, new _structure_structure__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](units, { parent: inputStructure }));
    };
}
function water() {
    return function query_water(ctx) {
        var inputStructure = ctx.inputStructure;
        var l = _mol_model_structure_structure_element__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].Location.create(inputStructure);
        var units = [];
        for (var _i = 0, _a = inputStructure.units; _i < _a.length; _i++) {
            var unit = _a[_i];
            if (unit.kind !== 0 /* Atomic */)
                continue;
            l.unit = unit;
            var elements = unit.elements;
            l.element = elements[0];
            if (_structure__WEBPACK_IMPORTED_MODULE_2__[/* StructureProperties */ "e"].entity.type(l) !== 'water')
                continue;
            units.push(unit);
        }
        return _selection__WEBPACK_IMPORTED_MODULE_4__[/* StructureSelection */ "a"].Singletons(inputStructure, new _structure_structure__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](units, { parent: inputStructure }));
    };
}
function atomicHet() {
    return function query_atomicHet(ctx) {
        var inputStructure = ctx.inputStructure;
        var l = _mol_model_structure_structure_element__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].Location.create(inputStructure);
        var units = [];
        for (var _i = 0, _a = inputStructure.units; _i < _a.length; _i++) {
            var unit = _a[_i];
            if (unit.kind !== 0 /* Atomic */)
                continue;
            l.unit = unit;
            var elements = unit.elements;
            l.element = elements[0];
            if (_structure__WEBPACK_IMPORTED_MODULE_2__[/* StructureProperties */ "e"].entity.type(l) === 'water')
                continue;
            if (_structure__WEBPACK_IMPORTED_MODULE_2__[/* StructureProperties */ "e"].entity.type(l) === 'polymer') {
                var residuesIt = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, elements);
                var residueCount = 0;
                while (residuesIt.hasNext) {
                    residueCount++;
                    residuesIt.move();
                }
                if (residueCount >= 8)
                    continue;
            }
            units.push(unit);
        }
        return _selection__WEBPACK_IMPORTED_MODULE_4__[/* StructureSelection */ "a"].Singletons(inputStructure, new _structure_structure__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](units, { parent: inputStructure }));
    };
}
function spheres() {
    return function query_spheres(ctx) {
        var inputStructure = ctx.inputStructure;
        var units = [];
        for (var _i = 0, _a = inputStructure.units; _i < _a.length; _i++) {
            var unit = _a[_i];
            if (unit.kind !== 1 /* Spheres */)
                continue;
            units.push(unit);
        }
        return _selection__WEBPACK_IMPORTED_MODULE_4__[/* StructureSelection */ "a"].Singletons(inputStructure, new _structure_structure__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"](units, { parent: inputStructure }));
    };
}
function bundleElementImpl(groupedUnits, ranges, set) {
    return {
        groupedUnits: groupedUnits,
        ranges: ranges,
        set: set
    };
}
function bundleGenerator(elements) {
    return function query_bundleGenerator(ctx) {
        var bundle = {
            hash: ctx.inputStructure.hashCode,
            elements: elements
        };
        return _selection__WEBPACK_IMPORTED_MODULE_4__[/* StructureSelection */ "a"].Sequence(ctx.inputStructure, [_structure_element_bundle__WEBPACK_IMPORTED_MODULE_6__[/* Bundle */ "a"].toStructure(bundle, ctx.inputStructure)]);
    };
}
//# sourceMappingURL=internal.js.map

/***/ }),
/* 269 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return RootStructureDefinition; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(41);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(11);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(1);
/* harmony import */ var _mol_model_structure_model_properties_symmetry__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(291);
/* harmony import */ var _objects__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(8);
/* harmony import */ var _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(113);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var RootStructureDefinition;
(function (RootStructureDefinition) {
    function getParams(model, defaultValue) {
        var symmetry = model && _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_8__[/* ModelSymmetry */ "a"].Provider.get(model);
        var assemblyIds = symmetry ? symmetry.assemblies.map(function (a) { return [a.id, a.id + ": " + Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_2__[/* stringToWords */ "d"])(a.details)]; }) : [];
        var showSymm = !symmetry ? true : !_mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* SpacegroupCell */ "f"].isZero(symmetry.spacegroup.cell);
        var operatorOptions = [];
        if (symmetry) {
            var operators = symmetry.spacegroup.operators;
            for (var i = 0, il = operators.length; i < il; i++) {
                operatorOptions.push([i, i + 1 + ": " + _mol_math_geometry__WEBPACK_IMPORTED_MODULE_3__[/* Spacegroup */ "e"].getOperatorXyz(operators[i])]);
            }
        }
        var asymIdsOptions = [];
        if (model) {
            model.properties.structAsymMap.forEach(function (v) {
                var label = v.id === v.auth_id ? v.id : v.id + " [auth " + v.auth_id + "]";
                asymIdsOptions.push([v.id, label]);
            });
        }
        var modes = {
            auto: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].EmptyGroup(),
            model: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].EmptyGroup(),
            assembly: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                id: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Optional(model
                    ? _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select(assemblyIds.length ? assemblyIds[0][0] : '', assemblyIds, { label: 'Asm Id', description: 'Assembly Id' })
                    : _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Text('', { label: 'Asm Id', description: 'Assembly Id (use empty for the 1st assembly)' }))
            }, { isFlat: true }),
            'symmetry-mates': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                radius: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(5, { min: 0, max: 50, step: 1 })
            }, { isFlat: true }),
            'symmetry': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                ijkMin: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].create(-1, -1, -1), { step: 1 }, { label: 'Min IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } }),
                ijkMax: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"].create(1, 1, 1), { step: 1 }, { label: 'Max IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } })
            }, { isFlat: true }),
            'symmetry-assembly': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                generators: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].ObjectList({
                    operators: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].ObjectList({
                        index: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select(0, operatorOptions),
                        shift: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_5__["Vec3"])(), { step: 1 }, { label: 'IJK', fieldLabels: { x: 'I', y: 'J', z: 'K' } })
                    }, function (e) { return e.index + 1 + "_" + e.shift.map(function (a) { return a + 5; }).join(''); }, {
                        defaultValue: []
                    }),
                    asymIds: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MultiSelect([], asymIdsOptions)
                }, function (e) { return e.asymIds.length + " asym ids, " + e.operators.length + " operators"; }, {
                    defaultValue: []
                })
            }, { isFlat: true })
        };
        var options = [];
        if (defaultValue === 'auto') {
            options.push(['auto', 'Auto']);
        }
        options.push(['model', 'Model']);
        if (assemblyIds.length > 0) {
            options.push(['assembly', 'Assembly']);
        }
        if (showSymm) {
            options.push(['symmetry-mates', 'Symmetry Mates']);
            options.push(['symmetry', 'Symmetry (indices)']);
            options.push(['symmetry-assembly', 'Symmetry (assembly)']);
        }
        return {
            type: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MappedStatic(defaultValue || 'model', modes, { options: options })
        };
    }
    RootStructureDefinition.getParams = getParams;
    function canAutoUpdate(oldParams, newParams) {
        if (newParams.name === 'symmetry-assembly' || (newParams.name === 'symmetry' && oldParams.name === 'symmetry'))
            return false;
        return true;
    }
    RootStructureDefinition.canAutoUpdate = canAutoUpdate;
    function buildAssembly(plugin, ctx, model, id) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var asm, symmetry, base, label, s, props;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        asm = void 0;
                        symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_8__[/* ModelSymmetry */ "a"].Provider.get(model);
                        // if no id is specified, use the 1st assembly.
                        if (!id && symmetry && symmetry.assemblies.length !== 0) {
                            id = symmetry.assemblies[0].id;
                        }
                        if (!symmetry || symmetry.assemblies.length === 0) {
                            plugin.log.warn("Model '" + model.entryId + "' has no assembly, returning model structure.");
                        }
                        else {
                            asm = _mol_model_structure_model_properties_symmetry__WEBPACK_IMPORTED_MODULE_6__[/* Symmetry */ "b"].findAssembly(model, id || '');
                            if (!asm) {
                                plugin.log.warn("Model '" + model.entryId + "' has no assembly called '" + id + "', returning model structure.");
                            }
                        }
                        base = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                        if (!asm) {
                            label = { label: 'Model', description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(base) };
                            return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(base, label)];
                        }
                        id = asm.id;
                        return [4 /*yield*/, _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSymmetry"].buildAssembly(base, id).runInContext(ctx)];
                    case 1:
                        s = _a.sent();
                        props = { label: "Assembly " + id, description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) };
                        return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, props)];
                }
            });
        });
    }
    function buildSymmetry(ctx, model, ijkMin, ijkMax) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var base, s, props;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        base = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                        return [4 /*yield*/, _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSymmetry"].buildSymmetryRange(base, ijkMin, ijkMax).runInContext(ctx)];
                    case 1:
                        s = _a.sent();
                        props = { label: "Symmetry [" + ijkMin + "] to [" + ijkMax + "]", description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) };
                        return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, props)];
                }
            });
        });
    }
    function buildSymmetryMates(ctx, model, radius) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var base, s, props;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        base = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                        return [4 /*yield*/, _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSymmetry"].builderSymmetryMates(base, radius).runInContext(ctx)];
                    case 1:
                        s = _a.sent();
                        props = { label: "Symmetry Mates", description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) };
                        return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, props)];
                }
            });
        });
    }
    function buildSymmetryAssembly(ctx, model, generators, symmetry) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var base, s, props;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        base = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                        return [4 /*yield*/, _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureSymmetry"].buildSymmetryAssembly(base, generators, symmetry).runInContext(ctx)];
                    case 1:
                        s = _a.sent();
                        props = { label: "Symmetry Assembly", description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) };
                        return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, props)];
                }
            });
        });
    }
    function create(plugin, ctx, model, params) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var symmetry, s, s;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_8__[/* ModelSymmetry */ "a"].Provider.get(model);
                if (!symmetry || !params || params.name === 'model') {
                    s = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                    return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, { label: 'Model', description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) })];
                }
                if (params.name === 'auto') {
                    if (symmetry.assemblies.length === 0) {
                        s = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].ofModel(model);
                        return [2 /*return*/, new _objects__WEBPACK_IMPORTED_MODULE_7__[/* PluginStateObject */ "a"].Molecule.Structure(s, { label: 'Model', description: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Structure"].elementDescription(s) })];
                    }
                    else {
                        return [2 /*return*/, buildAssembly(plugin, ctx, model)];
                    }
                }
                if (params.name === 'assembly') {
                    return [2 /*return*/, buildAssembly(plugin, ctx, model, params.params.id)];
                }
                if (params.name === 'symmetry') {
                    return [2 /*return*/, buildSymmetry(ctx, model, params.params.ijkMin, params.params.ijkMax)];
                }
                if (params.name === 'symmetry-mates') {
                    return [2 /*return*/, buildSymmetryMates(ctx, model, params.params.radius)];
                }
                if (params.name === 'symmetry-assembly') {
                    return [2 /*return*/, buildSymmetryAssembly(ctx, model, params.params.generators, symmetry)];
                }
                throw new Error("Unknown represetation type: " + params.name);
            });
        });
    }
    RootStructureDefinition.create = create;
})(RootStructureDefinition || (RootStructureDefinition = {}));
//# sourceMappingURL=root-structure.js.map

/***/ }),
/* 270 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export StructureRepresentationPresetProvider */
/* unused harmony export presetStaticComponent */
/* unused harmony export presetSelectionComponent */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PresetStructureRepresentations; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(33);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(13);
/* harmony import */ var _helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(80);
/* harmony import */ var _mol_plugin_config__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(101);
/* harmony import */ var _mol_plugin_behavior_dynamic_selection_structure_focus_representation__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(320);
/* harmony import */ var _helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(162);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









function StructureRepresentationPresetProvider(repr) { return repr; }
(function (StructureRepresentationPresetProvider) {
    StructureRepresentationPresetProvider.CommonParams = {
        ignoreHydrogens: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false)),
        quality: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Select('auto', _mol_geo_geometry_base__WEBPACK_IMPORTED_MODULE_2__[/* VisualQualityOptions */ "b"])),
        theme: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Group({
            globalName: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Text('')),
            carbonByChainId: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(true)),
            focus: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Group({
                name: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Text('')),
                params: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Optional(_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Value({}))
            }))
        }))
    };
    function reprBuilder(plugin, params) {
        var _a, _b, _c, _d;
        var update = plugin.state.data.build();
        var builder = plugin.builders.structure.representation;
        var typeParams = {
            quality: plugin.managers.structure.component.state.options.visualQuality,
            ignoreHydrogens: !plugin.managers.structure.component.state.options.showHydrogens,
        };
        if (params.quality && params.quality !== 'auto')
            typeParams.quality = params.quality;
        if (params.ignoreHydrogens !== void 0)
            typeParams.ignoreHydrogens = !!params.ignoreHydrogens;
        var color = ((_a = params.theme) === null || _a === void 0 ? void 0 : _a.globalName) ? (_b = params.theme) === null || _b === void 0 ? void 0 : _b.globalName : void 0;
        var ballAndStickColor = typeof ((_c = params.theme) === null || _c === void 0 ? void 0 : _c.carbonByChainId) !== 'undefined' ? { carbonByChainId: !!((_d = params.theme) === null || _d === void 0 ? void 0 : _d.carbonByChainId) } : {};
        return { update: update, builder: builder, color: color, typeParams: typeParams, ballAndStickColor: ballAndStickColor };
    }
    StructureRepresentationPresetProvider.reprBuilder = reprBuilder;
    function updateFocusRepr(plugin, structure, themeName, themeParams) {
        if (!themeName && !themeParams)
            return;
        return plugin.state.updateBehavior(_mol_plugin_behavior_dynamic_selection_structure_focus_representation__WEBPACK_IMPORTED_MODULE_7__["StructureFocusRepresentation"], function (p) {
            var c = Object(_helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_8__["createStructureColorThemeParams"])(plugin, structure, 'ball-and-stick', themeName, themeParams);
            p.surroundingsParams.colorTheme = c;
            p.targetParams.colorTheme = c;
        });
    }
    StructureRepresentationPresetProvider.updateFocusRepr = updateFocusRepr;
})(StructureRepresentationPresetProvider || (StructureRepresentationPresetProvider = {}));
var CommonParams = StructureRepresentationPresetProvider.CommonParams;
var reprBuilder = StructureRepresentationPresetProvider.reprBuilder;
var updateFocusRepr = StructureRepresentationPresetProvider.updateFocusRepr;
var auto = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-auto',
    display: {
        name: 'Automatic',
        description: 'Show representations based on the size of the structure. Smaller structures are shown with more detail than larger ones, ranging from atomistic display to coarse surfaces.'
    },
    params: function () { return CommonParams; },
    apply: function (ref, params, plugin) {
        var _a, _b;
        var structure = (_b = (_a = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!structure)
            return {};
        var thresholds = plugin.config.get(_mol_plugin_config__WEBPACK_IMPORTED_MODULE_6__["PluginConfig"].Structure.SizeThresholds) || _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].DefaultSizeThresholds;
        var size = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].getSize(structure, thresholds);
        switch (size) {
            case _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Gigantic:
            case _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Huge:
                return coarseSurface.apply(ref, params, plugin);
            case _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Large:
                return polymerCartoon.apply(ref, params, plugin);
            case _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Medium:
                return polymerAndLigand.apply(ref, params, plugin);
            case _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Small:
                // `showCarbohydrateSymbol: true` is nice e.g. for PDB 1aga
                return atomicDetail.apply(ref, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, params), { showCarbohydrateSymbol: true }), plugin);
        }
    }
});
var empty = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-empty',
    display: { name: 'Empty', description: 'Removes all existing representations.' },
    apply: function (ref, params, plugin) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                return [2 /*return*/, {}];
            });
        });
    }
});
var BuiltInPresetGroupName = 'Basic';
var polymerAndLigand = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-polymer-and-ligand',
    display: {
        name: 'Polymer & Ligand', group: BuiltInPresetGroupName,
        description: 'Shows polymers as Cartoon, ligands as Ball & Stick, carbohydrates as 3D-SNFG and water molecules semi-transparent.'
    },
    params: function () { return CommonParams; },
    apply: function (ref, params, plugin) {
        var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var structureCell, components, _l, structure, cartoonProps, waterType, lipidType, _m, update, builder, typeParams, color, ballAndStickColor, representations;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_o) {
                switch (_o.label) {
                    case 0:
                        structureCell = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref);
                        if (!structureCell)
                            return [2 /*return*/, {}];
                        _l = {};
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'polymer')];
                    case 1:
                        _l.polymer = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'ligand')];
                    case 2:
                        _l.ligand = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'non-standard')];
                    case 3:
                        _l.nonStandard = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'branched', { label: 'Carbohydrate' })];
                    case 4:
                        _l.branched = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'water')];
                    case 5:
                        _l.water = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'ion')];
                    case 6:
                        _l.ion = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'lipid')];
                    case 7:
                        _l.lipid = _o.sent();
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'coarse')];
                    case 8:
                        components = (_l.coarse = _o.sent(),
                            _l);
                        structure = structureCell.obj.data;
                        cartoonProps = {
                            sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2,
                        };
                        waterType = (((_c = (_b = (_a = components.water) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.elementCount) || 0) > 50000 ? 'line' : 'ball-and-stick';
                        lipidType = (((_f = (_e = (_d = components.lipid) === null || _d === void 0 ? void 0 : _d.obj) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.elementCount) || 0) > 20000 ? 'line' : 'ball-and-stick';
                        _m = reprBuilder(plugin, params), update = _m.update, builder = _m.builder, typeParams = _m.typeParams, color = _m.color, ballAndStickColor = _m.ballAndStickColor;
                        representations = {
                            polymer: builder.buildRepresentation(update, components.polymer, { type: 'cartoon', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), cartoonProps), color: color }, { tag: 'polymer' }),
                            ligand: builder.buildRepresentation(update, components.ligand, { type: 'ball-and-stick', typeParams: typeParams, color: color, colorParams: ballAndStickColor }, { tag: 'ligand' }),
                            nonStandard: builder.buildRepresentation(update, components.nonStandard, { type: 'ball-and-stick', typeParams: typeParams, color: color, colorParams: ballAndStickColor }, { tag: 'non-standard' }),
                            branchedBallAndStick: builder.buildRepresentation(update, components.branched, { type: 'ball-and-stick', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), { alpha: 0.3 }), color: color, colorParams: ballAndStickColor }, { tag: 'branched-ball-and-stick' }),
                            branchedSnfg3d: builder.buildRepresentation(update, components.branched, { type: 'carbohydrate', typeParams: typeParams, color: color }, { tag: 'branched-snfg-3d' }),
                            water: builder.buildRepresentation(update, components.water, { type: waterType, typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), { alpha: 0.6 }), color: color }, { tag: 'water' }),
                            ion: builder.buildRepresentation(update, components.ion, { type: 'ball-and-stick', typeParams: typeParams, color: color, colorParams: { carbonByChainId: false } }, { tag: 'ion' }),
                            lipid: builder.buildRepresentation(update, components.lipid, { type: lipidType, typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), { alpha: 0.6 }), color: color, colorParams: { carbonByChainId: false } }, { tag: 'lipid' }),
                            coarse: builder.buildRepresentation(update, components.coarse, { type: 'spacefill', typeParams: typeParams, color: color || 'chain-id' }, { tag: 'coarse' })
                        };
                        return [4 /*yield*/, update.commit({ revertOnError: false })];
                    case 9:
                        _o.sent();
                        return [4 /*yield*/, updateFocusRepr(plugin, structure, (_h = (_g = params.theme) === null || _g === void 0 ? void 0 : _g.focus) === null || _h === void 0 ? void 0 : _h.name, (_k = (_j = params.theme) === null || _j === void 0 ? void 0 : _j.focus) === null || _k === void 0 ? void 0 : _k.params)];
                    case 10:
                        _o.sent();
                        return [2 /*return*/, { components: components, representations: representations }];
                }
            });
        });
    }
});
var proteinAndNucleic = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-protein-and-nucleic',
    display: {
        name: 'Protein & Nucleic', group: BuiltInPresetGroupName,
        description: 'Shows proteins as Cartoon and RNA/DNA as Gaussian Surface.'
    },
    params: function () { return CommonParams; },
    apply: function (ref, params, plugin) {
        var _a, _b, _c, _d;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var structureCell, components, _e, structure, cartoonProps, gaussianProps, _f, update, builder, typeParams, color, representations;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        structureCell = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref);
                        if (!structureCell)
                            return [2 /*return*/, {}];
                        _e = {};
                        return [4 /*yield*/, presetSelectionComponent(plugin, structureCell, 'protein')];
                    case 1:
                        _e.protein = _g.sent();
                        return [4 /*yield*/, presetSelectionComponent(plugin, structureCell, 'nucleic')];
                    case 2:
                        components = (_e.nucleic = _g.sent(),
                            _e);
                        structure = structureCell.obj.data;
                        cartoonProps = {
                            sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2,
                        };
                        gaussianProps = {
                            radiusOffset: structure.isCoarseGrained ? 2 : 0,
                            smoothness: structure.isCoarseGrained ? 0.5 : 1.5,
                        };
                        _f = reprBuilder(plugin, params), update = _f.update, builder = _f.builder, typeParams = _f.typeParams, color = _f.color;
                        representations = {
                            protein: builder.buildRepresentation(update, components.protein, { type: 'cartoon', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), cartoonProps), color: color }, { tag: 'protein' }),
                            nucleic: builder.buildRepresentation(update, components.nucleic, { type: 'gaussian-surface', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), gaussianProps), color: color }, { tag: 'nucleic' })
                        };
                        return [4 /*yield*/, update.commit({ revertOnError: true })];
                    case 3:
                        _g.sent();
                        return [4 /*yield*/, updateFocusRepr(plugin, structure, (_b = (_a = params.theme) === null || _a === void 0 ? void 0 : _a.focus) === null || _b === void 0 ? void 0 : _b.name, (_d = (_c = params.theme) === null || _c === void 0 ? void 0 : _c.focus) === null || _d === void 0 ? void 0 : _d.params)];
                    case 4:
                        _g.sent();
                        return [2 /*return*/, { components: components, representations: representations }];
                }
            });
        });
    }
});
var coarseSurface = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-coarse-surface',
    display: {
        name: 'Coarse Surface', group: BuiltInPresetGroupName,
        description: 'Shows polymers as coarse Gaussian Surface.'
    },
    params: function () { return CommonParams; },
    apply: function (ref, params, plugin) {
        var _a, _b, _c, _d;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var structureCell, components, _e, structure, size, gaussianProps, _f, update, builder, typeParams, color, representations;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        structureCell = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref);
                        if (!structureCell)
                            return [2 /*return*/, {}];
                        _e = {};
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'polymer')];
                    case 1:
                        components = (_e.polymer = _g.sent(),
                            _e);
                        structure = structureCell.obj.data;
                        size = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].getSize(structure);
                        gaussianProps = Object.create(null);
                        if (size === _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Gigantic) {
                            Object.assign(gaussianProps, {
                                traceOnly: true,
                                radiusOffset: 2,
                                smoothness: 0.5,
                                visuals: ['structure-gaussian-surface-mesh']
                            });
                        }
                        else if (size === _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["Structure"].Size.Huge) {
                            Object.assign(gaussianProps, {
                                radiusOffset: structure.isCoarseGrained ? 2 : 0,
                                smoothness: 0.5,
                            });
                        }
                        else if (structure.isCoarseGrained) {
                            Object.assign(gaussianProps, {
                                radiusOffset: 2,
                                smoothness: 0.5,
                            });
                        }
                        _f = reprBuilder(plugin, params), update = _f.update, builder = _f.builder, typeParams = _f.typeParams, color = _f.color;
                        representations = {
                            polymer: builder.buildRepresentation(update, components.polymer, { type: 'gaussian-surface', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), gaussianProps), color: color }, { tag: 'polymer' })
                        };
                        return [4 /*yield*/, update.commit({ revertOnError: true })];
                    case 2:
                        _g.sent();
                        return [4 /*yield*/, updateFocusRepr(plugin, structure, (_b = (_a = params.theme) === null || _a === void 0 ? void 0 : _a.focus) === null || _b === void 0 ? void 0 : _b.name, (_d = (_c = params.theme) === null || _c === void 0 ? void 0 : _c.focus) === null || _d === void 0 ? void 0 : _d.params)];
                    case 3:
                        _g.sent();
                        return [2 /*return*/, { components: components, representations: representations }];
                }
            });
        });
    }
});
var polymerCartoon = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-polymer-cartoon',
    display: {
        name: 'Polymer Cartoon', group: BuiltInPresetGroupName,
        description: 'Shows polymers as Cartoon.'
    },
    params: function () { return CommonParams; },
    apply: function (ref, params, plugin) {
        var _a, _b, _c, _d;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var structureCell, components, _e, structure, cartoonProps, _f, update, builder, typeParams, color, representations;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        structureCell = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref);
                        if (!structureCell)
                            return [2 /*return*/, {}];
                        _e = {};
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'polymer')];
                    case 1:
                        components = (_e.polymer = _g.sent(),
                            _e);
                        structure = structureCell.obj.data;
                        cartoonProps = {
                            sizeFactor: structure.isCoarseGrained ? 0.8 : 0.2
                        };
                        _f = reprBuilder(plugin, params), update = _f.update, builder = _f.builder, typeParams = _f.typeParams, color = _f.color;
                        representations = {
                            polymer: builder.buildRepresentation(update, components.polymer, { type: 'cartoon', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), cartoonProps), color: color }, { tag: 'polymer' })
                        };
                        return [4 /*yield*/, update.commit({ revertOnError: true })];
                    case 2:
                        _g.sent();
                        return [4 /*yield*/, updateFocusRepr(plugin, structure, (_b = (_a = params.theme) === null || _a === void 0 ? void 0 : _a.focus) === null || _b === void 0 ? void 0 : _b.name, (_d = (_c = params.theme) === null || _c === void 0 ? void 0 : _c.focus) === null || _d === void 0 ? void 0 : _d.params)];
                    case 3:
                        _g.sent();
                        return [2 /*return*/, { components: components, representations: representations }];
                }
            });
        });
    }
});
var atomicDetail = StructureRepresentationPresetProvider({
    id: 'preset-structure-representation-atomic-detail',
    display: {
        name: 'Atomic Detail', group: BuiltInPresetGroupName,
        description: 'Shows everything in atomic detail with Ball & Stick.'
    },
    params: function () { return (Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, CommonParams), { showCarbohydrateSymbol: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false) })); },
    apply: function (ref, params, plugin) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var structureCell, components, _a, structure, highElementCount, atomicType, showCarbohydrateSymbol, _b, _c, _d, _e, _f, update, builder, typeParams, color, ballAndStickColor, representations;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_g) {
                switch (_g.label) {
                    case 0:
                        structureCell = _mol_state__WEBPACK_IMPORTED_MODULE_4__["StateObjectRef"].resolveAndCheck(plugin.state.data, ref);
                        if (!structureCell)
                            return [2 /*return*/, {}];
                        _a = {};
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'all')];
                    case 1:
                        components = (_a.all = _g.sent(),
                            _a.branched = undefined,
                            _a);
                        structure = structureCell.obj.data;
                        highElementCount = structure.elementCount > 200000;
                        atomicType = highElementCount ? 'line' : 'ball-and-stick';
                        showCarbohydrateSymbol = params.showCarbohydrateSymbol && !highElementCount;
                        if (!showCarbohydrateSymbol) return [3 /*break*/, 3];
                        _c = (_b = Object).assign;
                        _d = [components];
                        _e = {};
                        return [4 /*yield*/, presetStaticComponent(plugin, structureCell, 'branched', { label: 'Carbohydrate' })];
                    case 2:
                        _c.apply(_b, _d.concat([(_e.branched = _g.sent(),
                                _e)]));
                        _g.label = 3;
                    case 3:
                        _f = reprBuilder(plugin, params), update = _f.update, builder = _f.builder, typeParams = _f.typeParams, color = _f.color, ballAndStickColor = _f.ballAndStickColor;
                        representations = {
                            all: builder.buildRepresentation(update, components.all, { type: atomicType, typeParams: typeParams, color: color, colorParams: ballAndStickColor }, { tag: 'all' }),
                        };
                        if (showCarbohydrateSymbol) {
                            Object.assign(representations, {
                                snfg3d: builder.buildRepresentation(update, components.branched, { type: 'carbohydrate', typeParams: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, typeParams), { alpha: 0.4, visuals: ['carbohydrate-symbol'] }), color: color }, { tag: 'snfg-3d' }),
                            });
                        }
                        return [4 /*yield*/, update.commit({ revertOnError: true })];
                    case 4:
                        _g.sent();
                        return [2 /*return*/, { components: components, representations: representations }];
                }
            });
        });
    }
});
function presetStaticComponent(plugin, structure, type, params) {
    return plugin.builders.structure.tryCreateComponentStatic(structure, type, params);
}
function presetSelectionComponent(plugin, structure, query, params) {
    return plugin.builders.structure.tryCreateComponentFromSelection(structure, _helpers_structure_selection_query__WEBPACK_IMPORTED_MODULE_5__[/* StructureSelectionQueries */ "b"][query], "selection-" + query, params);
}
var PresetStructureRepresentations = {
    empty: empty,
    auto: auto,
    'atomic-detail': atomicDetail,
    'polymer-cartoon': polymerCartoon,
    'polymer-and-ligand': polymerAndLigand,
    'protein-and-nucleic': proteinAndNucleic,
    'coarse-surface': coarseSurface
};
//# sourceMappingURL=representation-preset.js.map

/***/ }),
/* 271 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "TrajectoryViewportControls", function() { return /* binding */ controls_TrajectoryViewportControls; });
__webpack_require__.d(__webpack_exports__, "StateSnapshotViewportControls", function() { return /* binding */ controls_StateSnapshotViewportControls; });
__webpack_require__.d(__webpack_exports__, "AnimationViewportControls", function() { return /* binding */ controls_AnimationViewportControls; });
__webpack_require__.d(__webpack_exports__, "SelectionViewportControls", function() { return /* binding */ controls_SelectionViewportControls; });
__webpack_require__.d(__webpack_exports__, "LociLabels", function() { return /* binding */ controls_LociLabels; });
__webpack_require__.d(__webpack_exports__, "CustomStructureControls", function() { return /* binding */ controls_CustomStructureControls; });
__webpack_require__.d(__webpack_exports__, "DefaultStructureTools", function() { return /* binding */ controls_DefaultStructureTools; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure/representation-preset.js
var representation_preset = __webpack_require__(270);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/trajectory.js
var formats_trajectory = __webpack_require__(367);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/root-structure.js
var root_structure = __webpack_require__(269);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var mol_plugin_state_transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/model.js + 35 modules
var transforms_model = __webpack_require__(316);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/assets.js
var assets = __webpack_require__(114);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/config.js
var config = __webpack_require__(101);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/actions/structure.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var DownloadModelRepresentationOptions = function (plugin) { return param_definition["ParamDefinition"].Group({
    type: root_structure["a" /* RootStructureDefinition */].getParams(void 0, 'auto').type,
    representation: param_definition["ParamDefinition"].Select(representation_preset["a" /* PresetStructureRepresentations */].auto.id, plugin.builders.structure.representation.getPresets().map(function (p) { return [p.id, p.display.name, p.display.group]; }), { description: 'Which representation preset to use.' }),
    asTrajectory: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { description: 'Load all entries into a single trajectory.' }))
}, { isExpanded: false }); };
var PdbDownloadProvider = {
    'rcsb': param_definition["ParamDefinition"].Group({
        encoding: param_definition["ParamDefinition"].Select('bcif', [['cif', 'cif'], ['bcif', 'bcif']]),
    }, { label: 'RCSB PDB', isFlat: true }),
    'pdbe': param_definition["ParamDefinition"].Group({
        variant: param_definition["ParamDefinition"].Select('updated-bcif', [['updated-bcif', 'Updated (bcif)'], ['updated', 'Updated'], ['archival', 'Archival']]),
    }, { label: 'PDBe', isFlat: true }),
};

var DownloadStructure = mol_state["StateAction"].build({
    from: objects["a" /* PluginStateObject */].Root,
    display: { name: 'Download Structure', description: 'Load a structure from the provided source and create its representation.' },
    params: function (_, plugin) {
        var options = DownloadModelRepresentationOptions(plugin);
        var defaultPdbProvider = plugin.config.get(config["PluginConfig"].Download.DefaultPdbProvider) || 'pdbe';
        return {
            source: param_definition["ParamDefinition"].MappedStatic('pdb', {
                'pdb': param_definition["ParamDefinition"].Group({
                    provider: param_definition["ParamDefinition"].Group({
                        id: param_definition["ParamDefinition"].Text('1tqn', { label: 'PDB Id(s)', description: 'One or more comma/space separated PDB ids.' }),
                        server: param_definition["ParamDefinition"].MappedStatic(defaultPdbProvider, PdbDownloadProvider),
                    }, { pivot: 'id' }),
                    options: options
                }, { isFlat: true, label: 'PDB' }),
                'pdb-dev': param_definition["ParamDefinition"].Group({
                    provider: param_definition["ParamDefinition"].Group({
                        id: param_definition["ParamDefinition"].Text('PDBDEV_00000001', { label: 'PDBDev Id(s)', description: 'One or more comma/space separated ids.' }),
                        encoding: param_definition["ParamDefinition"].Select('bcif', [['cif', 'cif'], ['bcif', 'bcif']]),
                    }, { pivot: 'id' }),
                    options: options
                }, { isFlat: true, label: 'PDBDEV' }),
                'swissmodel': param_definition["ParamDefinition"].Group({
                    id: param_definition["ParamDefinition"].Text('Q9Y2I8', { label: 'UniProtKB AC(s)', description: 'One or more comma/space separated ACs.' }),
                    options: options
                }, { isFlat: true, label: 'SWISS-MODEL', description: 'Loads the best homology model or experimental structure' }),
                'pubchem': param_definition["ParamDefinition"].Group({
                    id: param_definition["ParamDefinition"].Text('2244,2245', { label: 'PubChem ID', description: 'One or more comma/space separated IDs.' }),
                    options: options
                }, { isFlat: true, label: 'PubChem', description: 'Loads 3D conformer from PubChem.' }),
                'url': param_definition["ParamDefinition"].Group({
                    url: param_definition["ParamDefinition"].Url(''),
                    format: param_definition["ParamDefinition"].Select('mmcif', param_definition["ParamDefinition"].arrayToOptions(formats_trajectory["a" /* BuiltInTrajectoryFormats */].map(function (f) { return f[0]; }), function (f) { return f; })),
                    isBinary: param_definition["ParamDefinition"].Boolean(false),
                    options: options
                }, { isFlat: true, label: 'URL' })
            })
        };
    }
})(function (_a, plugin) {
    var params = _a.params, state = _a.state;
    return mol_task["b" /* Task */].create('Download Structure', function (ctx) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var src, downloadParams, asTrajectory, format, representationPreset, showUnitcell, structure;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    plugin.behaviors.layout.leftPanelTabName.next('data');
                    src = params.source;
                    asTrajectory = false, format = 'mmcif';
                    switch (src.name) {
                        case 'url':
                            downloadParams = [{ url: src.params.url, isBinary: src.params.isBinary }];
                            format = src.params.format;
                            break;
                        case 'pdb':
                            downloadParams = src.params.provider.server.name === 'pdbe'
                                ? src.params.provider.server.params.variant === 'updated'
                                    ? getDownloadParams(src.params.provider.id, function (id) { return "https://www.ebi.ac.uk/pdbe/static/entry/" + id.toLowerCase() + "_updated.cif"; }, function (id) { return "PDBe: " + id + " (updated cif)"; }, false)
                                    : src.params.provider.server.params.variant === 'updated-bcif'
                                        ? getDownloadParams(src.params.provider.id, function (id) { return "https://www.ebi.ac.uk/pdbe/entry-files/download/" + id.toLowerCase() + ".bcif"; }, function (id) { return "PDBe: " + id + " (updated cif)"; }, true)
                                        : getDownloadParams(src.params.provider.id, function (id) { return "https://www.ebi.ac.uk/pdbe/static/entry/" + id.toLowerCase() + ".cif"; }, function (id) { return "PDBe: " + id + " (cif)"; }, false)
                                : src.params.provider.server.params.encoding === 'cif'
                                    ? getDownloadParams(src.params.provider.id, function (id) { return "https://files.rcsb.org/download/" + id.toUpperCase() + ".cif"; }, function (id) { return "RCSB: " + id + " (cif)"; }, false)
                                    : getDownloadParams(src.params.provider.id, function (id) { return "https://models.rcsb.org/" + id.toUpperCase() + ".bcif"; }, function (id) { return "RCSB: " + id + " (bcif)"; }, true);
                            asTrajectory = !!src.params.options.asTrajectory;
                            break;
                        case 'pdb-dev':
                            downloadParams = getDownloadParams(src.params.provider.id, function (id) {
                                var nId = id.toUpperCase().startsWith('PDBDEV_') ? id : "PDBDEV_" + id.padStart(8, '0');
                                return src.params.provider.encoding === 'bcif'
                                    ? "https://pdb-dev.wwpdb.org/bcif/" + nId.toUpperCase() + ".bcif"
                                    : "https://pdb-dev.wwpdb.org/cif/" + nId.toUpperCase() + ".cif";
                            }, function (id) { return id.toUpperCase().startsWith('PDBDEV_') ? id : "PDBDEV_" + id.padStart(8, '0'); }, src.params.provider.encoding === 'bcif');
                            asTrajectory = !!src.params.options.asTrajectory;
                            break;
                        case 'swissmodel':
                            downloadParams = getDownloadParams(src.params.id, function (id) { return "https://swissmodel.expasy.org/repository/uniprot/" + id.toUpperCase() + ".pdb"; }, function (id) { return "SWISS-MODEL: " + id; }, false);
                            asTrajectory = !!src.params.options.asTrajectory;
                            format = 'pdb';
                            break;
                        case 'pubchem':
                            downloadParams = getDownloadParams(src.params.id, function (id) { return "https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/CID/" + id.trim() + "/record/SDF/?record_type=3d"; }, function (id) { return "PubChem: " + id; }, false);
                            asTrajectory = !!src.params.options.asTrajectory;
                            format = 'mol';
                            break;
                        default: throw new Error(src.name + " not supported.");
                    }
                    representationPreset = params.source.params.options.representation || representation_preset["a" /* PresetStructureRepresentations */].auto.id;
                    showUnitcell = representationPreset !== representation_preset["a" /* PresetStructureRepresentations */].empty.id;
                    structure = src.params.options.type.name === 'auto' ? void 0 : src.params.options.type;
                    return [4 /*yield*/, state.transaction(function () { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
                            var blob, trajectory, _i, downloadParams_1, download, data, trajectory;
                            return Object(tslib_es6["__generator"])(this, function (_a) {
                                switch (_a.label) {
                                    case 0:
                                        if (!(downloadParams.length > 0 && asTrajectory)) return [3 /*break*/, 4];
                                        return [4 /*yield*/, plugin.builders.data.downloadBlob({
                                                sources: downloadParams.map(function (src, i) { return ({ id: '' + i, url: src.url, isBinary: src.isBinary }); }),
                                                maxConcurrency: 6
                                            }, { state: { isGhost: true } })];
                                    case 1:
                                        blob = _a.sent();
                                        return [4 /*yield*/, plugin.builders.structure.parseTrajectory(blob, { formats: downloadParams.map(function (_, i) { return ({ id: '' + i, format: 'cif' }); }) })];
                                    case 2:
                                        trajectory = _a.sent();
                                        return [4 /*yield*/, plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', {
                                                structure: structure,
                                                showUnitcell: showUnitcell,
                                                representationPreset: representationPreset
                                            })];
                                    case 3:
                                        _a.sent();
                                        return [3 /*break*/, 10];
                                    case 4:
                                        _i = 0, downloadParams_1 = downloadParams;
                                        _a.label = 5;
                                    case 5:
                                        if (!(_i < downloadParams_1.length)) return [3 /*break*/, 10];
                                        download = downloadParams_1[_i];
                                        return [4 /*yield*/, plugin.builders.data.download(download, { state: { isGhost: true } })];
                                    case 6:
                                        data = _a.sent();
                                        return [4 /*yield*/, plugin.builders.structure.parseTrajectory(data, format)];
                                    case 7:
                                        trajectory = _a.sent();
                                        return [4 /*yield*/, plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', {
                                                structure: structure,
                                                showUnitcell: showUnitcell,
                                                representationPreset: representationPreset
                                            })];
                                    case 8:
                                        _a.sent();
                                        _a.label = 9;
                                    case 9:
                                        _i++;
                                        return [3 /*break*/, 5];
                                    case 10: return [2 /*return*/];
                                }
                            });
                        }); }).runInContext(ctx)];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
});
function getDownloadParams(src, url, label, isBinary) {
    var ids = src.split(/[,\s]/).map(function (id) { return id.trim(); }).filter(function (id) { return !!id && (id.length >= 4 || /^[1-9][0-9]*$/.test(id)); });
    var ret = [];
    for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
        var id = ids_1[_i];
        ret.push({ url: assets["Asset"].Url(url(id)), isBinary: isBinary, label: label(id) });
    }
    return ret;
}
var UpdateTrajectory = mol_state["StateAction"].build({
    display: { name: 'Update Trajectory' },
    params: {
        action: param_definition["ParamDefinition"].Select('advance', [['advance', 'Advance'], ['reset', 'Reset']]),
        by: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Numeric(1, { min: -1, max: 1, step: 1 }))
    }
})(function (_a) {
    var params = _a.params, state = _a.state;
    var models = state.selectQ(function (q) { return q.ofTransformer(mol_plugin_state_transforms["StateTransforms"].Model.ModelFromTrajectory); });
    var update = state.build();
    if (params.action === 'reset') {
        for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
            var m = models_1[_i];
            update.to(m).update({ modelIndex: 0 });
        }
    }
    else {
        var _loop_1 = function (m) {
            var parent_1 = mol_state["StateSelection"].findAncestorOfType(state.tree, state.cells, m.transform.ref, [objects["a" /* PluginStateObject */].Molecule.Trajectory]);
            if (!parent_1 || !parent_1.obj)
                return "continue";
            var traj = parent_1.obj;
            update.to(m).update(function (old) {
                var modelIndex = (old.modelIndex + params.by) % traj.data.length;
                if (modelIndex < 0)
                    modelIndex += traj.data.length;
                return { modelIndex: modelIndex };
            });
        };
        for (var _b = 0, models_2 = models; _b < models_2.length; _b++) {
            var m = models_2[_b];
            _loop_1(m);
        }
    }
    return state.updateTree(update);
});
var EnableModelCustomProps = mol_state["StateAction"].build({
    display: { name: 'Custom Model Properties', description: 'Enable parameters for custom properties of the model.' },
    from: objects["a" /* PluginStateObject */].Molecule.Model,
    params: function (a, ctx) {
        return ctx.customModelProperties.getParams(a === null || a === void 0 ? void 0 : a.data);
    },
    isApplicable: function (a, t, ctx) {
        return t.transformer !== transforms_model["CustomModelProperties"];
    }
})(function (_a, ctx) {
    var ref = _a.ref, params = _a.params;
    return ctx.builders.structure.insertModelProperties(ref, params);
});
var EnableStructureCustomProps = mol_state["StateAction"].build({
    display: { name: 'Custom Structure Properties', description: 'Enable parameters for custom properties of the structure.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: function (a, ctx) {
        return ctx.customStructureProperties.getParams(a === null || a === void 0 ? void 0 : a.data);
    },
    isApplicable: function (a, t, ctx) {
        return t.transformer !== transforms_model["CustomStructureProperties"];
    }
})(function (_a, ctx) {
    var ref = _a.ref, params = _a.params;
    return ctx.builders.structure.insertStructureProperties(ref, params);
});
var AddTrajectory = mol_state["StateAction"].build({
    display: { name: 'Add Trajectory', description: 'Add trajectory from existing model/topology and coordinates.' },
    from: objects["a" /* PluginStateObject */].Root,
    params: function (a, ctx) {
        var state = ctx.state.data;
        var models = Object(tslib_es6["__spreadArrays"])(state.selectQ(function (q) { return q.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Model); }), state.selectQ(function (q) { return q.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Topology); }));
        var modelOptions = models.map(function (t) { return [t.transform.ref, t.obj.label]; });
        var coords = state.selectQ(function (q) { return q.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Coordinates); });
        var coordOptions = coords.map(function (c) { return [c.transform.ref, c.obj.label]; });
        return {
            model: param_definition["ParamDefinition"].Select(modelOptions.length ? modelOptions[0][0] : '', modelOptions),
            coordinates: param_definition["ParamDefinition"].Select(coordOptions.length ? coordOptions[0][0] : '', coordOptions)
        };
    }
})(function (_a, ctx) {
    var params = _a.params, state = _a.state;
    return mol_task["b" /* Task */].create('Add Trajectory', function (taskCtx) {
        return state.transaction(function () { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
            var dependsOn, model, structure;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        dependsOn = [params.model, params.coordinates];
                        model = state.build().toRoot()
                            .apply(transforms_model["TrajectoryFromModelAndCoordinates"], {
                            modelRef: params.model,
                            coordinatesRef: params.coordinates
                        }, { dependsOn: dependsOn })
                            .apply(mol_plugin_state_transforms["StateTransforms"].Model.ModelFromTrajectory, { modelIndex: 0 });
                        return [4 /*yield*/, state.updateTree(model).runInContext(taskCtx)];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, ctx.builders.structure.createStructure(model.selector)];
                    case 2:
                        structure = _a.sent();
                        return [4 /*yield*/, ctx.builders.structure.representation.applyPreset(structure, 'auto')];
                    case 3:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        }); }).runInContext(taskCtx);
    });
});
//# sourceMappingURL=structure.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/animation.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var animation_AnimationControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(AnimationControls, _super);
    function AnimationControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.updateParams = function (p) {
            var _a;
            _this.plugin.managers.animation.updateParams((_a = {}, _a[p.name] = p.value, _a));
        };
        _this.updateCurrentParams = function (p) {
            var _a;
            _this.plugin.managers.animation.updateCurrentParams((_a = {}, _a[p.name] = p.value, _a));
        };
        _this.startOrStop = function () {
            var anim = _this.plugin.managers.animation;
            if (anim.state.animationState === 'playing')
                anim.stop();
            else {
                if (_this.props.onStart)
                    _this.props.onStart();
                anim.start();
            }
        };
        return _this;
    }
    AnimationControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.animation.events.updated, function () { return _this.forceUpdate(); });
    };
    AnimationControls.prototype.render = function () {
        var _a, _b;
        var anim = this.plugin.managers.animation;
        if (anim.isEmpty)
            return null;
        var isDisabled = anim.state.animationState === 'playing';
        var canApply = (_b = (_a = anim.current.anim).canApply) === null || _b === void 0 ? void 0 : _b.call(_a, this.plugin);
        return react["createElement"](react["Fragment"], null,
            react["createElement"](parameters["ParameterControls"], { params: anim.getParams(), values: anim.state.params, onChange: this.updateParams, isDisabled: isDisabled }),
            react["createElement"](parameters["ParameterControls"], { params: anim.current.params, values: anim.current.paramValues, onChange: this.updateCurrentParams, isDisabled: isDisabled }),
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["Button"], { icon: anim.state.animationState !== 'playing' ? void 0 : icons["PlayArrowSvg"], onClick: this.startOrStop, disabled: canApply !== void 0 && canApply.canApply === false }, anim.state.animationState === 'playing' ? 'Stop' : canApply === void 0 || canApply.canApply ? 'Start' : canApply.reason || 'Start')));
    };
    return AnimationControls;
}(base["PluginUIComponent"]));

//# sourceMappingURL=animation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/components.js + 1 modules
var components = __webpack_require__(322);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/measurements.js
var measurements = __webpack_require__(386);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/selection.js
var structure_selection = __webpack_require__(206);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/source.js + 1 modules
var source = __webpack_require__(391);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/volume.js
var volume = __webpack_require__(371);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/mat4.js
var mat4 = __webpack_require__(105);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/matrix.js
var matrix_matrix = __webpack_require__(64);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/evd.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var evd_EVD;
(function (EVD) {
    function createCache(size) {
        return {
            size: size,
            matrix: matrix_matrix["a" /* default */].create(size, size),
            eigenValues: new Float64Array(size),
            D: new Float64Array(size),
            E: new Float64Array(size)
        };
    }
    EVD.createCache = createCache;
    /**
     * Computes EVD and stores the result in the cache.
     */
    function compute(cache) {
        symmetricEigenDecomp(cache.size, cache.matrix.data, cache.eigenValues, cache.D, cache.E);
    }
    EVD.compute = compute;
})(evd_EVD || (evd_EVD = {}));
// The EVD code has been adapted from Math.NET, MIT license, Copyright (c) 2002-2015 Math.NET
//
// 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 symmetricEigenDecomp(order, matrixEv, vectorEv, d, e) {
    for (var i = 0; i < order; i++) {
        e[i] = 0.0;
    }
    var om1 = order - 1;
    for (var i = 0; i < order; i++) {
        d[i] = matrixEv[i * order + om1];
    }
    symmetricTridiagonalize(matrixEv, d, e, order);
    symmetricDiagonalize(matrixEv, d, e, order);
    for (var i = 0; i < order; i++) {
        vectorEv[i] = d[i];
    }
}
function symmetricTridiagonalize(a, d, e, order) {
    // Householder reduction to tridiagonal form.
    for (var i = order - 1; i > 0; i--) {
        // Scale to avoid under/overflow.
        var scale = 0.0;
        var h = 0.0;
        for (var k = 0; k < i; k++) {
            scale = scale + Math.abs(d[k]);
        }
        if (scale === 0.0) {
            e[i] = d[i - 1];
            for (var j = 0; j < i; j++) {
                d[j] = a[(j * order) + i - 1];
                a[(j * order) + i] = 0.0;
                a[(i * order) + j] = 0.0;
            }
        }
        else {
            // Generate Householder vector.
            for (var k = 0; k < i; k++) {
                d[k] /= scale;
                h += d[k] * d[k];
            }
            var f = d[i - 1];
            var g = Math.sqrt(h);
            if (f > 0) {
                g = -g;
            }
            e[i] = scale * g;
            h = h - (f * g);
            d[i - 1] = f - g;
            for (var j = 0; j < i; j++) {
                e[j] = 0.0;
            }
            // Apply similarity transformation to remaining columns.
            for (var j = 0; j < i; j++) {
                f = d[j];
                a[(i * order) + j] = f;
                g = e[j] + (a[(j * order) + j] * f);
                for (var k = j + 1; k <= i - 1; k++) {
                    g += a[(j * order) + k] * d[k];
                    e[k] += a[(j * order) + k] * f;
                }
                e[j] = g;
            }
            f = 0.0;
            for (var j = 0; j < i; j++) {
                e[j] /= h;
                f += e[j] * d[j];
            }
            var hh = f / (h + h);
            for (var j = 0; j < i; j++) {
                e[j] -= hh * d[j];
            }
            for (var j = 0; j < i; j++) {
                f = d[j];
                g = e[j];
                for (var k = j; k <= i - 1; k++) {
                    a[(j * order) + k] -= (f * e[k]) + (g * d[k]);
                }
                d[j] = a[(j * order) + i - 1];
                a[(j * order) + i] = 0.0;
            }
        }
        d[i] = h;
    }
    // Accumulate transformations.
    for (var i = 0; i < order - 1; i++) {
        a[(i * order) + order - 1] = a[(i * order) + i];
        a[(i * order) + i] = 1.0;
        var h = d[i + 1];
        if (h !== 0.0) {
            for (var k = 0; k <= i; k++) {
                d[k] = a[((i + 1) * order) + k] / h;
            }
            for (var j = 0; j <= i; j++) {
                var g = 0.0;
                for (var k = 0; k <= i; k++) {
                    g += a[((i + 1) * order) + k] * a[(j * order) + k];
                }
                for (var k = 0; k <= i; k++) {
                    a[(j * order) + k] -= g * d[k];
                }
            }
        }
        for (var k = 0; k <= i; k++) {
            a[((i + 1) * order) + k] = 0.0;
        }
    }
    for (var j = 0; j < order; j++) {
        d[j] = a[(j * order) + order - 1];
        a[(j * order) + order - 1] = 0.0;
    }
    a[(order * order) - 1] = 1.0;
    e[0] = 0.0;
}
function symmetricDiagonalize(a, d, e, order) {
    var maxiter = 1000;
    for (var i = 1; i < order; i++) {
        e[i - 1] = e[i];
    }
    e[order - 1] = 0.0;
    var f = 0.0;
    var tst1 = 0.0;
    var eps = Math.pow(2, -53); // DoubleWidth = 53
    for (var l = 0; l < order; l++) {
        // Find small subdiagonal element
        tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));
        var m = l;
        while (m < order) {
            if (Math.abs(e[m]) <= eps * tst1) {
                break;
            }
            m++;
        }
        // If m == l, d[l] is an eigenvalue,
        // otherwise, iterate.
        if (m > l) {
            var iter = 0;
            do {
                iter = iter + 1; // (Could check iteration count here.)
                // Compute implicit shift
                var g = d[l];
                var p = (d[l + 1] - g) / (2.0 * e[l]);
                var r = hypotenuse(p, 1.0);
                if (p < 0) {
                    r = -r;
                }
                d[l] = e[l] / (p + r);
                d[l + 1] = e[l] * (p + r);
                var dl1 = d[l + 1];
                var h = g - d[l];
                for (var i = l + 2; i < order; i++) {
                    d[i] -= h;
                }
                f = f + h;
                // Implicit QL transformation.
                p = d[m];
                var c = 1.0;
                var c2 = c;
                var c3 = c;
                var el1 = e[l + 1];
                var s = 0.0;
                var s2 = 0.0;
                for (var i = m - 1; i >= l; i--) {
                    c3 = c2;
                    c2 = c;
                    s2 = s;
                    g = c * e[i];
                    h = c * p;
                    r = hypotenuse(p, e[i]);
                    e[i + 1] = s * r;
                    s = e[i] / r;
                    c = p / r;
                    p = (c * d[i]) - (s * g);
                    d[i + 1] = h + (s * ((c * g) + (s * d[i])));
                    // Accumulate transformation.
                    for (var k = 0; k < order; k++) {
                        h = a[((i + 1) * order) + k];
                        a[((i + 1) * order) + k] = (s * a[(i * order) + k]) + (c * h);
                        a[(i * order) + k] = (c * a[(i * order) + k]) - (s * h);
                    }
                }
                p = (-s) * s2 * c3 * el1 * e[l] / dl1;
                e[l] = s * p;
                d[l] = c * p;
                // Check for convergence. If too many iterations have been performed,
                // throw exception that Convergence Failed
                if (iter >= maxiter) {
                    throw 'SVD: Not converging.';
                }
            } while (Math.abs(e[l]) > eps * tst1);
        }
        d[l] = d[l] + f;
        e[l] = 0.0;
    }
    // Sort eigenvalues and corresponding vectors.
    for (var i = 0; i < order - 1; i++) {
        var k = i;
        var p = d[i];
        for (var j = i + 1; j < order; j++) {
            if (d[j] < p) {
                k = j;
                p = d[j];
            }
        }
        if (k !== i) {
            d[k] = d[i];
            d[i] = p;
            for (var j = 0; j < order; j++) {
                p = a[(i * order) + j];
                a[(i * order) + j] = a[(k * order) + j];
                a[(k * order) + j] = p;
            }
        }
    }
}
function hypotenuse(a, b) {
    if (Math.abs(a) > Math.abs(b)) {
        var r = b / a;
        return Math.abs(a) * Math.sqrt(1 + (r * r));
    }
    if (b !== 0.0) {
        var r = a / b;
        return Math.abs(b) * Math.sqrt(1 + (r * r));
    }
    return 0.0;
}
//# sourceMappingURL=evd.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/centroid-helper.js
var centroid_helper = __webpack_require__(195);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/primitives/sphere3d.js
var sphere3d = __webpack_require__(274);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/minimize-rmsd.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var minimize_rmsd_MinimizeRmsd;
(function (MinimizeRmsd) {
    var Positions;
    (function (Positions) {
        function empty(n) {
            return { x: new Float64Array(n), y: new Float64Array(n), z: new Float64Array(n) };
        }
        Positions.empty = empty;
    })(Positions = MinimizeRmsd.Positions || (MinimizeRmsd.Positions = {}));
    function compute(data, result) {
        if (typeof result === 'undefined')
            result = { bTransform: mat4["a" /* default */].zero(), rmsd: 0.0 };
        findMinimalRmsdTransformImpl(new minimize_rmsd_RmsdTransformState(data, result));
        return result;
    }
    MinimizeRmsd.compute = compute;
})(minimize_rmsd_MinimizeRmsd || (minimize_rmsd_MinimizeRmsd = {}));
var minimize_rmsd_RmsdTransformState = /** @class */ (function () {
    function RmsdTransformState(data, into) {
        this.evdCache = evd_EVD.createCache(4);
        this.translateB = mat4["a" /* default */].identity();
        this.rotateB = mat4["a" /* default */].identity();
        this.tempMatrix = mat4["a" /* default */].identity();
        this.a = data.a;
        this.b = data.b;
        if (data.centerA)
            this.centerA = data.centerA;
        else
            this.centerA = data.centerA = centroid_helper["a" /* CentroidHelper */].fromArrays(data.a, Object(sphere3d["a" /* Sphere3D */])()).center;
        if (data.centerB)
            this.centerB = data.centerB;
        else
            this.centerB = data.centerB = centroid_helper["a" /* CentroidHelper */].fromArrays(data.b, Object(sphere3d["a" /* Sphere3D */])()).center;
        this.result = into;
    }
    return RmsdTransformState;
}());
function computeN(state) {
    var N = state.evdCache.matrix;
    matrix_matrix["a" /* default */].makeZero(N);
    var xsA = state.a.x, ysA = state.a.y, zsA = state.a.z;
    var xsB = state.b.x, ysB = state.b.y, zsB = state.b.z;
    var cA = state.centerA;
    var cB = state.centerB;
    var sizeSq = 0.0;
    for (var i = 0, _l = state.a.x.length; i < _l; i++) {
        var aX = xsA[i] - cA[0], aY = ysA[i] - cA[1], aZ = zsA[i] - cA[2];
        var bX = xsB[i] - cB[0], bY = ysB[i] - cB[1], bZ = zsB[i] - cB[2];
        sizeSq += aX * aX + aY * aY + aZ * aZ + bX * bX + bY * bY + bZ * bZ;
        matrix_matrix["a" /* default */].add(N, 0, 0, aX * bX + aY * bY + aZ * bZ);
        matrix_matrix["a" /* default */].add(N, 0, 1, -(aZ * bY) + aY * bZ);
        matrix_matrix["a" /* default */].add(N, 0, 2, aZ * bX - aX * bZ);
        matrix_matrix["a" /* default */].add(N, 0, 3, -(aY * bX) + aX * bY);
        matrix_matrix["a" /* default */].add(N, 1, 0, -(aZ * bY) + aY * bZ);
        matrix_matrix["a" /* default */].add(N, 1, 1, aX * bX - aY * bY - aZ * bZ);
        matrix_matrix["a" /* default */].add(N, 1, 2, aY * bX + aX * bY);
        matrix_matrix["a" /* default */].add(N, 1, 3, aZ * bX + aX * bZ);
        matrix_matrix["a" /* default */].add(N, 2, 0, aZ * bX - aX * bZ);
        matrix_matrix["a" /* default */].add(N, 2, 1, aY * bX + aX * bY);
        matrix_matrix["a" /* default */].add(N, 2, 2, -(aX * bX) + aY * bY - aZ * bZ);
        matrix_matrix["a" /* default */].add(N, 2, 3, aZ * bY + aY * bZ);
        matrix_matrix["a" /* default */].add(N, 3, 0, -(aY * bX) + aX * bY);
        matrix_matrix["a" /* default */].add(N, 3, 1, aZ * bX + aX * bZ);
        matrix_matrix["a" /* default */].add(N, 3, 2, aZ * bY + aY * bZ);
        matrix_matrix["a" /* default */].add(N, 3, 3, -(aX * bX) - aY * bY + aZ * bZ);
        // conjugate instead of transpose.
        // var l = new Quaternion(-a.X, -a.Y, -a.Z, 0).RightMultiplicationToMatrix();
        // l.Transpose();
        // var r = new Quaternion(b.X, b.Y, b.Z, 0).LeftMultiplicationToMatrix();
        // N += l * r;
    }
    return sizeSq;
}
function makeTransformMatrix(state) {
    var ev = state.evdCache.matrix;
    var qX = matrix_matrix["a" /* default */].get(ev, 1, 3);
    var qY = matrix_matrix["a" /* default */].get(ev, 2, 3);
    var qZ = matrix_matrix["a" /* default */].get(ev, 3, 3);
    var qW = matrix_matrix["a" /* default */].get(ev, 0, 3);
    var n1 = 2 * qY * qY;
    var n2 = 2 * qZ * qZ;
    var n3 = 2 * qX * qX;
    var n4 = 2 * qX * qY;
    var n5 = 2 * qW * qZ;
    var n6 = 2 * qX * qZ;
    var n7 = 2 * qW * qY;
    var n8 = 2 * qY * qZ;
    var n9 = 2 * qW * qX;
    var m = state.translateB;
    // translation to center
    mat4["a" /* default */].setValue(m, 0, 3, -state.centerB[0]);
    mat4["a" /* default */].setValue(m, 1, 3, -state.centerB[1]);
    mat4["a" /* default */].setValue(m, 2, 3, -state.centerB[2]);
    m = state.rotateB;
    // rotation
    mat4["a" /* default */].setValue(m, 0, 0, 1 - n1 - n2);
    mat4["a" /* default */].setValue(m, 0, 1, n4 + n5);
    mat4["a" /* default */].setValue(m, 0, 2, n6 - n7);
    mat4["a" /* default */].setValue(m, 1, 0, n4 - n5);
    mat4["a" /* default */].setValue(m, 1, 1, 1 - n3 - n2);
    mat4["a" /* default */].setValue(m, 1, 2, n8 + n9);
    mat4["a" /* default */].setValue(m, 2, 0, n6 + n7);
    mat4["a" /* default */].setValue(m, 2, 1, n8 - n9);
    mat4["a" /* default */].setValue(m, 2, 2, 1 - n3 - n1);
    mat4["a" /* default */].setValue(m, 3, 3, 1);
    mat4["a" /* default */].mul(state.tempMatrix, state.rotateB, state.translateB);
    m = state.translateB;
    // translation to center
    mat4["a" /* default */].setValue(m, 0, 3, state.centerA[0]);
    mat4["a" /* default */].setValue(m, 1, 3, state.centerA[1]);
    mat4["a" /* default */].setValue(m, 2, 3, state.centerA[2]);
    mat4["a" /* default */].mul(state.result.bTransform, state.translateB, state.tempMatrix);
}
function findMinimalRmsdTransformImpl(state) {
    var sizeSq = computeN(state);
    evd_EVD.compute(state.evdCache);
    var rmsd = sizeSq - 2.0 * state.evdCache.eigenValues[3];
    rmsd = rmsd < 0.0 ? 0.0 : Math.sqrt(rmsd / state.a.x.length);
    makeTransformMatrix(state);
    state.result.rmsd = rmsd;
}
//# sourceMappingURL=minimize-rmsd.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/element.js + 3 modules
var structure_element = __webpack_require__(129);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure.js + 5 modules
var structure_structure = __webpack_require__(27);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence/alignment/substitution-matrix.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var aminoacidsX = 'ACDEFGHIKLMNPQRSTVWY';
var aminoacids = 'ARNDCQEGHILKMFPSTWYVBZX';
var blosum62x = [
    [4, 0, -2, -1, -2, 0, -2, -1, -1, -1, -1, -2, -1, -1, -1, 1, 0, 0, -3, -2],
    [0, 9, -3, -4, -2, -3, -3, -1, -3, -1, -1, -3, -3, -3, -3, -1, -1, -1, -2, -2],
    [-2, -3, 6, 2, -3, -1, -1, -3, -1, -4, -3, 1, -1, 0, -2, 0, -1, -3, -4, -3],
    [-1, -4, 2, 5, -3, -2, 0, -3, 1, -3, -2, 0, -1, 2, 0, 0, -1, -2, -3, -2],
    [-2, -2, -3, -3, 6, -3, -1, 0, -3, 0, 0, -3, -4, -3, -3, -2, -2, -1, 1, 3],
    [0, -3, -1, -2, -3, 6, -2, -4, -2, -4, -3, 0, -2, -2, -2, 0, -2, -3, -2, -3],
    [-2, -3, -1, 0, -1, -2, 8, -3, -1, -3, -2, 1, -2, 0, 0, -1, -2, -3, -2, 2],
    [-1, -1, -3, -3, 0, -4, -3, 4, -3, 2, 1, -3, -3, -3, -3, -2, -1, 3, -3, -1],
    [-1, -3, -1, 1, -3, -2, -1, -3, 5, -2, -1, 0, -1, 1, 2, 0, -1, -2, -3, -2],
    [-1, -1, -4, -3, 0, -4, -3, 2, -2, 4, 2, -3, -3, -2, -2, -2, -1, 1, -2, -1],
    [-1, -1, -3, -2, 0, -3, -2, 1, -1, 2, 5, -2, -2, 0, -1, -1, -1, 1, -1, -1],
    [-2, -3, 1, 0, -3, 0, 1, -3, 0, -3, -2, 6, -2, 0, 0, 1, 0, -3, -4, -2],
    [-1, -3, -1, -1, -4, -2, -2, -3, -1, -3, -2, -2, 7, -1, -2, -1, -1, -2, -4, -3],
    [-1, -3, 0, 2, -3, -2, 0, -3, 1, -2, 0, 0, -1, 5, 1, 0, -1, -2, -2, -1],
    [-1, -3, -2, 0, -3, -2, 0, -3, 2, -2, -1, 0, -2, 1, 5, -1, -1, -3, -3, -2],
    [1, -1, 0, 0, -2, 0, -1, -2, 0, -2, -1, 1, -1, 0, -1, 4, 1, -2, -3, -2],
    [0, -1, -1, -1, -2, -2, -2, -1, -1, -1, -1, 0, -1, -1, -1, 1, 5, 0, -2, -2],
    [0, -1, -3, -2, -1, -3, -3, 3, -2, 1, 1, -3, -2, -2, -3, -2, 0, 4, -3, -1],
    [-3, -2, -4, -3, 1, -2, -2, -3, -3, -2, -1, -4, -4, -2, -3, -3, -2, -3, 11, 2],
    [-2, -2, -3, -2, 3, -3, 2, -1, -2, -1, -1, -2, -3, -1, -2, -2, -2, -1, 2, 7] // Y
];
var blosum62 = [
    // A  R  N  D  C  Q  E  G  H  I  L  K  M  F  P  S  T  W  Y  V  B  Z  X
    [4, -1, -2, -2, 0, -1, -1, 0, -2, -1, -1, -1, -1, -2, -1, 1, 0, -3, -2, 0, -2, -1, 0],
    [-1, 5, 0, -2, -3, 1, 0, -2, 0, -3, -2, 2, -1, -3, -2, -1, -1, -3, -2, -3, -1, 0, -1],
    [-2, 0, 6, 1, -3, 0, 0, 0, 1, -3, -3, 0, -2, -3, -2, 1, 0, -4, -2, -3, 3, 0, -1],
    [-2, -2, 1, 6, -3, 0, 2, -1, -1, -3, -4, -1, -3, -3, -1, 0, -1, -4, -3, -3, 4, 1, -1],
    [0, -3, -3, -3, 9, -3, -4, -3, -3, -1, -1, -3, -1, -2, -3, -1, -1, -2, -2, -1, -3, -3, -2],
    [-1, 1, 0, 0, -3, 5, 2, -2, 0, -3, -2, 1, 0, -3, -1, 0, -1, -2, -1, -2, 0, 3, -1],
    [-1, 0, 0, 2, -4, 2, 5, -2, 0, -3, -3, 1, -2, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1],
    [0, -2, 0, -1, -3, -2, -2, 6, -2, -4, -4, -2, -3, -3, -2, 0, -2, -2, -3, -3, -1, -2, -1],
    [-2, 0, 1, -1, -3, 0, 0, -2, 8, -3, -3, -1, -2, -1, -2, -1, -2, -2, 2, -3, 0, 0, -1],
    [-1, -3, -3, -3, -1, -3, -3, -4, -3, 4, 2, -3, 1, 0, -3, -2, -1, -3, -1, 3, -3, -3, -1],
    [-1, -2, -3, -4, -1, -2, -3, -4, -3, 2, 4, -2, 2, 0, -3, -2, -1, -2, -1, 1, -4, -3, -1],
    [-1, 2, 0, -1, -3, 1, 1, -2, -1, -3, -2, 5, -1, -3, -1, 0, -1, -3, -2, -2, 0, 1, -1],
    [-1, -1, -2, -3, -1, 0, -2, -3, -2, 1, 2, -1, 5, 0, -2, -1, -1, -1, -1, 1, -3, -1, -1],
    [-2, -3, -3, -3, -2, -3, -3, -3, -1, 0, 0, -3, 0, 6, -4, -2, -2, 1, 3, -1, -3, -3, -1],
    [-1, -2, -2, -1, -3, -1, -1, -2, -2, -3, -3, -1, -2, -4, 7, -1, -1, -4, -3, -2, -2, -1, -2],
    [1, -1, 1, 0, -1, 0, 0, 0, -1, -2, -2, 0, -1, -2, -1, 4, 1, -3, -2, -2, 0, 0, 0],
    [0, -1, 0, -1, -1, -1, -1, -2, -2, -1, -1, -1, -1, -2, -1, 1, 5, -2, -2, 0, -1, -1, 0],
    [-3, -3, -4, -4, -2, -2, -3, -2, -2, -3, -2, -3, -1, 1, -4, -3, -2, 11, 2, -3, -4, -3, -2],
    [-2, -2, -2, -3, -2, -1, -2, -3, 2, -1, -1, -2, -1, 3, -3, -2, -2, 2, 7, -1, -3, -2, -1],
    [0, -3, -3, -3, -1, -2, -2, -3, -3, 3, 1, -2, 1, -1, -2, -2, 0, -3, -1, 4, -3, -2, -1],
    [-2, -1, 3, 4, -3, 0, 1, -1, 0, -3, -4, 0, -3, -3, -2, 0, -1, -4, -3, -3, 4, 1, -1],
    [-1, 0, 0, 1, -3, 3, 4, -2, 0, -3, -3, 1, -1, -3, -1, 0, -1, -3, -2, -2, 1, 4, -1],
    [0, -1, -1, -1, -2, -1, -1, -1, -1, -1, -1, -1, -1, -1, -2, 0, 0, -2, -1, -1, -1, -1, -1] // X
];
function prepareMatrix(cellNames, mat) {
    var j;
    var i = 0;
    var matDict = {};
    mat.forEach(function (row) {
        j = 0;
        var rowDict = {};
        row.forEach(function (elm) { return rowDict[cellNames[j++]] = elm; });
        matDict[cellNames[i++]] = rowDict;
    });
    return matDict;
}
var SubstitutionMatrices = (function () { return ({
    blosum62: prepareMatrix(aminoacids, blosum62),
    blosum62x: prepareMatrix(aminoacidsX, blosum62x)
}); })();
//# sourceMappingURL=substitution-matrix.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence/alignment/alignment.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var DefaultAlignmentOptions = {
    gapPenalty: -11,
    gapExtensionPenalty: -1,
    substMatrix: 'default'
};
function align(seqA, seqB, options) {
    if (options === void 0) { options = {}; }
    var o = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultAlignmentOptions), options);
    var alignment = new alignment_Alignment(seqA, seqB, o);
    alignment.calculate();
    return alignment.trace();
}
var alignment_Alignment = /** @class */ (function () {
    function Alignment(seqA, seqB, options) {
        this.seqA = seqA;
        this.seqB = seqB;
        this.S = [];
        this.V = [];
        this.H = [];
        this.gapPenalty = options.gapPenalty;
        this.gapExtensionPenalty = options.gapExtensionPenalty;
        this.substMatrix = options.substMatrix === 'default' ? undefined : SubstitutionMatrices[options.substMatrix];
        this.n = this.seqA.length;
        this.m = this.seqB.length;
    }
    Alignment.prototype.initMatrices = function () {
        var _a = this, n = _a.n, m = _a.m, gapPenalty = _a.gapPenalty, S = _a.S, V = _a.V, H = _a.H;
        for (var i = 0; i <= n; ++i) {
            S[i] = [], V[i] = [], H[i] = [];
            for (var j = 0; j <= m; ++j) {
                S[i][j] = 0, V[i][j] = 0, H[i][j] = 0;
            }
        }
        for (var i = 0; i <= n; ++i) {
            S[i][0] = gapPenalty;
            H[i][0] = -Infinity;
        }
        for (var j = 0; j <= m; ++j) {
            S[0][j] = gapPenalty;
            V[0][j] = -Infinity;
        }
        S[0][0] = 0;
    };
    Alignment.prototype.makeScoreFn = function () {
        var _a = this, seqA = _a.seqA, seqB = _a.seqB, substMatrix = _a.substMatrix;
        if (substMatrix) {
            return function score(i, j) {
                var _a, _b;
                var cA = seqA[i];
                var cB = seqB[j];
                return (_b = (_a = substMatrix[cA]) === null || _a === void 0 ? void 0 : _a[cB]) !== null && _b !== void 0 ? _b : -4;
            };
        }
        else {
            return function scoreNoSubstMat(i, j) {
                var cA = seqA[i];
                var cB = seqB[j];
                return cA === cB ? 5 : -3;
            };
        }
    };
    Alignment.prototype.calculate = function () {
        this.initMatrices();
        var scoreFn = this.makeScoreFn();
        var _a = this, V = _a.V, H = _a.H, S = _a.S, n = _a.n, m = _a.m, gapExtensionPenalty = _a.gapExtensionPenalty, gapPenalty = _a.gapPenalty;
        var Vi1, Si1, Vi, Hi, Si;
        for (var i = 1; i <= n; ++i) {
            Si1 = S[i - 1], Vi1 = V[i - 1];
            Vi = V[i], Hi = H[i], Si = S[i];
            for (var j = 1; j <= m; ++j) {
                Vi[j] = Math.max(Si1[j] + gapPenalty, Vi1[j] + gapExtensionPenalty);
                Hi[j] = Math.max(Si[j - 1] + gapPenalty, Hi[j - 1] + gapExtensionPenalty);
                Si[j] = Math.max(Si1[j - 1] + scoreFn(i - 1, j - 1), // match
                Vi[j], // del
                Hi[j] // ins
                );
            }
        }
    };
    Alignment.prototype.trace = function () {
        var scoreFn = this.makeScoreFn();
        var _a = this, V = _a.V, H = _a.H, S = _a.S, seqA = _a.seqA, seqB = _a.seqB, gapExtensionPenalty = _a.gapExtensionPenalty, gapPenalty = _a.gapPenalty;
        var i = this.n;
        var j = this.m;
        var mat;
        var score;
        var aliA = '';
        var aliB = '';
        if (S[i][j] >= V[i][j]) {
            mat = 'S';
            score = S[i][j];
        }
        else if (V[i][j] >= H[i][j]) {
            mat = 'V';
            score = V[i][j];
        }
        else {
            mat = 'H';
            score = H[i][j];
        }
        while (i > 0 && j > 0) {
            if (mat === 'S') {
                if (S[i][j] === S[i - 1][j - 1] + scoreFn(i - 1, j - 1)) {
                    aliA = seqA[i - 1] + aliA;
                    aliB = seqB[j - 1] + aliB;
                    --i;
                    --j;
                    mat = 'S';
                }
                else if (S[i][j] === V[i][j]) {
                    mat = 'V';
                }
                else if (S[i][j] === H[i][j]) {
                    mat = 'H';
                }
                else {
                    --i;
                    --j;
                }
            }
            else if (mat === 'V') {
                if (V[i][j] === V[i - 1][j] + gapExtensionPenalty) {
                    aliA = seqA[i - 1] + aliA;
                    aliB = '-' + aliB;
                    --i;
                    mat = 'V';
                }
                else if (V[i][j] === S[i - 1][j] + gapPenalty) {
                    aliA = seqA[i - 1] + aliA;
                    aliB = '-' + aliB;
                    --i;
                    mat = 'S';
                }
                else {
                    --i;
                }
            }
            else if (mat === 'H') {
                if (H[i][j] === H[i][j - 1] + gapExtensionPenalty) {
                    aliA = '-' + aliA;
                    aliB = seqB[j - 1] + aliB;
                    --j;
                    mat = 'H';
                }
                else if (H[i][j] === S[i][j - 1] + gapPenalty) {
                    aliA = '-' + aliA;
                    aliB = seqB[j - 1] + aliB;
                    --j;
                    mat = 'S';
                }
                else {
                    --j;
                }
            }
        }
        while (i > 0) {
            aliA = seqA[i - 1] + aliA;
            aliB = '-' + aliB;
            --i;
        }
        while (j > 0) {
            aliA = '-' + aliA;
            aliB = seqB[j - 1] + aliB;
            --j;
        }
        return { aliA: aliA, aliB: aliB, score: score };
    };
    return Alignment;
}());
//# sourceMappingURL=alignment.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence/alignment/sequence.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var sequence_AlignSequences;
(function (AlignSequences) {
    function createSeqIdIndicesMap(element) {
        var seqIds = new Map();
        if (structure_structure["g" /* Unit */].isAtomic(element.unit)) {
            var label_seq_id = element.unit.model.atomicHierarchy.residues.label_seq_id;
            var residueIndex = element.unit.residueIndex;
            for (var i = 0, il = mol_data_int["OrderedSet"].size(element.indices); i < il; ++i) {
                var uI = mol_data_int["OrderedSet"].getAt(element.indices, i);
                var eI = element.unit.elements[uI];
                var seqId = label_seq_id.value(residueIndex[eI]);
                if (seqIds.has(seqId))
                    seqIds.get(seqId).push(uI);
                else
                    seqIds.set(seqId, [uI]);
            }
        }
        else if (structure_structure["g" /* Unit */].isCoarse(element.unit)) {
            var seq_id_begin = (structure_structure["g" /* Unit */].isSpheres(element.unit)
                ? element.unit.model.coarseHierarchy.spheres
                : element.unit.model.coarseHierarchy.gaussians).seq_id_begin;
            for (var i = 0, il = mol_data_int["OrderedSet"].size(element.indices); i < il; ++i) {
                var uI = mol_data_int["OrderedSet"].getAt(element.indices, i);
                var eI = element.unit.elements[uI];
                var seqId = seq_id_begin.value(eI);
                seqIds.set(seqId, [uI]);
            }
        }
        return seqIds;
    }
    function compute(input, options) {
        if (options === void 0) { options = {}; }
        var seqA = getSequence(input.a.unit);
        var seqB = getSequence(input.b.unit);
        var seqIdIndicesA = createSeqIdIndicesMap(input.a);
        var seqIdIndicesB = createSeqIdIndicesMap(input.b);
        var indicesA = [];
        var indicesB = [];
        var _a = align(seqA.code.toArray(), seqB.code.toArray(), options), aliA = _a.aliA, aliB = _a.aliB, score = _a.score;
        var seqIdxA = 0, seqIdxB = 0;
        for (var i = 0, il = aliA.length; i < il; ++i) {
            if (aliA[i] === '-' || aliB[i] === '-') {
                if (aliA[i] !== '-')
                    seqIdxA += 1;
                if (aliB[i] !== '-')
                    seqIdxB += 1;
                continue;
            }
            var seqIdA = seqA.seqId.value(seqIdxA);
            var seqIdB = seqB.seqId.value(seqIdxB);
            if (seqIdIndicesA.has(seqIdA) && seqIdIndicesB.has(seqIdB)) {
                var iA = seqIdIndicesA.get(seqIdA);
                var iB = seqIdIndicesB.get(seqIdB);
                // use min length to guard against alternate locations
                for (var j = 0, jl = Math.min(iA.length, iB.length); j < jl; ++j) {
                    indicesA.push(iA[j]);
                    indicesB.push(iB[j]);
                }
            }
            seqIdxA += 1, seqIdxB += 1;
        }
        var outA = mol_data_int["OrderedSet"].intersect(mol_data_int["OrderedSet"].ofSortedArray(indicesA), input.a.indices);
        var outB = mol_data_int["OrderedSet"].intersect(mol_data_int["OrderedSet"].ofSortedArray(indicesB), input.b.indices);
        return {
            a: { unit: input.a.unit, indices: outA },
            b: { unit: input.b.unit, indices: outB },
            score: score
        };
    }
    AlignSequences.compute = compute;
})(sequence_AlignSequences || (sequence_AlignSequences = {}));
function entityKey(unit) {
    switch (unit.kind) {
        case 0 /* Atomic */:
            return unit.model.atomicHierarchy.index.getEntityFromChain(unit.chainIndex[unit.elements[0]]);
        case 1 /* Spheres */:
            return unit.model.coarseHierarchy.spheres.entityKey[unit.elements[0]];
        case 2 /* Gaussians */:
            return unit.model.coarseHierarchy.gaussians.entityKey[unit.elements[0]];
    }
}
function getSequence(unit) {
    return unit.model.sequence.byEntityKey[entityKey(unit)].sequence;
}
//# sourceMappingURL=sequence.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/properties.js
var properties = __webpack_require__(168);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/util/superposition.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






function superpose(xs) {
    var ret = [];
    if (xs.length <= 0)
        return ret;
    var n = getMinSize(xs);
    var input = {
        a: getPositionTable(xs[0], n),
        b: getPositionTable(xs[1], n)
    };
    ret[0] = minimize_rmsd_MinimizeRmsd.compute(input);
    for (var i = 2; i < xs.length; i++) {
        input.b = getPositionTable(xs[i], n);
        input.centerB = void 0;
        ret.push(minimize_rmsd_MinimizeRmsd.compute(input));
    }
    return ret;
}
var reProtein = /(polypeptide|cyclic-pseudo-peptide)/i;
function alignAndSuperpose(xs) {
    var ret = [];
    if (xs.length <= 0)
        return ret;
    var l = structure_element["a" /* default */].Loci.getFirstLocation(xs[0]);
    var subtype = properties["a" /* default */].entity.subtype(l);
    var substMatrix = subtype.match(reProtein) ? 'blosum62' : 'default';
    for (var i = 1; i < xs.length; i++) {
        var _a = sequence_AlignSequences.compute({
            a: xs[0].elements[0],
            b: xs[i].elements[0],
        }, { substMatrix: substMatrix }), a = _a.a, b = _a.b, score = _a.score;
        var lociA = structure_element["a" /* default */].Loci(xs[0].structure, [a]);
        var lociB = structure_element["a" /* default */].Loci(xs[i].structure, [b]);
        var n = mol_data_int["OrderedSet"].size(a.indices);
        ret.push(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, minimize_rmsd_MinimizeRmsd.compute({
            a: getPositionTable(lociA, n),
            b: getPositionTable(lociB, n)
        })), { alignmentScore: score }));
    }
    return ret;
}
function getPositionTable(xs, n) {
    var ret = minimize_rmsd_MinimizeRmsd.Positions.empty(n);
    var o = 0;
    for (var _a = 0, _b = xs.elements; _a < _b.length; _a++) {
        var u = _b[_a];
        var unit = u.unit, indices = u.indices;
        var elements = unit.elements;
        var _c = unit.conformation, x = _c.x, y = _c.y, z = _c.z;
        for (var i = 0, _i = mol_data_int["OrderedSet"].size(indices); i < _i; i++) {
            var e = elements[mol_data_int["OrderedSet"].getAt(indices, i)];
            ret.x[o] = x(e);
            ret.y[o] = y(e);
            ret.z[o] = z(e);
            o++;
            if (o >= n)
                break;
        }
        if (o >= n)
            break;
    }
    return ret;
}
function getMinSize(xs) {
    if (xs.length === 0)
        return 0;
    var s = structure_element["a" /* default */].Loci.size(xs[0]);
    for (var i = 1; i < xs.length; i++) {
        var t = structure_element["a" /* default */].Loci.size(xs[i]);
        if (t < s)
            s = t;
    }
    return s;
}
//# sourceMappingURL=superposition.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-selection-query.js
var structure_selection_query = __webpack_require__(80);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string.js
var string = __webpack_require__(41);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/superposition.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var superposition_StructureSuperpositionControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureSuperpositionControls, _super);
    function StructureSuperpositionControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    StructureSuperpositionControls.prototype.defaultState = function () {
        return {
            isCollapsed: false,
            header: 'Superposition',
            brand: { accent: 'gray', svg: icons["SuperpositionSvg"] },
            isHidden: true
        };
    };
    StructureSuperpositionControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (sel) {
            _this.setState({ isHidden: sel.structures.length < 2 });
        });
    };
    StructureSuperpositionControls.prototype.renderControls = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"](superposition_SuperpositionControls, null));
    };
    return StructureSuperpositionControls;
}(base["CollapsableControls"]));

var StructureSuperpositionParams = {
    alignSequences: param_definition["ParamDefinition"].Boolean(true, { isEssential: true, description: 'Perform a sequence alignment and use the aligned residue pairs to guide the 3D superposition.' }),
};
var DefaultStructureSuperpositionOptions = param_definition["ParamDefinition"].getDefaultValues(StructureSuperpositionParams);
var SuperpositionTag = 'SuperpositionTransform';
;
;
var superposition_SuperpositionControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SuperpositionControls, _super);
    function SuperpositionControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isBusy: false,
            action: undefined,
            options: DefaultStructureSuperpositionOptions
        };
        _this.superposeChains = function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var query, entries, traceLocis, transforms, eA, i, il, eB, _a, bTransform, rmsd, labelA, labelB;
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        query = structure_selection_query["b" /* StructureSelectionQueries */].trace.query;
                        entries = this.chainEntries;
                        traceLocis = entries.map(function (e, i) {
                            var s = mol_model_structure["StructureElement"].Loci.toStructure(e.loci);
                            var loci = mol_model_structure["StructureSelection"].toLociWithSourceUnits(query(new mol_model_structure["QueryContext"](s)));
                            return mol_model_structure["StructureElement"].Loci.remap(loci, i === 0
                                ? _this.plugin.helpers.substructureParent.get(e.loci.structure.root).obj.data
                                : loci.structure.root);
                        });
                        transforms = this.state.options.alignSequences
                            ? alignAndSuperpose(traceLocis)
                            : superpose(traceLocis);
                        eA = entries[0];
                        i = 1, il = traceLocis.length;
                        _b.label = 1;
                    case 1:
                        if (!(i < il)) return [3 /*break*/, 4];
                        eB = entries[i];
                        _a = transforms[i - 1], bTransform = _a.bTransform, rmsd = _a.rmsd;
                        return [4 /*yield*/, this.transform(eB.cell, bTransform)];
                    case 2:
                        _b.sent();
                        labelA = Object(string["e" /* stripTags */])(eA.label);
                        labelB = Object(string["e" /* stripTags */])(eB.label);
                        this.plugin.log.info("Superposed [" + labelA + "] and [" + labelB + "] with RMSD " + rmsd.toFixed(2) + ".");
                        _b.label = 3;
                    case 3:
                        ++i;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        _this.superposeAtoms = function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var entries, atomLocis, transforms, eA, i, il, eB, _a, bTransform, rmsd, labelA, labelB, count;
            var _this = this;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        entries = this.atomEntries;
                        atomLocis = entries.map(function (e, i) {
                            return mol_model_structure["StructureElement"].Loci.remap(e.loci, i === 0
                                ? _this.plugin.helpers.substructureParent.get(e.loci.structure.root).obj.data
                                : e.loci.structure.root);
                        });
                        transforms = superpose(atomLocis);
                        eA = entries[0];
                        i = 1, il = atomLocis.length;
                        _b.label = 1;
                    case 1:
                        if (!(i < il)) return [3 /*break*/, 4];
                        eB = entries[i];
                        _a = transforms[i - 1], bTransform = _a.bTransform, rmsd = _a.rmsd;
                        return [4 /*yield*/, this.transform(eB.cell, bTransform)];
                    case 2:
                        _b.sent();
                        labelA = Object(string["e" /* stripTags */])(eA.label);
                        labelB = Object(string["e" /* stripTags */])(eB.label);
                        count = entries[i].atoms.length;
                        this.plugin.log.info("Superposed " + count + " " + (count === 1 ? 'atom' : 'atoms') + " of [" + labelA + "] and [" + labelB + "] with RMSD " + rmsd.toFixed(2) + ".");
                        _b.label = 3;
                    case 3:
                        ++i;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        _this.toggleByChains = function () { return _this.setState({ action: _this.state.action === 'byChains' ? void 0 : 'byChains' }); };
        _this.toggleByAtoms = function () { return _this.setState({ action: _this.state.action === 'byAtoms' ? void 0 : 'byAtoms' }); };
        _this.toggleOptions = function () { return _this.setState({ action: _this.state.action === 'options' ? void 0 : 'options' }); };
        _this.setOptions = function (values) {
            _this.setState({ options: values });
        };
        return _this;
    }
    SuperpositionControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.selection.events.changed, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.selection.events.additionsHistoryUpdated, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(SuperpositionControls.prototype, "selection", {
        get: function () {
            return this.plugin.managers.structure.selection;
        },
        enumerable: false,
        configurable: true
    });
    SuperpositionControls.prototype.transform = function (s, matrix) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var r, o, params, b;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        r = mol_state["StateObjectRef"].resolveAndCheck(this.plugin.state.data, s);
                        if (!r)
                            return [2 /*return*/];
                        o = mol_state["StateSelection"].findTagInSubtree(this.plugin.state.data.tree, r.transform.ref, SuperpositionTag);
                        params = {
                            transform: {
                                name: 'matrix',
                                params: { data: matrix, transpose: false }
                            }
                        };
                        b = o
                            ? this.plugin.state.data.build().to(o).update(params)
                            : this.plugin.state.data.build().to(s)
                                .insert(mol_plugin_state_transforms["StateTransforms"].Model.TransformStructureConformation, params, { tags: SuperpositionTag });
                        return [4 /*yield*/, this.plugin.runTask(this.plugin.state.data.updateTree(b))];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SuperpositionControls.prototype.highlight = function (loci) {
        this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci: loci }, false);
    };
    SuperpositionControls.prototype.moveHistory = function (e, direction) {
        this.plugin.managers.structure.selection.modifyHistory(e, direction, void 0, true);
    };
    SuperpositionControls.prototype.focusLoci = function (loci) {
        this.plugin.managers.camera.focusLoci(loci);
    };
    SuperpositionControls.prototype.lociEntry = function (e, idx) {
        var _this = this;
        return react["createElement"]("div", { className: 'msp-flex-row', key: idx },
            react["createElement"](common["Button"], { noOverflow: true, title: 'Click to focus. Hover to highlight.', onClick: function () { return _this.focusLoci(e.loci); }, style: { width: 'auto', textAlign: 'left' }, onMouseEnter: function () { return _this.highlight(e.loci); }, onMouseLeave: this.plugin.managers.interactivity.lociHighlights.clearHighlights },
                react["createElement"]("span", { dangerouslySetInnerHTML: { __html: e.label } })));
    };
    SuperpositionControls.prototype.historyEntry = function (e, idx) {
        var _this = this;
        var history = this.plugin.managers.structure.selection.additionsHistory;
        return react["createElement"]("div", { className: 'msp-flex-row', key: e.id },
            react["createElement"](common["Button"], { noOverflow: true, title: 'Click to focus. Hover to highlight.', onClick: function () { return _this.focusLoci(e.loci); }, style: { width: 'auto', textAlign: 'left' }, onMouseEnter: function () { return _this.highlight(e.loci); }, onMouseLeave: this.plugin.managers.interactivity.lociHighlights.clearHighlights },
                idx,
                ". ",
                react["createElement"]("span", { dangerouslySetInnerHTML: { __html: e.label } })),
            history.length > 1 && react["createElement"](common["IconButton"], { svg: icons["ArrowUpwardSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.moveHistory(e, 'up'); }, flex: '20px', title: 'Move up' }),
            history.length > 1 && react["createElement"](common["IconButton"], { svg: icons["ArrowDownwardSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.moveHistory(e, 'down'); }, flex: '20px', title: 'Move down' }),
            react["createElement"](common["IconButton"], { svg: icons["DeleteOutlinedSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.plugin.managers.structure.selection.modifyHistory(e, 'remove'); }, flex: true, title: 'Remove' }));
    };
    SuperpositionControls.prototype.atomsLociEntry = function (e, idx) {
        var _this = this;
        return react["createElement"]("div", { key: idx },
            react["createElement"]("div", { className: 'msp-control-group-header' },
                react["createElement"]("div", { className: 'msp-no-overflow', title: e.label }, e.label)),
            react["createElement"]("div", { className: 'msp-control-offset' }, e.atoms.map(function (h, i) { return _this.historyEntry(h, i); })));
    };
    Object.defineProperty(SuperpositionControls.prototype, "chainEntries", {
        get: function () {
            var _this = this;
            var location = mol_model_structure["StructureElement"].Location.create();
            var entries = [];
            this.plugin.managers.structure.selection.entries.forEach(function (_a, ref) {
                var selection = _a.selection;
                var cell = mol_state["StateObjectRef"].resolveAndCheck(_this.plugin.state.data, ref);
                if (!cell || mol_model_structure["StructureElement"].Loci.isEmpty(selection))
                    return;
                // only single polymer chain selections
                var l = mol_model_structure["StructureElement"].Loci.getFirstLocation(selection, location);
                if (selection.elements.length > 1 || mol_model_structure["StructureProperties"].entity.type(l) !== 'polymer')
                    return;
                var stats = mol_model_structure["StructureElement"].Stats.ofLoci(selection);
                var counts = Object(mol_theme_label["structureElementStatsLabel"])(stats, { countsOnly: true });
                var chain = Object(mol_theme_label["elementLabel"])(l, { reverse: true, granularity: 'chain' }).split('|');
                var label = counts + " | " + chain[0] + " | " + chain[chain.length - 1];
                entries.push({ loci: selection, label: label, cell: cell });
            });
            return entries;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SuperpositionControls.prototype, "atomEntries", {
        get: function () {
            var _this = this;
            var structureEntries = new Map();
            var history = this.plugin.managers.structure.selection.additionsHistory;
            for (var i = 0, il = history.length; i < il; ++i) {
                var e = history[i];
                if (mol_model_structure["StructureElement"].Loci.size(e.loci) !== 1)
                    continue;
                var k = e.loci.structure;
                if (structureEntries.has(k))
                    structureEntries.get(k).push(e);
                else
                    structureEntries.set(k, [e]);
            }
            var entries = [];
            structureEntries.forEach(function (atoms, structure) {
                var cell = _this.plugin.helpers.substructureParent.get(structure);
                var elements = [];
                for (var i = 0, il = atoms.length; i < il; ++i) {
                    // note, we don't do loci union here to keep order of selected atoms
                    // for atom pairing during superposition
                    elements.push(atoms[i].loci.elements[0]);
                }
                var loci = mol_model_structure["StructureElement"].Loci(atoms[0].loci.structure, elements);
                var label = loci.structure.label.split(' | ')[0];
                entries.push({ loci: loci, label: label, cell: cell, atoms: atoms });
            });
            return entries;
        },
        enumerable: false,
        configurable: true
    });
    SuperpositionControls.prototype.addByChains = function () {
        var _this = this;
        var entries = this.chainEntries;
        return react["createElement"](react["Fragment"], null,
            entries.length > 0 && react["createElement"]("div", { className: 'msp-control-offset' }, entries.map(function (e, i) { return _this.lociEntry(e, i); })),
            entries.length < 2 && react["createElement"]("div", { className: 'msp-control-offset msp-help-text' },
                react["createElement"]("div", { className: 'msp-help-description' },
                    react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"], inline: true }),
                    "Add 2 or more selections (toggle ",
                    react["createElement"](structure_selection["ToggleSelectionModeButton"], { inline: true }),
                    " mode) from separate structures. Selections must be limited to single polymer chains or residues therein.")),
            entries.length > 1 && react["createElement"](common["Button"], { title: 'Superpose structures by selected chains.', className: 'msp-btn-commit msp-btn-commit-on', onClick: this.superposeChains, style: { marginTop: '1px' } }, "Superpose"));
    };
    SuperpositionControls.prototype.addByAtoms = function () {
        var _this = this;
        var entries = this.atomEntries;
        return react["createElement"](react["Fragment"], null,
            entries.length > 0 && react["createElement"]("div", { className: 'msp-control-offset' }, entries.map(function (e, i) { return _this.atomsLociEntry(e, i); })),
            entries.length < 2 && react["createElement"]("div", { className: 'msp-control-offset msp-help-text' },
                react["createElement"]("div", { className: 'msp-help-description' },
                    react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"], inline: true }),
                    "Add 1 or more selections (toggle ",
                    react["createElement"](structure_selection["ToggleSelectionModeButton"], { inline: true }),
                    " mode) from separate structures. Selections must be limited to single atoms.")),
            entries.length > 1 && react["createElement"](common["Button"], { title: 'Superpose structures by selected atoms.', className: 'msp-btn-commit msp-btn-commit-on', onClick: this.superposeAtoms, style: { marginTop: '1px' } }, "Superpose"));
    };
    SuperpositionControls.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["ToggleButton"], { icon: icons["SuperposeChainsSvg"], label: 'By Chains', toggle: this.toggleByChains, isSelected: this.state.action === 'byChains', disabled: this.state.isBusy }),
                react["createElement"](common["ToggleButton"], { icon: icons["SuperposeAtomsSvg"], label: 'By Atoms', toggle: this.toggleByAtoms, isSelected: this.state.action === 'byAtoms', disabled: this.state.isBusy }),
                react["createElement"](common["ToggleButton"], { icon: icons["TuneSvg"], label: '', title: 'Options', toggle: this.toggleOptions, isSelected: this.state.action === 'options', disabled: this.state.isBusy, style: { flex: '0 0 40px', padding: 0 } })),
            this.state.action === 'byChains' && this.addByChains(),
            this.state.action === 'byAtoms' && this.addByAtoms(),
            this.state.action === 'options' && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](parameters["ParameterControls"], { params: StructureSuperpositionParams, values: this.state.options, onChangeValues: this.setOptions, isDisabled: this.state.isBusy })));
    };
    return SuperpositionControls;
}(base["PurePluginUIComponent"]));

//# sourceMappingURL=superposition.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var controls_TrajectoryViewportControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(TrajectoryViewportControls, _super);
    function TrajectoryViewportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { show: false, label: '' };
        _this.update = function () {
            var state = _this.plugin.state.data;
            var models = state.selectQ(function (q) { return q.ofTransformer(mol_plugin_state_transforms["StateTransforms"].Model.ModelFromTrajectory); });
            if (models.length === 0) {
                _this.setState({ show: false });
                return;
            }
            var label = '', count = 0, parents = new Set();
            for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
                var m = models_1[_i];
                if (!m.sourceRef)
                    continue;
                var parent_1 = state.cells.get(m.sourceRef).obj;
                if (!parent_1)
                    continue;
                if (parent_1.data.length > 1) {
                    if (parents.has(m.sourceRef)) {
                        // do not show the controls if there are 2 models of the same trajectory present
                        _this.setState({ show: false });
                        return;
                    }
                    parents.add(m.sourceRef);
                    count++;
                    if (!label) {
                        var idx = m.transform.params.modelIndex;
                        label = "Model " + (idx + 1) + " / " + parent_1.data.length;
                    }
                }
            }
            if (count > 1)
                label = '';
            _this.setState({ show: count > 0, label: label });
        };
        _this.reset = function () { return commands["PluginCommands"].State.ApplyAction(_this.plugin, {
            state: _this.plugin.state.data,
            action: UpdateTrajectory.create({ action: 'reset' })
        }); };
        _this.prev = function () { return commands["PluginCommands"].State.ApplyAction(_this.plugin, {
            state: _this.plugin.state.data,
            action: UpdateTrajectory.create({ action: 'advance', by: -1 })
        }); };
        _this.next = function () { return commands["PluginCommands"].State.ApplyAction(_this.plugin, {
            state: _this.plugin.state.data,
            action: UpdateTrajectory.create({ action: 'advance', by: 1 })
        }); };
        return _this;
    }
    TrajectoryViewportControls.prototype.componentDidMount = function () {
        this.subscribe(this.plugin.state.data.events.changed, this.update);
        this.subscribe(this.plugin.behaviors.state.isAnimating, this.update);
    };
    TrajectoryViewportControls.prototype.render = function () {
        var isAnimating = this.plugin.behaviors.state.isAnimating.value;
        if (!this.state.show || (isAnimating && !this.state.label))
            return null;
        return react["createElement"]("div", { className: 'msp-traj-controls' },
            !isAnimating && react["createElement"](common["IconButton"], { svg: icons["SkipPreviousSvg"], title: 'First Model', onClick: this.reset, disabled: isAnimating }),
            !isAnimating && react["createElement"](common["IconButton"], { svg: icons["NavigateBeforeSvg"], title: 'Previous Model', onClick: this.prev, disabled: isAnimating }),
            !isAnimating && react["createElement"](common["IconButton"], { svg: icons["NavigateNextSvg"], title: 'Next Model', onClick: this.next, disabled: isAnimating }),
            !!this.state.label && react["createElement"]("span", null, this.state.label));
    };
    return TrajectoryViewportControls;
}(base["PluginUIComponent"]));

var controls_StateSnapshotViewportControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StateSnapshotViewportControls, _super);
    function StateSnapshotViewportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isBusy: false, show: true };
        _this.keyUp = function (e) {
            if (!e.ctrlKey || _this.state.isBusy || e.target !== document.body)
                return;
            var snapshots = _this.plugin.managers.snapshot;
            if (e.keyCode === 37) { // left
                if (snapshots.state.isPlaying)
                    snapshots.stop();
                _this.prev();
            }
            else if (e.keyCode === 38) { // up
                if (snapshots.state.isPlaying)
                    snapshots.stop();
                if (snapshots.state.entries.size === 0)
                    return;
                var e_1 = snapshots.state.entries.get(0);
                _this.update(e_1.snapshot.id);
            }
            else if (e.keyCode === 39) { // right
                if (snapshots.state.isPlaying)
                    snapshots.stop();
                _this.next();
            }
            else if (e.keyCode === 40) { // down
                if (snapshots.state.isPlaying)
                    snapshots.stop();
                if (snapshots.state.entries.size === 0)
                    return;
                var e_2 = snapshots.state.entries.get(snapshots.state.entries.size - 1);
                _this.update(e_2.snapshot.id);
            }
        };
        _this.change = function (e) {
            if (e.target.value === 'none')
                return;
            _this.update(e.target.value);
        };
        _this.prev = function () {
            var s = _this.plugin.managers.snapshot;
            var id = s.getNextId(s.state.current, -1);
            if (id)
                _this.update(id);
        };
        _this.next = function () {
            var s = _this.plugin.managers.snapshot;
            var id = s.getNextId(s.state.current, 1);
            if (id)
                _this.update(id);
        };
        _this.togglePlay = function () {
            _this.plugin.managers.snapshot.togglePlay();
        };
        return _this;
    }
    StateSnapshotViewportControls.prototype.componentDidMount = function () {
        var _this = this;
        // TODO: this needs to be diabled when the state is updating!
        this.subscribe(this.plugin.managers.snapshot.events.changed, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (isBusy) { return _this.setState({ isBusy: isBusy }); });
        this.subscribe(this.plugin.behaviors.state.isAnimating, function (isBusy) { return _this.setState({ isBusy: isBusy }); });
        window.addEventListener('keyup', this.keyUp, false);
    };
    StateSnapshotViewportControls.prototype.componentWillUnmount = function () {
        _super.prototype.componentWillUnmount.call(this);
        window.removeEventListener('keyup', this.keyUp, false);
    };
    StateSnapshotViewportControls.prototype.update = function (id) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({ isBusy: true });
                        return [4 /*yield*/, commands["PluginCommands"].State.Snapshots.Apply(this.plugin, { id: id })];
                    case 1:
                        _a.sent();
                        this.setState({ isBusy: false });
                        return [2 /*return*/];
                }
            });
        });
    };
    StateSnapshotViewportControls.prototype.render = function () {
        var snapshots = this.plugin.managers.snapshot;
        var count = snapshots.state.entries.size;
        if (count < 2 || !this.state.show) {
            return null;
        }
        var current = snapshots.state.current;
        var isPlaying = snapshots.state.isPlaying;
        return react["createElement"]("div", { className: 'msp-state-snapshot-viewport-controls' },
            react["createElement"]("select", { className: 'msp-form-control', value: current || 'none', onChange: this.change, disabled: this.state.isBusy || isPlaying },
                !current && react["createElement"]("option", { key: 'none', value: 'none' }),
                snapshots.state.entries.valueSeq().map(function (e, i) { return react["createElement"]("option", { key: e.snapshot.id, value: e.snapshot.id }, "[" + (i + 1) + "/" + count + "]",
                    " ",
                    e.name || new Date(e.timestamp).toLocaleString()); })),
            react["createElement"](common["IconButton"], { svg: isPlaying ? icons["StopSvg"] : icons["PlayArrowSvg"], title: isPlaying ? 'Pause' : 'Cycle States', onClick: this.togglePlay, disabled: isPlaying ? false : this.state.isBusy }),
            !isPlaying && react["createElement"](react["Fragment"], null,
                react["createElement"](common["IconButton"], { svg: icons["NavigateBeforeSvg"], title: 'Previous State', onClick: this.prev, disabled: this.state.isBusy || isPlaying }),
                react["createElement"](common["IconButton"], { svg: icons["NavigateNextSvg"], title: 'Next State', onClick: this.next, disabled: this.state.isBusy || isPlaying })));
    };
    return StateSnapshotViewportControls;
}(base["PluginUIComponent"]));

var controls_AnimationViewportControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(AnimationViewportControls, _super);
    function AnimationViewportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isEmpty: true, isExpanded: false, isBusy: false, isAnimating: false, isPlaying: false };
        _this.toggleExpanded = function () { return _this.setState({ isExpanded: !_this.state.isExpanded }); };
        _this.stop = function () {
            _this.plugin.managers.animation.stop();
            _this.plugin.managers.snapshot.stop();
        };
        return _this;
    }
    AnimationViewportControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.snapshot.events.changed, function () {
            if (_this.plugin.managers.snapshot.state.isPlaying)
                _this.setState({ isPlaying: true, isExpanded: false });
            else
                _this.setState({ isPlaying: false });
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (isBusy) {
            if (isBusy)
                _this.setState({ isBusy: true, isExpanded: false, isEmpty: _this.plugin.state.data.tree.transforms.size < 2 });
            else
                _this.setState({ isBusy: false, isEmpty: _this.plugin.state.data.tree.transforms.size < 2 });
        });
        this.subscribe(this.plugin.behaviors.state.isAnimating, function (isAnimating) {
            if (isAnimating)
                _this.setState({ isAnimating: true, isExpanded: false });
            else
                _this.setState({ isAnimating: false });
        });
    };
    AnimationViewportControls.prototype.render = function () {
        var isPlaying = this.plugin.managers.snapshot.state.isPlaying;
        if (isPlaying || this.state.isEmpty || this.plugin.managers.animation.isEmpty || !this.plugin.config.get(config["PluginConfig"].Viewport.ShowAnimation))
            return null;
        var isAnimating = this.state.isAnimating;
        return react["createElement"]("div", { className: 'msp-animation-viewport-controls' },
            react["createElement"]("div", null,
                react["createElement"]("div", { className: 'msp-semi-transparent-background' }),
                react["createElement"](common["IconButton"], { svg: isAnimating || isPlaying ? icons["StopSvg"] : icons["SubscriptionsOutlinedSvg"], transparent: true, title: isAnimating ? 'Stop' : 'Select Animation', onClick: isAnimating || isPlaying ? this.stop : this.toggleExpanded, toggleState: this.state.isExpanded, disabled: isAnimating || isPlaying ? false : this.state.isBusy || this.state.isPlaying || this.state.isEmpty })),
            (this.state.isExpanded && !this.state.isBusy) && react["createElement"]("div", { className: 'msp-animation-viewport-controls-select' },
                react["createElement"](animation_AnimationControls, { onStart: this.toggleExpanded })));
    };
    return AnimationViewportControls;
}(base["PluginUIComponent"]));

var controls_SelectionViewportControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SelectionViewportControls, _super);
    function SelectionViewportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onMouseMove = function (e) {
            // ignore mouse moves when no button is held
            if (e.buttons === 0)
                e.stopPropagation();
        };
        return _this;
    }
    SelectionViewportControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.interaction.selectionMode, function () { return _this.forceUpdate(); });
    };
    SelectionViewportControls.prototype.render = function () {
        if (!this.plugin.selectionMode)
            return null;
        return react["createElement"]("div", { className: 'msp-selection-viewport-controls', onMouseMove: this.onMouseMove },
            react["createElement"](structure_selection["StructureSelectionActionsControls"], null));
    };
    return SelectionViewportControls;
}(base["PluginUIComponent"]));

var controls_LociLabels = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(LociLabels, _super);
    function LociLabels() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { labels: [] };
        return _this;
    }
    LociLabels.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.labels.highlight, function (e) { return _this.setState({ labels: e.labels }); });
    };
    LociLabels.prototype.render = function () {
        if (this.state.labels.length === 0) {
            return null;
        }
        return react["createElement"]("div", { className: 'msp-highlight-info' }, this.state.labels.map(function (e, i) { return react["createElement"]("div", { key: '' + i, dangerouslySetInnerHTML: { __html: e } }); }));
    };
    return LociLabels;
}(base["PluginUIComponent"]));

var controls_CustomStructureControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(CustomStructureControls, _super);
    function CustomStructureControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    CustomStructureControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.behaviors.events.changed, function () { return _this.forceUpdate(); });
    };
    CustomStructureControls.prototype.render = function () {
        var _this = this;
        var controls = [];
        this.plugin.customStructureControls.forEach(function (Controls, key) {
            controls.push(react["createElement"](Controls, { initiallyCollapsed: _this.props.initiallyCollapsed, key: key }));
        });
        return controls.length > 0 ? react["createElement"](react["Fragment"], null, controls) : null;
    };
    return CustomStructureControls;
}(base["PluginUIComponent"]));

var controls_DefaultStructureTools = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(DefaultStructureTools, _super);
    function DefaultStructureTools() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DefaultStructureTools.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-section-header' },
                react["createElement"](icons["Icon"], { svg: icons["BuildSvg"] }),
                "Structure Tools"),
            react["createElement"](source["StructureSourceControls"], null),
            react["createElement"](measurements["StructureMeasurementsControls"], null),
            react["createElement"](superposition_StructureSuperpositionControls, null),
            react["createElement"](components["StructureComponentControls"], null),
            react["createElement"](volume["VolumeStreamingControls"], null),
            react["createElement"](volume["VolumeSourceControls"], null),
            react["createElement"](controls_CustomStructureControls, null));
    };
    return DefaultStructureTools;
}(base["PluginUIComponent"]));

//# sourceMappingURL=controls.js.map

/***/ }),
/* 272 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export arrayLess */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arraySwap; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return sortArray; });
/* unused harmony export sortArrayRange */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return sort; });
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function arrayLess(arr, i, j) {
    return arr[i] - arr[j];
}
function arraySwap(arr, i, j) {
    var temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
function medianPivotIndex(data, cmp, l, r) {
    var m = (l + r) >> 1;
    if (cmp(data, l, r) > 0)
        return cmp(data, l, m) > 0 ? cmp(data, m, r) > 0 ? m : r : l;
    else
        return cmp(data, r, m) > 0 ? cmp(data, m, l) > 0 ? m : l : r;
}
function partition(ctx, l, r) {
    var cmp = ctx.cmp, swap = ctx.swap, data = ctx.data, parts = ctx.parts;
    var equals = l + 1, tail = r;
    // move the median to the 1st spot
    swap(data, l, medianPivotIndex(data, cmp, l, r));
    while (cmp(data, tail, l) > 0) {
        --tail;
    }
    for (var i = l + 1; i <= tail; i++) {
        var c = cmp(data, i, l);
        if (c > 0) {
            swap(data, i, tail);
            --tail;
            while (cmp(data, tail, l) > 0) {
                --tail;
            }
            i--;
        }
        else if (c === 0) {
            swap(data, i, equals);
            equals++;
        }
    }
    // move the medians to the correct spots
    for (var i = l; i < equals; i++) {
        swap(data, i, l + tail - i);
    }
    parts[0] = tail - equals + l + 1;
    parts[1] = tail;
}
function insertionSort(_a, start, end) {
    var data = _a.data, cmp = _a.cmp, swap = _a.swap;
    for (var i = start + 1; i <= end; i++) {
        var j = i - 1;
        while (j >= start && cmp(data, j, j + 1) > 0) {
            swap(data, j, j + 1);
            j = j - 1;
        }
    }
}
function quickSort(ctx, low, high) {
    var parts = ctx.parts;
    while (low < high) {
        if (high - low < 16) {
            insertionSort(ctx, low, high);
            return;
        }
        partition(ctx, low, high);
        var li = parts[0], ri = parts[1];
        if (li - low < high - ri) {
            quickSort(ctx, low, li - 1);
            low = ri + 1;
        }
        else {
            quickSort(ctx, ri + 1, high);
            high = li - 1;
        }
    }
}
function partitionArrayAsc(data, parts, l, r) {
    var equals = l + 1, tail = r;
    // move the median to the 1st spot
    arraySwap(data, l, medianPivotIndex(data, arrayLess, l, r));
    var pivot = data[l];
    while (data[tail] > pivot) {
        --tail;
    }
    for (var i = l + 1; i <= tail; i++) {
        var v = data[i];
        if (v > pivot) {
            arraySwap(data, i, tail);
            --tail;
            while (data[tail] > pivot) {
                --tail;
            }
            i--;
        }
        else if (v === pivot) {
            arraySwap(data, i, equals);
            ++equals;
        }
    }
    // move all medians to the correct spots
    for (var i = l; i < equals; i++) {
        arraySwap(data, i, l + tail - i);
    }
    parts[0] = tail - equals + l + 1;
    parts[1] = tail;
}
function insertionSortArrayAsc(data, start, end) {
    for (var i = start + 1; i <= end; i++) {
        var key = data[i];
        var j = i - 1;
        while (j >= start && data[j] > key) {
            data[j + 1] = data[j];
            j = j - 1;
        }
        data[j + 1] = key;
    }
}
function quickSortArrayAsc(data, parts, low, high) {
    while (low < high) {
        if (high - low < 16) {
            insertionSortArrayAsc(data, low, high);
            return;
        }
        partitionArrayAsc(data, parts, low, high);
        var li = parts[0], ri = parts[1];
        if (li - low < high - ri) {
            quickSortArrayAsc(data, parts, low, li - 1);
            low = ri + 1;
        }
        else {
            quickSortArrayAsc(data, parts, ri + 1, high);
            high = li - 1;
        }
    }
}
function sortArray(data, cmp) {
    if (cmp === void 0) { cmp = arrayLess; }
    return sortArrayRange(data, 0, data.length, cmp);
}
function sortArrayRange(data, start, end, cmp) {
    if (cmp === void 0) { cmp = arrayLess; }
    if (cmp === arrayLess)
        quickSortArrayAsc(data, [0, 0], start, end - 1);
    else
        quickSort({ data: data, cmp: cmp, swap: arraySwap, parts: [0, 0] }, start, end - 1);
    return data;
}
function sort(data, start, end, cmp, swap) {
    var ctx = { data: data, cmp: cmp, swap: swap, parts: [0, 0] };
    quickSort(ctx, start, end - 1);
    return data;
}
//# sourceMappingURL=sort.js.map

/***/ }),
/* 273 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return pipe; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return pipeFromArray; });
/* harmony import */ var _identity__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(181);
/** PURE_IMPORTS_START _identity PURE_IMPORTS_END */

function pipe() {
    var fns = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        fns[_i] = arguments[_i];
    }
    return pipeFromArray(fns);
}
function pipeFromArray(fns) {
    if (fns.length === 0) {
        return _identity__WEBPACK_IMPORTED_MODULE_0__[/* identity */ "a"];
    }
    if (fns.length === 1) {
        return fns[0];
    }
    return function piped(input) {
        return fns.reduce(function (prev, fn) { return fn(prev); }, input);
    };
}
//# sourceMappingURL=pipe.js.map


/***/ }),
/* 274 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Sphere3D; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(6);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function Sphere3D() {
    return Sphere3D.zero();
}
(function (Sphere3D) {
    function hasExtrema(sphere) {
        return sphere.extrema !== undefined;
    }
    Sphere3D.hasExtrema = hasExtrema;
    function create(center, radius) { return { center: center, radius: radius }; }
    Sphere3D.create = create;
    function zero() { return { center: Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), radius: 0 }; }
    Sphere3D.zero = zero;
    function clone(a) {
        var out = create(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(a.center), a.radius);
        if (hasExtrema(a))
            out.extrema = a.extrema;
        return out;
    }
    Sphere3D.clone = clone;
    function set(out, center, radius) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(out.center, center);
        out.radius = radius;
        return out;
    }
    Sphere3D.set = set;
    function copy(out, a) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(out.center, a.center);
        out.radius = a.radius;
        if (hasExtrema(a))
            setExtrema(out, a.extrema);
        return out;
    }
    Sphere3D.copy = copy;
    function setExtrema(out, extrema) {
        var _a;
        if (out.extrema !== undefined) {
            out.extrema.length = 0;
            (_a = out.extrema).push.apply(_a, extrema);
        }
        else {
            out.extrema = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(extrema);
        }
        return out;
    }
    Sphere3D.setExtrema = setExtrema;
    function computeBounding(data) {
        var x = data.x, y = data.y, z = data.z, indices = data.indices;
        var cx = 0, cy = 0, cz = 0;
        var radiusSq = 0;
        var size = _mol_data_int__WEBPACK_IMPORTED_MODULE_2__["OrderedSet"].size(indices);
        for (var t = 0; t < size; t++) {
            var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_2__["OrderedSet"].getAt(indices, t);
            cx += x[i];
            cy += y[i];
            cz += z[i];
        }
        if (size > 0) {
            cx /= size;
            cy /= size;
            cz /= size;
        }
        for (var t = 0; t < size; t++) {
            var i = _mol_data_int__WEBPACK_IMPORTED_MODULE_2__["OrderedSet"].getAt(indices, t);
            var dx = x[i] - cx, dy = y[i] - cy, dz = z[i] - cz;
            var d = dx * dx + dy * dy + dz * dz;
            if (d > radiusSq)
                radiusSq = d;
        }
        return { center: _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].create(cx, cy, cz), radius: Math.sqrt(radiusSq) };
    }
    Sphere3D.computeBounding = computeBounding;
    /** Transform sphere with a Mat4 */
    function transform(out, sphere, m) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformMat4(out.center, sphere.center, m);
        out.radius = sphere.radius * _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].getMaxScaleOnAxis(m);
        return out;
    }
    Sphere3D.transform = transform;
    function toArray(s, out, offset) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].toArray(s.center, out, offset);
        out[offset + 3] = s.radius;
    }
    Sphere3D.toArray = toArray;
    function fromArray(out, array, offset) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].fromArray(out.center, array, offset);
        out.radius = array[offset + 3];
        return out;
    }
    Sphere3D.fromArray = fromArray;
    function fromBox3D(out, box) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].scale(out.center, _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(out.center, box.max, box.min), 0.5);
        out.radius = _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(out.center, box.max);
        return out;
    }
    Sphere3D.fromBox3D = fromBox3D;
    function fromAxes3D(out, axes) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(out.center, axes.origin);
        out.radius = Math.max(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].magnitude(axes.dirA), _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].magnitude(axes.dirB), _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].magnitude(axes.dirC));
        return out;
    }
    Sphere3D.fromAxes3D = fromAxes3D;
    var tmpAddVec3 = Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
    function addVec3(out, s, v) {
        var d = _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(s.center, v);
        if (d < s.radius)
            return Sphere3D.copy(out, s);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpAddVec3, s.center, v);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpAddVec3, s.center, tmpAddVec3);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(tmpAddVec3, tmpAddVec3, s.radius);
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].scale(out.center, _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(tmpAddVec3, tmpAddVec3, v), 0.5);
        out.radius = _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(out.center, v);
        return out;
    }
    Sphere3D.addVec3 = addVec3;
    /** Expand sphere radius by another sphere */
    function expandBySphere(out, sphere, by) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(out.center, sphere.center);
        out.radius = Math.max(sphere.radius, _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(sphere.center, by.center) + by.radius);
        if (hasExtrema(sphere) && hasExtrema(by)) {
            setExtrema(out, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(sphere.extrema.map(function (e) { return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(e); }), by.extrema.map(function (e) { return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(e); })));
        }
        return out;
    }
    Sphere3D.expandBySphere = expandBySphere;
    var tmpDir = Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
    /** Expand sphere radius by delta */
    function expand(out, sphere, delta) {
        _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(out.center, sphere.center);
        out.radius = sphere.radius + delta;
        if (hasExtrema(sphere)) {
            setExtrema(out, sphere.extrema.map(function (e) {
                _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(tmpDir, e, sphere.center);
                var dist = _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(sphere.center, e);
                _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].normalize(tmpDir, tmpDir);
                return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].scaleAndAdd(Object(_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), sphere.center, tmpDir, dist + delta);
            }));
        }
        return out;
    }
    Sphere3D.expand = expand;
    /**
     * Returns whether or not the spheres have exactly the same center and radius (when compared with ===)
     */
    function exactEquals(a, b) {
        return a.radius === b.radius && _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].exactEquals(a.center, b.center);
    }
    Sphere3D.exactEquals = exactEquals;
    /**
     * Returns whether or not the spheres have approximately the same center and radius.
     */
    function equals(a, b) {
        var ar = a.radius;
        var br = b.radius;
        return (Math.abs(ar - br) <= _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["EPSILON"] * Math.max(1.0, Math.abs(ar), Math.abs(br)) &&
            _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].equals(a.center, b.center));
    }
    Sphere3D.equals = equals;
    /**
     * Check if `a` includes `b`, use `extrema` of `b` when available
     */
    function includes(a, b) {
        if (hasExtrema(b)) {
            for (var _i = 0, _a = b.extrema; _i < _a.length; _i++) {
                var e = _a[_i];
                if (_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(a.center, e) > a.radius)
                    return false;
            }
            return true;
        }
        else {
            return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(a.center, b.center) + b.radius <= a.radius;
        }
    }
    Sphere3D.includes = includes;
    /** Check if `a` and `b` are overlapping */
    function overlaps(a, b) {
        return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(a.center, b.center) <= a.radius + b.radius;
    }
    Sphere3D.overlaps = overlaps;
    /** Get the signed distance of `a` and `b` */
    function distance(a, b) {
        return _linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(a.center, b.center) - a.radius + b.radius;
    }
    Sphere3D.distance = distance;
})(Sphere3D || (Sphere3D = {}));

//# sourceMappingURL=sphere3d.js.map

/***/ }),
/* 275 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Loci; });
/* harmony import */ var _mol_data_generic__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(55);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(1);
/* harmony import */ var _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(10);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(112);
/* harmony import */ var _unit__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(37);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(9);
/* harmony import */ var _location__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(87);
/* harmony import */ var _mol_math_linear_algebra_matrix_principal_axes__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(227);
/* harmony import */ var _properties__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(168);
/* harmony import */ var _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(126);
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











function Loci(structure, elements) {
    return { kind: 'element-loci', structure: structure, elements: elements };
}
(function (Loci) {
    function is(x) {
        return !!x && x.kind === 'element-loci';
    }
    Loci.is = is;
    function areEqual(a, b) {
        if (a.structure !== b.structure)
            return false;
        if (a.elements.length !== b.elements.length)
            return false;
        for (var i = 0, il = a.elements.length; i < il; ++i) {
            var elementA = a.elements[i];
            var elementB = b.elements[i];
            if (elementA.unit.id !== elementB.unit.id)
                return false;
            if (!_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].areEqual(elementA.indices, elementB.indices))
                return false;
        }
        return true;
    }
    Loci.areEqual = areEqual;
    function isEmpty(loci) {
        return size(loci) === 0;
    }
    Loci.isEmpty = isEmpty;
    function isWholeStructure(loci) {
        return size(loci) === loci.structure.elementCount;
    }
    Loci.isWholeStructure = isWholeStructure;
    function size(loci) {
        var s = 0;
        for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
            var u = _b[_a];
            s += _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(u.indices);
        }
        return s;
    }
    Loci.size = size;
    function all(structure) {
        return Loci(structure, structure.units.map(function (unit) { return ({
            unit: unit,
            indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].ofBounds(0, unit.elements.length)
        }); }));
    }
    Loci.all = all;
    function none(structure) {
        return Loci(structure, []);
    }
    Loci.none = none;
    function getFirstLocation(loci, e) {
        if (isEmpty(loci))
            return void 0;
        var unit = loci.elements[0].unit;
        var element = unit.elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(loci.elements[0].indices, 0)];
        if (e) {
            e.structure = loci.structure;
            e.unit = loci.elements[0].unit;
            e.element = element;
            return e;
        }
        return _location__WEBPACK_IMPORTED_MODULE_7__[/* Location */ "a"].create(loci.structure, unit, element);
    }
    Loci.getFirstLocation = getFirstLocation;
    function firstElement(loci) {
        if (isEmpty(loci))
            return loci;
        return Loci(loci.structure, [{
                unit: loci.elements[0].unit,
                indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].ofSingleton(_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].start(loci.elements[0].indices))
            }]);
    }
    Loci.firstElement = firstElement;
    function firstResidue(loci) {
        if (isEmpty(loci))
            return loci;
        return extendToWholeResidues(firstElement(loci));
    }
    Loci.firstResidue = firstResidue;
    function firstChain(loci) {
        if (isEmpty(loci))
            return loci;
        return extendToWholeChains(firstElement(loci));
    }
    Loci.firstChain = firstChain;
    function toStructure(loci) {
        var units = [];
        var _loop_1 = function (e) {
            var unit = e.unit, indices = e.indices;
            var elements = new Int32Array(_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices));
            _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].forEach(indices, function (v, i) { return elements[i] = unit.elements[v]; });
            units.push(unit.getChild(_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].ofSortedArray(elements)));
        };
        for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            _loop_1(e);
        }
        return _structure__WEBPACK_IMPORTED_MODULE_4__[/* default */ "a"].create(units, { parent: loci.structure.parent });
    }
    Loci.toStructure = toStructure;
    // TODO: there should be a version that property supports partitioned units
    function remap(loci, structure) {
        if (structure === loci.structure)
            return loci;
        var elements = [];
        loci.elements.forEach(function (e) {
            if (!structure.unitMap.has(e.unit.id))
                return;
            var unit = structure.unitMap.get(e.unit.id);
            var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].indexedIntersect(e.indices, e.unit.elements, unit.elements);
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices) > 0)
                elements.push({ unit: unit, indices: indices });
        });
        return Loci(structure, elements);
    }
    Loci.remap = remap;
    /** Create union of `xs` and `ys` */
    function union(xs, ys) {
        if (xs.elements.length > ys.elements.length)
            return union(ys, xs);
        if (Loci.isEmpty(xs))
            return ys;
        var map = new Map();
        for (var _a = 0, _b = xs.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            map.set(e.unit.id, e.indices);
        }
        var elements = [];
        for (var _c = 0, _d = ys.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            if (map.has(e.unit.id)) {
                elements[elements.length] = { unit: e.unit, indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].union(map.get(e.unit.id), e.indices) };
                map.delete(e.unit.id);
            }
            else {
                elements[elements.length] = e;
            }
        }
        map.forEach(function (indices, id) {
            elements[elements.length] = { unit: xs.structure.unitMap.get(id), indices: indices };
        });
        return Loci(xs.structure, elements);
    }
    Loci.union = union;
    /** Subtract `ys` from `xs` */
    function subtract(xs, ys) {
        var map = new Map();
        for (var _a = 0, _b = ys.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            map.set(e.unit.id, e.indices);
        }
        var elements = [];
        for (var _c = 0, _d = xs.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            if (map.has(e.unit.id)) {
                var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].subtract(e.indices, map.get(e.unit.id));
                if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices) === 0)
                    continue;
                elements[elements.length] = { unit: e.unit, indices: indices };
            }
            else {
                elements[elements.length] = e;
            }
        }
        return Loci(xs.structure, elements);
    }
    Loci.subtract = subtract;
    /** Intersect `xs` and `ys` */
    function intersect(xs, ys) {
        var map = new Map();
        for (var _a = 0, _b = xs.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            map.set(e.unit.id, e.indices);
        }
        var elements = [];
        for (var _c = 0, _d = ys.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            if (!map.has(e.unit.id))
                continue;
            var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].intersect(map.get(e.unit.id), e.indices);
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices) === 0)
                continue;
            elements[elements.length] = { unit: e.unit, indices: indices };
        }
        return Loci(xs.structure, elements);
    }
    Loci.intersect = intersect;
    function areIntersecting(xs, ys) {
        if (xs.elements.length > ys.elements.length)
            return areIntersecting(ys, xs);
        if (Loci.isEmpty(xs))
            return Loci.isEmpty(ys);
        var map = new Map();
        for (var _a = 0, _b = xs.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            map.set(e.unit.id, e.indices);
        }
        for (var _c = 0, _d = ys.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            if (!map.has(e.unit.id))
                continue;
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].areIntersecting(map.get(e.unit.id), e.indices))
                return true;
        }
        return false;
    }
    Loci.areIntersecting = areIntersecting;
    /** Check if second loci is a subset of the first */
    function isSubset(xs, ys) {
        if (Loci.isEmpty(xs))
            return Loci.isEmpty(ys);
        var map = new Map();
        for (var _a = 0, _b = xs.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            map.set(e.unit.id, e.indices);
        }
        var isSubset = false;
        for (var _c = 0, _d = ys.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            if (!map.has(e.unit.id))
                continue;
            if (!_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].isSubset(map.get(e.unit.id), e.indices))
                return false;
            else
                isSubset = true;
        }
        return isSubset;
    }
    Loci.isSubset = isSubset;
    function extendToWholeResidues(loci, restrictToConformation) {
        var elements = [];
        var residueAltIds = new Set();
        for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
            var lociElement = _b[_a];
            if (isWholeUnit(lociElement)) {
                elements[elements.length] = lociElement;
                continue;
            }
            if (lociElement.unit.kind === 0 /* Atomic */) {
                var unitElements = lociElement.unit.elements;
                var h = lociElement.unit.model.atomicHierarchy;
                var label_alt_id = lociElement.unit.model.atomicHierarchy.atoms.label_alt_id;
                var _c = h.residueAtomSegments, residueIndex = _c.index, residueOffsets = _c.offsets;
                var newIndices = [];
                var indices = lociElement.indices, len = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices);
                var i = 0;
                while (i < len) {
                    residueAltIds.clear();
                    var eI = unitElements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)];
                    var rI = residueIndex[eI];
                    residueAltIds.add(label_alt_id.value(eI));
                    i++;
                    while (i < len) {
                        var eI_1 = unitElements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)];
                        if (residueIndex[eI_1] !== rI)
                            break;
                        residueAltIds.add(label_alt_id.value(eI_1));
                        i++;
                    }
                    var hasSharedAltId = residueAltIds.has('');
                    for (var j = residueOffsets[rI], _j = residueOffsets[rI + 1]; j < _j; j++) {
                        var idx = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].indexOf(unitElements, j);
                        if (idx >= 0) {
                            var altId = label_alt_id.value(j);
                            if (!restrictToConformation || hasSharedAltId || !altId || residueAltIds.has(altId)) {
                                newIndices[newIndices.length] = idx;
                            }
                        }
                    }
                }
                elements[elements.length] = { unit: lociElement.unit, indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].ofSortedArray(newIndices) };
            }
            else {
                // coarse elements are already by-residue
                elements[elements.length] = lociElement;
            }
        }
        return Loci(loci.structure, elements);
    }
    Loci.extendToWholeResidues = extendToWholeResidues;
    function getChainSegments(unit) {
        switch (unit.kind) {
            case 0 /* Atomic */: return unit.model.atomicHierarchy.chainAtomSegments;
            case 1 /* Spheres */: return unit.model.coarseHierarchy.spheres.chainElementSegments;
            case 2 /* Gaussians */: return unit.model.coarseHierarchy.gaussians.chainElementSegments;
        }
    }
    function isWholeUnit(element) {
        return element.unit.elements.length === _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(element.indices);
    }
    function makeIndexSet(newIndices) {
        if (newIndices.length > 12 && newIndices[newIndices.length - 1] - newIndices[0] === newIndices.length - 1) {
            return _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["Interval"].ofRange(newIndices[0], newIndices[newIndices.length - 1]);
        }
        else {
            return _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["SortedArray"].ofSortedArray(newIndices);
        }
    }
    function collectChains(unit, chainIndices, elements) {
        var index = getChainSegments(unit).index;
        var xs = unit.elements;
        var size = 0;
        for (var i = 0, _i = xs.length; i < _i; i++) {
            var eI = xs[i];
            var cI = index[eI];
            if (!chainIndices.has(cI))
                continue;
            size++;
        }
        if (size === unit.elements.length) {
            elements[elements.length] = { unit: unit, indices: _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["Interval"].ofBounds(0, size) };
            return;
        }
        var newIndices = new Int32Array(size);
        size = 0;
        for (var i = 0, _i = xs.length; i < _i; i++) {
            var eI = xs[i];
            var cI = index[eI];
            if (!chainIndices.has(cI))
                continue;
            newIndices[size++] = i;
        }
        if (newIndices.length > 0) {
            elements[elements.length] = { unit: unit, indices: makeIndexSet(newIndices) };
        }
    }
    function extendGroupToWholeChains(loci, start, end, isPartitioned, elements) {
        var chainIndex = getChainSegments(loci.elements[0].unit).index;
        var chainIndices = new Set();
        for (var lI = start; lI < end; lI++) {
            var lociElement = loci.elements[lI];
            var indices = lociElement.indices;
            var unitElements = lociElement.unit.elements;
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                chainIndices.add(chainIndex[unitElements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)]]);
            }
        }
        if (isPartitioned) {
            var baseUnit = loci.elements[0].unit;
            // TODO: check for accidental quadratic for really large structures (but should be ok).
            for (var _a = 0, _b = loci.structure.units; _a < _b.length; _a++) {
                var unit = _b[_a];
                if (!_unit__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].areSameChainOperatorGroup(unit, baseUnit))
                    continue;
                collectChains(unit, chainIndices, elements);
            }
        }
        else {
            for (var lI = start; lI < end; lI++) {
                collectChains(loci.elements[lI].unit, chainIndices, elements);
            }
        }
    }
    function extendToWholeChains(loci) {
        var elements = [];
        for (var i = 0, len = loci.elements.length; i < len; i++) {
            var e = loci.elements[i];
            if (_unit__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].Traits.is(e.unit.traits, 2 /* Partitioned */)) {
                var start = i;
                while (i < len && _unit__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].areSameChainOperatorGroup(loci.elements[i].unit, e.unit)) {
                    i++;
                }
                var end = i;
                i--;
                extendGroupToWholeChains(loci, start, end, true, elements);
            }
            else {
                if (isWholeUnit(e)) {
                    elements[elements.length] = e;
                }
                else {
                    extendGroupToWholeChains(loci, i, i + 1, false, elements);
                }
            }
        }
        return Loci(loci.structure, elements);
    }
    Loci.extendToWholeChains = extendToWholeChains;
    function entityModelKey(location) {
        return location.unit.model.id + "|" + _properties__WEBPACK_IMPORTED_MODULE_9__[/* default */ "a"].entity.id(location);
    }
    function extendToWholeEntities(loci) {
        var elements = [];
        var l = _location__WEBPACK_IMPORTED_MODULE_7__[/* Location */ "a"].create(loci.structure);
        var entities = new Set();
        var units = loci.structure.units;
        for (var i = 0, len = loci.elements.length; i < len; i++) {
            var e = loci.elements[i];
            l.unit = e.unit;
            l.element = e.unit.elements[0];
            entities.add(entityModelKey(l));
        }
        for (var i = 0, il = units.length; i < il; ++i) {
            var unit = units[i];
            l.unit = unit;
            l.element = unit.elements[0];
            if (entities.has(entityModelKey(l))) {
                var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].ofBounds(0, unit.elements.length);
                elements[elements.length] = { unit: unit, indices: indices };
            }
        }
        return Loci(loci.structure, elements);
    }
    Loci.extendToWholeEntities = extendToWholeEntities;
    function extendToWholeModels(loci) {
        var elements = [];
        var models = new Set();
        var units = loci.structure.units;
        for (var i = 0, len = loci.elements.length; i < len; i++) {
            var e = loci.elements[i];
            models.add(e.unit.model.id);
        }
        for (var i = 0, il = units.length; i < il; ++i) {
            var unit = units[i];
            if (models.has(unit.model.id)) {
                var indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].ofBounds(0, unit.elements.length);
                elements[elements.length] = { unit: unit, indices: indices };
            }
        }
        return Loci(loci.structure, elements);
    }
    Loci.extendToWholeModels = extendToWholeModels;
    function extendToAllInstances(loci) {
        var elements = [];
        var byInvariantId = new Map();
        var _a = loci.structure, unitSymmetryGroups = _a.unitSymmetryGroups, unitSymmetryGroupsIndexMap = _a.unitSymmetryGroupsIndexMap;
        for (var i = 0, len = loci.elements.length; i < len; i++) {
            var e = loci.elements[i];
            var invariantId = e.unit.invariantId;
            if (byInvariantId.has(invariantId)) {
                byInvariantId.set(invariantId, _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].union(e.indices, byInvariantId.get(invariantId)));
            }
            else {
                byInvariantId.set(invariantId, e.indices);
            }
        }
        byInvariantId.forEach(function (indices, invariantId) {
            var units = unitSymmetryGroups[unitSymmetryGroupsIndexMap.get(invariantId)].units;
            for (var i = 0, il = units.length; i < il; ++i) {
                elements[elements.length] = { unit: units[i], indices: indices };
            }
        });
        return Loci(loci.structure, elements);
    }
    Loci.extendToAllInstances = extendToAllInstances;
    //
    var boundaryHelper = new _mol_math_geometry_boundary_helper__WEBPACK_IMPORTED_MODULE_10__[/* BoundaryHelper */ "a"]('98');
    var tempPosBoundary = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].zero();
    function getBoundary(loci) {
        boundaryHelper.reset();
        for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            var indices = e.indices;
            var pos = e.unit.conformation.position, r = e.unit.conformation.r;
            var elements = e.unit.elements;
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                var eI = elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)];
                pos(eI, tempPosBoundary);
                boundaryHelper.includePositionRadius(tempPosBoundary, r(eI));
            }
        }
        boundaryHelper.finishedIncludeStep();
        for (var _c = 0, _d = loci.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            var indices = e.indices;
            var pos = e.unit.conformation.position, r = e.unit.conformation.r;
            var elements = e.unit.elements;
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                var eI = elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)];
                pos(eI, tempPosBoundary);
                boundaryHelper.radiusPositionRadius(tempPosBoundary, r(eI));
            }
        }
        return { box: boundaryHelper.getBox(), sphere: boundaryHelper.getSphere() };
    }
    Loci.getBoundary = getBoundary;
    var tempPos = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].zero();
    function toPositionsArray(loci, positions, offset) {
        if (offset === void 0) { offset = 0; }
        var m = offset;
        for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
            var e = _b[_a];
            var indices = e.indices;
            var pos = e.unit.conformation.position;
            var elements = e.unit.elements;
            var indexCount = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices);
            for (var i = 0; i < indexCount; i++) {
                var eI = elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)];
                pos(eI, tempPos);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_2__["Vec3"].toArray(tempPos, positions, m + i * 3);
            }
            m += indexCount * 3;
        }
        return positions;
    }
    Loci.toPositionsArray = toPositionsArray;
    function getPrincipalAxes(loci) {
        var elementCount = size(loci);
        var positions = toPositionsArray(loci, new Float32Array(3 * elementCount));
        return _mol_math_linear_algebra_matrix_principal_axes__WEBPACK_IMPORTED_MODULE_8__[/* PrincipalAxes */ "a"].ofPositions(positions);
    }
    Loci.getPrincipalAxes = getPrincipalAxes;
    function sourceIndex(unit, element) {
        return _unit__WEBPACK_IMPORTED_MODULE_5__[/* default */ "a"].isAtomic(unit)
            ? unit.model.atomicHierarchy.atoms.sourceIndex.value(element)
            // TODO: when implemented, this should map to the source index.
            : element;
    }
    function toExpression(loci) {
        var _a;
        if (Loci.isEmpty(loci))
            return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.empty();
        var models = loci.structure.models;
        var sourceIndexMap = new Map();
        for (var _b = 0, _c = loci.elements; _b < _c.length; _b++) {
            var e = _c[_b];
            var indices = e.indices;
            var elements = e.unit.elements;
            var key = models.length === 1
                ? e.unit.conformation.operator.name
                : e.unit.conformation.operator.name + " " + e.unit.model.label + " " + e.unit.model.modelNum;
            var sourceIndices = void 0;
            if (sourceIndexMap.has(key))
                sourceIndices = sourceIndexMap.get(key).xs;
            else {
                sourceIndices = _mol_data_generic__WEBPACK_IMPORTED_MODULE_0__[/* UniqueArray */ "c"].create();
                sourceIndexMap.set(key, { modelLabel: e.unit.model.label, modelIndex: e.unit.model.modelNum, xs: sourceIndices });
            }
            for (var i = 0, _i = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].size(indices); i < _i; i++) {
                var idx = sourceIndex(e.unit, elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(indices, i)]);
                _mol_data_generic__WEBPACK_IMPORTED_MODULE_0__[/* UniqueArray */ "c"].add(sourceIndices, idx, idx);
            }
        }
        var opData = [];
        var keys = sourceIndexMap.keys();
        while (true) {
            var k = keys.next();
            if (k.done)
                break;
            var e = sourceIndexMap.get(k.value);
            opData.push(getOpData(k.value, e.xs.array, models.length > 1, e.modelLabel, e.modelIndex));
        }
        var opGroups = new Map();
        for (var i = 0, il = opData.length; i < il; ++i) {
            var d = opData[i];
            var hash = Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_6__[/* hash2 */ "i"])(Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_6__[/* hashFnv32a */ "l"])(d.atom.ranges), Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_6__[/* hashFnv32a */ "l"])(d.atom.set));
            var key = hash + "|" + (d.entity ? (d.entity.modelLabel + d.entity.modelIndex) : '');
            if (opGroups.has(key)) {
                (_a = opGroups.get(key).chain.opName).push.apply(_a, d.chain.opName);
            }
            else {
                opGroups.set(key, d);
            }
        }
        var opQueries = [];
        opGroups.forEach(function (d) {
            var _a = d.atom, ranges = _a.ranges, set = _a.set;
            var opName = d.chain.opName;
            var opProp = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.atomProperty.core.operatorName();
            var siProp = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.atomProperty.core.sourceIndex();
            var tests = [];
            // TODO: add set.ofRanges constructor to MolQL???
            if (set.length > 0) {
                tests[tests.length] = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.set(set), siProp]);
            }
            for (var rI = 0, _rI = ranges.length / 2; rI < _rI; rI++) {
                tests[tests.length] = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.inRange([siProp, ranges[2 * rI], ranges[2 * rI + 1]]);
            }
            if (d.entity) {
                var _b = d.entity, modelLabel = _b.modelLabel, modelIndex = _b.modelIndex;
                opQueries.push(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                    'atom-test': tests.length > 1 ? _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or(tests) : tests[0],
                    'chain-test': opName.length > 1
                        ? _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.set(opName), opProp])
                        : _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([opProp, opName[0]]),
                    'entity-test': _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.and([
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.atomProperty.core.modelLabel(), modelLabel]),
                        _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.atomProperty.core.modelIndex(), modelIndex]),
                    ])
                }));
            }
            else {
                opQueries.push(_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.generator.atomGroups({
                    'atom-test': tests.length > 1 ? _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.logic.or(tests) : tests[0],
                    'chain-test': opName.length > 1
                        ? _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.set.has([_mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.type.set(opName), opProp])
                        : _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].core.rel.eq([opProp, opName[0]])
                }));
            }
        });
        return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([
            opQueries.length === 1
                ? opQueries[0]
                // Need to union before merge for fast performance
                : _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.combinator.merge(opQueries.map(function (q) { return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_3__["MolScriptBuilder"].struct.modifier.union([q]); }))
        ]);
    }
    Loci.toExpression = toExpression;
    function getOpData(opName, xs, multimodel, modelLabel, modelIndex) {
        Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_6__[/* sortArray */ "q"])(xs);
        var ranges = [];
        var set = [];
        var i = 0, len = xs.length;
        while (i < len) {
            var start = i;
            i++;
            while (i < len && xs[i - 1] + 1 === xs[i])
                i++;
            var end = i;
            // TODO: is this a good value?
            if (end - start > 12) {
                ranges[ranges.length] = xs[start];
                ranges[ranges.length] = xs[end - 1];
            }
            else {
                for (var j = start; j < end; j++) {
                    set[set.length] = xs[j];
                }
            }
        }
        return multimodel
            ? {
                atom: { set: set, ranges: ranges },
                chain: { opName: [opName] },
                entity: { modelLabel: modelLabel, modelIndex: modelIndex }
            }
            : {
                atom: { set: set, ranges: ranges },
                chain: { opName: [opName] },
            };
    }
})(Loci || (Loci = {}));
//# sourceMappingURL=loci.js.map

/***/ }),
/* 276 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "CustomModelProperty", function() { return CustomModelProperty; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(65);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(41);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var CustomModelProperty;
(function (CustomModelProperty) {
    function createProvider(builder) {
        var _this = this;
        var descriptorName = builder.descriptor.name;
        var propertyDataName = builder.type === 'static' ? '_staticPropertyData' : '_dynamicPropertyData';
        var get = function (data) {
            if (!(descriptorName in data[propertyDataName])) {
                data[propertyDataName][descriptorName] = {
                    props: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(builder.getParams(data))),
                    data: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueBox */ "d"].create(undefined)
                };
            }
            return data[propertyDataName][descriptorName];
        };
        var set = function (data, props, value) {
            var property = get(data);
            data[propertyDataName][descriptorName] = {
                props: props,
                data: _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* ValueBox */ "d"].withValue(property.data, value)
            };
        };
        return {
            label: builder.label,
            descriptor: builder.descriptor,
            isHidden: builder.isHidden,
            getParams: function (data) {
                var params = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].clone(builder.getParams(data));
                _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].setDefaultValues(params, get(data).props);
                return params;
            },
            defaultParams: builder.defaultParams,
            isApplicable: builder.isApplicable,
            attach: function (ctx, data, props, addRef) {
                if (props === void 0) { props = {}; }
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                    var property, p, _a, value, assets;
                    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                if (addRef)
                                    data.customProperties.reference(builder.descriptor, true);
                                property = get(data);
                                p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].merge(builder.defaultParams, property.props, props);
                                if (property.data.value && _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].areEqual(builder.defaultParams, property.props, p))
                                    return [2 /*return*/];
                                return [4 /*yield*/, builder.obtain(ctx, data, p)];
                            case 1:
                                _a = _b.sent(), value = _a.value, assets = _a.assets;
                                data.customProperties.add(builder.descriptor);
                                data.customProperties.assets(builder.descriptor, assets);
                                set(data, p, value);
                                return [2 /*return*/];
                        }
                    });
                });
            },
            ref: function (data, add) { return data.customProperties.reference(builder.descriptor, add); },
            get: function (data) { var _a; return (_a = get(data)) === null || _a === void 0 ? void 0 : _a.data; },
            set: function (data, props) {
                if (props === void 0) { props = {}; }
                var property = get(data);
                var p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].merge(builder.defaultParams, property.props, props);
                if (!_mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].areEqual(builder.defaultParams, property.props, p)) {
                    // this invalidates property.value
                    set(data, p, undefined);
                    // dispose of assets
                    data.customProperties.assets(builder.descriptor);
                }
            },
            props: function (data) { return get(data).props; },
        };
    }
    CustomModelProperty.createProvider = createProvider;
    function createSimple(name, type, defaultValue) {
        var _this = this;
        var defaultParams = { value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Value(defaultValue, { isHidden: true }) };
        return createProvider({
            label: Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_4__[/* stringToWords */ "d"])(name),
            descriptor: Object(_mol_model_custom_property__WEBPACK_IMPORTED_MODULE_3__["CustomPropertyDescriptor"])({ name: name }),
            isHidden: true,
            type: type,
            defaultParams: defaultParams,
            getParams: function () { return ({ value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Value(defaultValue, { isHidden: true }) }); },
            isApplicable: function () { return true; },
            obtain: function (ctx, data, props) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                var _a;
                return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                    return [2 /*return*/, { value: (_a = props.value) !== null && _a !== void 0 ? _a : defaultValue }];
                });
            }); }
        });
    }
    CustomModelProperty.createSimple = createSimple;
})(CustomModelProperty || (CustomModelProperty = {}));
//# sourceMappingURL=custom-model-property.js.map

/***/ }),
/* 277 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return rxSubscriber; });
/* unused harmony export $$rxSubscriber */
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var rxSubscriber = /*@__PURE__*/ (function () {
    return typeof Symbol === 'function'
        ? /*@__PURE__*/ Symbol('rxSubscriber')
        : '@@rxSubscriber_' + /*@__PURE__*/ Math.random();
})();
var $$rxSubscriber = rxSubscriber;
//# sourceMappingURL=rxSubscriber.js.map


/***/ }),
/* 278 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UnsubscriptionError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () {
    function UnsubscriptionErrorImpl(errors) {
        Error.call(this);
        this.message = errors ?
            errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n  ') : '';
        this.name = 'UnsubscriptionError';
        this.errors = errors;
        return this;
    }
    UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return UnsubscriptionErrorImpl;
})();
var UnsubscriptionError = UnsubscriptionErrorImpl;
//# sourceMappingURL=UnsubscriptionError.js.map


/***/ }),
/* 279 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BehaviorSubject; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(60);
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(208);
/** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */



var BehaviorSubject = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](BehaviorSubject, _super);
    function BehaviorSubject(_value) {
        var _this = _super.call(this) || this;
        _this._value = _value;
        return _this;
    }
    Object.defineProperty(BehaviorSubject.prototype, "value", {
        get: function () {
            return this.getValue();
        },
        enumerable: true,
        configurable: true
    });
    BehaviorSubject.prototype._subscribe = function (subscriber) {
        var subscription = _super.prototype._subscribe.call(this, subscriber);
        if (subscription && !subscription.closed) {
            subscriber.next(this._value);
        }
        return subscription;
    };
    BehaviorSubject.prototype.getValue = function () {
        if (this.hasError) {
            throw this.thrownError;
        }
        else if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_2__[/* ObjectUnsubscribedError */ "a"]();
        }
        else {
            return this._value;
        }
    };
    BehaviorSubject.prototype.next = function (value) {
        _super.prototype.next.call(this, this._value = value);
    };
    return BehaviorSubject;
}(_Subject__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"]));

//# sourceMappingURL=BehaviorSubject.js.map


/***/ }),
/* 280 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ModelSecondaryStructure; });
/* harmony import */ var _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/* harmony import */ var _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(119);
/* harmony import */ var _mol_model_structure_model_properties_seconday_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(358);
/* harmony import */ var _common_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(188);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var ModelSecondaryStructure;
(function (ModelSecondaryStructure) {
    ModelSecondaryStructure.Descriptor = {
        name: 'model_secondary_structure',
    };
    ModelSecondaryStructure.Provider = _common_property__WEBPACK_IMPORTED_MODULE_3__[/* FormatPropertyProvider */ "a"].create(ModelSecondaryStructure.Descriptor);
    function fromStruct(conf, sheetRange, hierarchy) {
        var map = new Map();
        var elements = [{ kind: 'none' }];
        addHelices(conf, map, elements);
        // must add Helices 1st because of 'key' value assignment.
        addSheets(sheetRange, map, conf._rowCount, elements);
        var n = hierarchy.residues._rowCount;
        var getIndex = function (rI) { return rI; };
        var secStruct = {
            type: new Int32Array(n),
            key: new Int32Array(n),
            elements: elements
        };
        if (map.size > 0)
            assignSecondaryStructureRanges(hierarchy, map, secStruct);
        return Object(_mol_model_structure_model_properties_seconday_structure__WEBPACK_IMPORTED_MODULE_2__[/* SecondaryStructure */ "a"])(secStruct.type, secStruct.key, secStruct.elements, getIndex);
    }
    ModelSecondaryStructure.fromStruct = fromStruct;
})(ModelSecondaryStructure || (ModelSecondaryStructure = {}));
function addHelices(cat, map, elements) {
    if (!cat._rowCount)
        return;
    var beg_label_asym_id = cat.beg_label_asym_id, beg_label_seq_id = cat.beg_label_seq_id, pdbx_beg_PDB_ins_code = cat.pdbx_beg_PDB_ins_code;
    var end_label_seq_id = cat.end_label_seq_id, pdbx_end_PDB_ins_code = cat.pdbx_end_PDB_ins_code;
    var pdbx_PDB_helix_class = cat.pdbx_PDB_helix_class, conf_type_id = cat.conf_type_id, details = cat.details;
    for (var i = 0, _i = cat._rowCount; i < _i; i++) {
        var type = _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["SecondaryStructureType"].create(pdbx_PDB_helix_class.valueKind(i) === 0 /* Present */
            ? _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["SecondaryStructureType"].SecondaryStructurePdb[pdbx_PDB_helix_class.value(i)]
            : conf_type_id.valueKind(i) === 0 /* Present */
                ? _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["SecondaryStructureType"].SecondaryStructureMmcif[conf_type_id.value(i)]
                : 536870912 /* NA */);
        var element = {
            kind: 'helix',
            flags: type,
            type_id: conf_type_id.valueKind(i) === 0 /* Present */ ? conf_type_id.value(i) : 'HELIX_P',
            helix_class: pdbx_PDB_helix_class.value(i),
            details: details.valueKind(i) === 0 /* Present */ ? details.value(i) : void 0
        };
        var entry = {
            startSeqNumber: beg_label_seq_id.value(i),
            startInsCode: pdbx_beg_PDB_ins_code.value(i),
            endSeqNumber: end_label_seq_id.value(i),
            endInsCode: pdbx_end_PDB_ins_code.value(i),
            type: type,
            key: elements.length
        };
        elements[elements.length] = element;
        var asymId = beg_label_asym_id.value(i);
        if (map.has(asymId)) {
            var entries = map.get(asymId);
            if (entries.has(entry.startSeqNumber)) {
                entries.get(entry.startSeqNumber).push(entry);
            }
            else {
                entries.set(entry.startSeqNumber, [entry]);
            }
        }
        else {
            map.set(asymId, new Map([[entry.startSeqNumber, [entry]]]));
        }
    }
}
function addSheets(cat, map, sheetCount, elements) {
    if (!cat._rowCount)
        return;
    var beg_label_asym_id = cat.beg_label_asym_id, beg_label_seq_id = cat.beg_label_seq_id, pdbx_beg_PDB_ins_code = cat.pdbx_beg_PDB_ins_code;
    var end_label_seq_id = cat.end_label_seq_id, pdbx_end_PDB_ins_code = cat.pdbx_end_PDB_ins_code;
    var sheet_id = cat.sheet_id;
    var sheet_id_key = new Map();
    var currentKey = sheetCount + 1;
    for (var i = 0, _i = cat._rowCount; i < _i; i++) {
        var id = sheet_id.value(i);
        var key = void 0;
        if (sheet_id_key.has(id))
            key = sheet_id_key.get(id);
        else {
            key = currentKey++;
            sheet_id_key.set(id, key);
        }
        var type = _mol_model_structure_model_types__WEBPACK_IMPORTED_MODULE_0__["SecondaryStructureType"].create(4 /* Beta */ | 8388608 /* BetaSheet */);
        var element = {
            kind: 'sheet',
            flags: type,
            sheet_id: id,
            symmetry: void 0
        };
        var entry = {
            startSeqNumber: beg_label_seq_id.value(i),
            startInsCode: pdbx_beg_PDB_ins_code.value(i),
            endSeqNumber: end_label_seq_id.value(i),
            endInsCode: pdbx_end_PDB_ins_code.value(i),
            type: type,
            key: elements.length
        };
        elements[elements.length] = element;
        var asymId = beg_label_asym_id.value(i);
        if (map.has(asymId)) {
            var entries = map.get(asymId);
            if (entries.has(entry.startSeqNumber)) {
                entries.get(entry.startSeqNumber).push(entry);
            }
            else {
                entries.set(entry.startSeqNumber, [entry]);
            }
        }
        else {
            map.set(asymId, new Map([[entry.startSeqNumber, [entry]]]));
        }
    }
    return;
}
function assignSecondaryStructureEntry(hierarchy, entry, resStart, resEnd, data) {
    var _a = hierarchy.residues, label_seq_id = _a.label_seq_id, pdbx_PDB_ins_code = _a.pdbx_PDB_ins_code;
    var endSeqNumber = entry.endSeqNumber, endInsCode = entry.endInsCode, key = entry.key, type = entry.type;
    var rI = resStart;
    while (rI < resEnd) {
        var seqNumber = label_seq_id.value(rI);
        data.type[rI] = type;
        data.key[rI] = key;
        if ((seqNumber > endSeqNumber) ||
            (seqNumber === endSeqNumber && pdbx_PDB_ins_code.value(rI) === endInsCode)) {
            break;
        }
        rI++;
    }
}
function assignSecondaryStructureRanges(hierarchy, map, data) {
    var chainCount = hierarchy.chainAtomSegments.count;
    var label_asym_id = hierarchy.chains.label_asym_id;
    var _a = hierarchy.residues, label_seq_id = _a.label_seq_id, pdbx_PDB_ins_code = _a.pdbx_PDB_ins_code;
    for (var cI = 0; cI < chainCount; cI++) {
        var resStart = _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__["AtomicHierarchy"].chainStartResidueIndex(hierarchy, cI), resEnd = _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__["AtomicHierarchy"].chainEndResidueIndexExcl(hierarchy, cI);
        var asymId = label_asym_id.value(cI);
        if (map.has(asymId)) {
            var entries = map.get(asymId);
            for (var rI = resStart; rI < resEnd; rI++) {
                var seqNumber = label_seq_id.value(rI);
                if (entries.has(seqNumber)) {
                    var entryList = entries.get(seqNumber);
                    for (var _b = 0, entryList_1 = entryList; _b < entryList_1.length; _b++) {
                        var entry = entryList_1[_b];
                        var insCode = pdbx_PDB_ins_code.value(rI);
                        if (entry.startInsCode !== insCode)
                            continue;
                        assignSecondaryStructureEntry(hierarchy, entry, rI, resEnd, data);
                    }
                }
            }
        }
    }
}
//# sourceMappingURL=secondary-structure.js.map

/***/ }),
/* 281 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getUsageHint */
/* unused harmony export getDataType */
/* unused harmony export getBufferType */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return getAttribType; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createAttributeBuffer; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createAttributeBuffers; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createElementsBuffer; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(96);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var getNextBufferId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_1__[/* idFactory */ "a"])();
function getUsageHint(gl, usageHint) {
    switch (usageHint) {
        case 'static': return gl.STATIC_DRAW;
        case 'dynamic': return gl.DYNAMIC_DRAW;
        case 'stream': return gl.STREAM_DRAW;
    }
}
function getDataType(gl, dataType) {
    switch (dataType) {
        case 'uint8': return gl.UNSIGNED_BYTE;
        case 'int8': return gl.BYTE;
        case 'uint16': return gl.UNSIGNED_SHORT;
        case 'int16': return gl.SHORT;
        case 'uint32': return gl.UNSIGNED_INT;
        case 'int32': return gl.INT;
        case 'float32': return gl.FLOAT;
    }
}
function dataTypeFromArray(gl, array) {
    if (array instanceof Uint8Array) {
        return gl.UNSIGNED_BYTE;
    }
    else if (array instanceof Int8Array) {
        return gl.BYTE;
    }
    else if (array instanceof Uint16Array) {
        return gl.UNSIGNED_SHORT;
    }
    else if (array instanceof Int16Array) {
        return gl.SHORT;
    }
    else if (array instanceof Uint32Array) {
        return gl.UNSIGNED_INT;
    }
    else if (array instanceof Int32Array) {
        return gl.INT;
    }
    else if (array instanceof Float32Array) {
        return gl.FLOAT;
    }
    else {
        throw new Error('Should nevver happen');
    }
}
function getBufferType(gl, bufferType) {
    switch (bufferType) {
        case 'attribute': return gl.ARRAY_BUFFER;
        case 'elements': return gl.ELEMENT_ARRAY_BUFFER;
        case 'uniform': return gl.UNIFORM_BUFFER;
    }
}
function getBuffer(gl) {
    var buffer = gl.createBuffer();
    if (buffer === null) {
        throw new Error('Could not create WebGL buffer');
    }
    return buffer;
}
function createBuffer(gl, array, usageHint, bufferType) {
    var _buffer = getBuffer(gl);
    var _usageHint = getUsageHint(gl, usageHint);
    var _bufferType = getBufferType(gl, bufferType);
    var _dataType = dataTypeFromArray(gl, array);
    var _bpe = array.BYTES_PER_ELEMENT;
    var _length = array.length;
    function updateData(array) {
        gl.bindBuffer(_bufferType, _buffer);
        gl.bufferData(_bufferType, array, _usageHint);
    }
    updateData(array);
    var destroyed = false;
    return {
        id: getNextBufferId(),
        _usageHint: _usageHint,
        _bufferType: _bufferType,
        _dataType: _dataType,
        _bpe: _bpe,
        length: _length,
        getBuffer: function () { return _buffer; },
        updateData: updateData,
        updateSubData: function (array, offset, count) {
            gl.bindBuffer(_bufferType, _buffer);
            gl.bufferSubData(_bufferType, offset * _bpe, array.subarray(offset, offset + count));
        },
        reset: function () {
            _buffer = getBuffer(gl);
            updateData(array);
        },
        destroy: function () {
            if (destroyed)
                return;
            gl.deleteBuffer(_buffer);
            destroyed = true;
        }
    };
}
function getAttribType(gl, kind, itemSize) {
    switch (kind) {
        case 'int32':
            switch (itemSize) {
                case 1: return gl.INT;
                case 2: return gl.INT_VEC2;
                case 3: return gl.INT_VEC3;
                case 4: return gl.INT_VEC4;
            }
            break;
        case 'float32':
            switch (itemSize) {
                case 1: return gl.FLOAT;
                case 2: return gl.FLOAT_VEC2;
                case 3: return gl.FLOAT_VEC3;
                case 4: return gl.FLOAT_VEC4;
                case 16: return gl.FLOAT_MAT4;
            }
            break;
    }
    throw new Error("unknown attribute type for kind '" + kind + "' and itemSize '" + itemSize + "'");
}
function createAttributeBuffer(gl, extensions, array, itemSize, divisor, usageHint) {
    if (usageHint === void 0) { usageHint = 'dynamic'; }
    var instancedArrays = extensions.instancedArrays;
    var buffer = createBuffer(gl, array, usageHint, 'attribute');
    var _bufferType = buffer._bufferType, _dataType = buffer._dataType, _bpe = buffer._bpe;
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, buffer), { bind: function (location) {
            gl.bindBuffer(_bufferType, buffer.getBuffer());
            if (itemSize === 16) {
                for (var i = 0; i < 4; ++i) {
                    gl.enableVertexAttribArray(location + i);
                    gl.vertexAttribPointer(location + i, 4, _dataType, false, 4 * 4 * _bpe, i * 4 * _bpe);
                    instancedArrays.vertexAttribDivisor(location + i, divisor);
                }
            }
            else {
                gl.enableVertexAttribArray(location);
                gl.vertexAttribPointer(location, itemSize, _dataType, false, 0, 0);
                instancedArrays.vertexAttribDivisor(location, divisor);
            }
        } });
}
function createAttributeBuffers(ctx, schema, values) {
    var buffers = [];
    Object.keys(schema).forEach(function (k) {
        var spec = schema[k];
        if (spec.type === 'attribute') {
            buffers[buffers.length] = [k, ctx.resources.attribute(values[k].ref.value, spec.itemSize, spec.divisor)];
        }
    });
    return buffers;
}
function createElementsBuffer(gl, array, usageHint) {
    if (usageHint === void 0) { usageHint = 'static'; }
    var buffer = createBuffer(gl, array, usageHint, 'elements');
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, buffer), { bind: function () {
            gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, buffer.getBuffer());
        } });
}
//# sourceMappingURL=buffer.js.map

/***/ }),
/* 282 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export PhysicalSizeThemeParams */
/* unused harmony export getPhysicalSizeThemeParams */
/* unused harmony export getPhysicalRadius */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PhysicalSizeTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PhysicalSizeThemeProvider; });
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(4);
/* harmony import */ var _mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(119);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DefaultSize = 1;
var Description = 'Assigns a physical size, i.e. vdW radius for atoms or given radius for coarse spheres.';
var PhysicalSizeThemeParams = {
    scale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Numeric(1, { min: 0.1, max: 5, step: 0.1 })
};
function getPhysicalSizeThemeParams(ctx) {
    return PhysicalSizeThemeParams; // TODO return copy
}
function getPhysicalRadius(unit, element) {
    if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Unit"].isAtomic(unit)) {
        return Object(_mol_model_structure_model_properties_atomic__WEBPACK_IMPORTED_MODULE_1__["VdwRadius"])(unit.model.atomicHierarchy.atoms.type_symbol.value(element));
    }
    else if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Unit"].isSpheres(unit)) {
        return unit.model.coarseConformation.spheres.radius[element];
    }
    else {
        return 0;
    }
}
/**
 * Create attribute data with the physical size of an element,
 * i.e. vdw for atoms and radius for coarse spheres
 */
function PhysicalSizeTheme(ctx, props) {
    var scale = props.scale === void 0 ? 1 : props.scale;
    function size(location) {
        var size;
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["StructureElement"].Location.is(location)) {
            size = scale * getPhysicalRadius(location.unit, location.element);
        }
        else if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_0__["Bond"].isLocation(location)) {
            size = scale * getPhysicalRadius(location.aUnit, location.aUnit.elements[location.aIndex]);
        }
        else {
            size = scale * DefaultSize;
        }
        return size;
    }
    return {
        factory: PhysicalSizeTheme,
        granularity: 'group',
        size: size,
        props: props,
        description: Description
    };
}
var PhysicalSizeThemeProvider = {
    name: 'physical',
    label: 'Physical',
    category: '',
    factory: PhysicalSizeTheme,
    getParams: getPhysicalSizeThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(PhysicalSizeThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=physical.js.map

/***/ }),
/* 283 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ObjectKeys; });
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function ObjectKeys(o) {
    return Object.keys(o);
}
;
//# sourceMappingURL=type-helpers.js.map

/***/ }),
/* 284 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return CameraHelperParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CameraHelper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_gl_scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(263);
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(232);
/* harmony import */ var _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(34);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(1);
/* harmony import */ var _mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(75);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(39);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(47);
/* harmony import */ var _mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(81);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(5);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(11);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(2);
/* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(151);
/* harmony import */ var _mol_model_shape__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(49);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














// TODO add scale line/grid
var AxesParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_6__[/* Mesh */ "a"].Params), { alpha: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_6__[/* Mesh */ "a"].Params.alpha), { defaultValue: 0.33 }), ignoreLight: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_6__[/* Mesh */ "a"].Params.ignoreLight), { defaultValue: true }), colorX: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_7__[/* ColorNames */ "a"].red, { isEssential: true }), colorY: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_7__[/* ColorNames */ "a"].green, { isEssential: true }), colorZ: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_7__[/* ColorNames */ "a"].blue, { isEssential: true }), scale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Numeric(0.33, { min: 0.1, max: 2, step: 0.1 }, { isEssential: true }) });
var CameraHelperParams = {
    axes: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].MappedStatic('on', {
        on: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Group(AxesParams),
        off: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_11__["ParamDefinition"].Group({})
    }, { cycle: true, description: 'Show camera orientation axes' }),
};
var CameraHelper = /** @class */ (function () {
    function CameraHelper(webgl, props) {
        if (props === void 0) { props = {}; }
        this.webgl = webgl;
        this.props = {
            axes: { name: 'off', params: {} }
        };
        this.scene = _mol_gl_scene__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(webgl);
        this.camera = new _camera__WEBPACK_IMPORTED_MODULE_2__[/* Camera */ "a"]();
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].set(this.camera.up, 0, 1, 0);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].set(this.camera.target, 0, 0, 0);
        this.setProps(props);
    }
    CameraHelper.prototype.setProps = function (props) {
        var _this = this;
        this.props = Object(immer__WEBPACK_IMPORTED_MODULE_12__[/* default */ "a"])(this.props, function (p) {
            if (props.axes !== undefined) {
                p.axes.name = props.axes.name;
                if (props.axes.name === 'on') {
                    _this.scene.clear();
                    var params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, props.axes.params), { scale: props.axes.params.scale * _this.webgl.pixelRatio });
                    _this.renderObject = createAxesRenderObject(params);
                    _this.scene.add(_this.renderObject);
                    _this.scene.commit();
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].set(_this.camera.position, 0, 0, params.scale * 200);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].lookAt(_this.camera.view, _this.camera.position, _this.camera.target, _this.camera.up);
                    p.axes.params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, props.axes.params);
                }
            }
        });
    };
    Object.defineProperty(CameraHelper.prototype, "isEnabled", {
        get: function () {
            return this.props.axes.name === 'on';
        },
        enumerable: false,
        configurable: true
    });
    CameraHelper.prototype.update = function (camera) {
        if (!this.renderObject)
            return;
        updateCamera(this.camera, camera.viewport);
        var m = this.renderObject.values.aTransform.ref.value;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].extractRotation(m, camera.view);
        var r = this.renderObject.values.boundingSphere.ref.value.radius;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].setTranslation(m, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].create(-camera.viewport.width / 2 + r, -camera.viewport.height / 2 + r, 0));
        _mol_util__WEBPACK_IMPORTED_MODULE_9__[/* ValueCell */ "e"].update(this.renderObject.values.aTransform, this.renderObject.values.aTransform.ref.value);
        this.scene.update([this.renderObject], true);
    };
    return CameraHelper;
}());

function updateCamera(camera, viewport) {
    var near = camera.near, far = camera.far;
    var fullLeft = -(viewport.width - viewport.x) / 2;
    var fullRight = (viewport.width - viewport.x) / 2;
    var fullTop = (viewport.height - viewport.y) / 2;
    var fullBottom = -(viewport.height - viewport.y) / 2;
    var dx = (fullRight - fullLeft) / 2;
    var dy = (fullTop - fullBottom) / 2;
    var cx = (fullRight + fullLeft) / 2;
    var cy = (fullTop + fullBottom) / 2;
    var left = cx - dx;
    var right = cx + dx;
    var top = cy + dy;
    var bottom = cy - dy;
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Mat4"].ortho(camera.projection, left, right, top, bottom, near, far);
}
function createAxesMesh(scale, mesh) {
    var state = _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__[/* MeshBuilder */ "a"].createState(512, 256, mesh);
    var radius = 0.05 * scale;
    var x = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].unitX, scale);
    var y = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].unitY, scale);
    var z = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].unitZ, scale);
    var cylinderProps = { radiusTop: radius, radiusBottom: radius, radialSegments: 32 };
    state.currentGroup = 0;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_5__[/* addSphere */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].origin, radius, 2);
    state.currentGroup = 1;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_5__[/* addSphere */ "a"])(state, x, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_8__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].origin, x, 1, cylinderProps);
    state.currentGroup = 2;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_5__[/* addSphere */ "a"])(state, y, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_8__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].origin, y, 1, cylinderProps);
    state.currentGroup = 3;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_5__[/* addSphere */ "a"])(state, z, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_8__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].origin, z, 1, cylinderProps);
    return _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_3__[/* MeshBuilder */ "a"].getMesh(state);
}
function getAxesShape(props, shape) {
    var scale = 100 * props.scale;
    var mesh = createAxesMesh(scale, shape === null || shape === void 0 ? void 0 : shape.geometry);
    mesh.setBoundingSphere(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_10__[/* Sphere3D */ "g"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_4__["Vec3"].create(scale / 2, scale / 2, scale / 2), scale + scale / 4));
    var getColor = function (groupId) {
        switch (groupId) {
            case 1: return props.colorX;
            case 2: return props.colorY;
            case 3: return props.colorZ;
            default: return _mol_util_color_names__WEBPACK_IMPORTED_MODULE_7__[/* ColorNames */ "a"].grey;
        }
    };
    return _mol_model_shape__WEBPACK_IMPORTED_MODULE_13__[/* Shape */ "a"].create('axes', {}, mesh, getColor, function () { return 1; }, function () { return ''; });
}
function createAxesRenderObject(props) {
    var shape = getAxesShape(props);
    return _mol_model_shape__WEBPACK_IMPORTED_MODULE_13__[/* Shape */ "a"].createRenderObject(shape, props);
}
//# sourceMappingURL=camera-helper.js.map

/***/ }),
/* 285 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateSnapshots", function() { return StateSnapshots; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateExportImportControls", function() { return StateExportImportControls; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalStateSnapshotParams", function() { return LocalStateSnapshotParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalStateSnapshots", function() { return LocalStateSnapshots; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "LocalStateSnapshotList", function() { return LocalStateSnapshotList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "RemoteStateSnapshots", function() { return RemoteStateSnapshots; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(102);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(immutable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(26);
/* harmony import */ var _mol_plugin_config__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(101);
/* harmony import */ var _mol_plugin_state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(372);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(5);
/* harmony import */ var _mol_util_now__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(83);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(2);
/* harmony import */ var _mol_util_url__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(262);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(32);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(14);
/* harmony import */ var _controls_parameters__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(66);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */














var StateSnapshots = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateSnapshots, _super);
    function StateSnapshots() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    StateSnapshots.prototype.render = function () {
        var _a;
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", null,
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["SectionHeader"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SaveOutlinedSvg"], title: 'Plugin State' }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { style: { marginBottom: '10px' } },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["ExpandGroup"], { header: 'Save Options', initiallyExpanded: false },
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"](LocalStateSnapshotParams, null))),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](LocalStateSnapshots, null),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](LocalStateSnapshotList, null),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["SectionHeader"], { title: 'Save as File', accent: 'blue' }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](StateExportImportControls, null),
            ((_a = this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.remoteState) !== 'none' && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](RemoteStateSnapshots, null));
    };
    return StateSnapshots;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var StateExportImportControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateExportImportControls, _super);
    function StateExportImportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.downloadToFileJson = function () {
            var _a, _b;
            (_b = (_a = _this.props).onAction) === null || _b === void 0 ? void 0 : _b.call(_a);
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.DownloadToFile(_this.plugin, { type: 'json' });
        };
        _this.downloadToFileZip = function () {
            var _a, _b;
            (_b = (_a = _this.props).onAction) === null || _b === void 0 ? void 0 : _b.call(_a);
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.DownloadToFile(_this.plugin, { type: 'zip' });
        };
        _this.open = function (e) {
            var _a, _b;
            if (!e.target.files || !e.target.files[0]) {
                _this.plugin.log.error('No state file selected');
                return;
            }
            (_b = (_a = _this.props).onAction) === null || _b === void 0 ? void 0 : _b.call(_a);
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.OpenFile(_this.plugin, { file: e.target.files[0] });
        };
        return _this;
    }
    StateExportImportControls.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](react__WEBPACK_IMPORTED_MODULE_2__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-flex-row' },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["GetAppSvg"], onClick: this.downloadToFileJson, title: 'Save the state description. Input data are loaded using the provided sources. Does not work if local files are used as input.' }, "State"),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["GetAppSvg"], onClick: this.downloadToFileZip, title: 'Save the state including the input data.' }, "Session"),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-btn msp-btn-block msp-btn-action msp-loader-msp-btn-file' },
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["OpenInBrowserSvg"], inline: true }),
                    " Open ",
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("input", { onChange: this.open, type: 'file', multiple: false, accept: '.molx,.molj' }))),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-help-text', style: { padding: '10px' } },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_12__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["WarningSvg"] }),
                " This is an experimental feature and stored states/sessions might not be openable in a future version."));
    };
    return StateExportImportControls;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var LocalStateSnapshotParams = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LocalStateSnapshotParams, _super);
    function LocalStateSnapshotParams() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    LocalStateSnapshotParams.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.snapshotParams, function () { return _this.forceUpdate(); });
    };
    LocalStateSnapshotParams.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_13__["ParameterControls"], { params: _mol_plugin_state__WEBPACK_IMPORTED_MODULE_5__[/* PluginState */ "a"].SnapshotParams, values: this.plugin.state.snapshotParams.value, onChangeValues: this.plugin.state.setSnapshotParams });
    };
    return LocalStateSnapshotParams;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var LocalStateSnapshots = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LocalStateSnapshots, _super);
    function LocalStateSnapshots() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { params: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].getDefaultValues(LocalStateSnapshots.Params) };
        _this.add = function () {
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Add(_this.plugin, {
                name: _this.state.params.name,
                description: _this.state.params.description
            });
        };
        _this.updateParams = function (params) { return _this.setState({ params: params }); };
        _this.clear = function () {
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Clear(_this.plugin, {});
        };
        return _this;
    }
    LocalStateSnapshots.prototype.shouldComponentUpdate = function (nextProps, nextState) {
        return !Object(_mol_util__WEBPACK_IMPORTED_MODULE_6__[/* shallowEqualObjects */ "m"])(this.props, nextProps) || !Object(_mol_util__WEBPACK_IMPORTED_MODULE_6__[/* shallowEqualObjects */ "m"])(this.state, nextState);
    };
    LocalStateSnapshots.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", null,
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_13__["ParameterControls"], { params: LocalStateSnapshots.Params, values: this.state.params, onEnter: this.add, onChangeValues: this.updateParams }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-flex-row' },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { onClick: this.clear, svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["DeleteOutlinedSvg"], title: 'Remove All' }),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { onClick: this.add, icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["AddSvg"], style: { textAlign: 'right' }, commit: true }, "Add")));
    };
    LocalStateSnapshots.Params = {
        name: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text(),
        description: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text()
    };
    return LocalStateSnapshots;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var LocalStateSnapshotList = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LocalStateSnapshotList, _super);
    function LocalStateSnapshotList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.apply = function (e) {
            var id = e.currentTarget.getAttribute('data-id');
            if (!id)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Apply(_this.plugin, { id: id });
        };
        _this.remove = function (e) {
            var id = e.currentTarget.getAttribute('data-id');
            if (!id)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Remove(_this.plugin, { id: id });
        };
        _this.moveUp = function (e) {
            var id = e.currentTarget.getAttribute('data-id');
            if (!id)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Move(_this.plugin, { id: id, dir: -1 });
        };
        _this.moveDown = function (e) {
            var id = e.currentTarget.getAttribute('data-id');
            if (!id)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Move(_this.plugin, { id: id, dir: 1 });
        };
        _this.replace = function (e) {
            var id = e.currentTarget.getAttribute('data-id');
            if (!id)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Replace(_this.plugin, { id: id });
        };
        return _this;
    }
    LocalStateSnapshotList.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.snapshot.events.changed, function () { return _this.forceUpdate(); });
    };
    LocalStateSnapshotList.prototype.render = function () {
        var _this = this;
        var current = this.plugin.managers.snapshot.state.current;
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("ul", { style: { listStyle: 'none', marginTop: '10px' }, className: 'msp-state-list' }, this.plugin.managers.snapshot.state.entries.map(function (e) { return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("li", { key: e.snapshot.id, className: 'msp-flex-row' },
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { "data-id": e.snapshot.id, onClick: _this.apply, className: 'msp-no-overflow' },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("span", { style: { fontWeight: e.snapshot.id === current ? 'bold' : void 0 } }, e.name || new Date(e.timestamp).toLocaleString()),
                " ",
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("small", null, "" + (e.snapshot.durationInMs ? Object(_mol_util_now__WEBPACK_IMPORTED_MODULE_7__[/* formatTimespan */ "a"])(e.snapshot.durationInMs, false) + ("" + (e.description ? ', ' : '')) : '') + (e.description ? e.description : ''))),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["ArrowUpwardSvg"], "data-id": e.snapshot.id, title: 'Move Up', onClick: _this.moveUp, flex: '20px' }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["ArrowDownwardSvg"], "data-id": e.snapshot.id, title: 'Move Down', onClick: _this.moveDown, flex: '20px' }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["SwapHorizSvg"], "data-id": e.snapshot.id, title: 'Replace', onClick: _this.replace, flex: '20px' }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["DeleteOutlinedSvg"], "data-id": e.snapshot.id, title: 'Remove', onClick: _this.remove, flex: '20px' })); }));
    };
    return LocalStateSnapshotList;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var RemoteStateSnapshots = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RemoteStateSnapshots, _super);
    function RemoteStateSnapshots() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.Params = {
            name: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text(),
            options: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Group({
                description: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text(),
                playOnLoad: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Boolean(false),
                serverUrl: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text(_this.plugin.config.get(_mol_plugin_config__WEBPACK_IMPORTED_MODULE_4__["PluginConfig"].State.CurrentServer))
            })
        };
        _this.state = { params: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].getDefaultValues(_this.Params), entries: Object(immutable__WEBPACK_IMPORTED_MODULE_1__["OrderedMap"])(), isBusy: false };
        _this.ListOnlyParams = {
            options: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Group({
                serverUrl: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_8__["ParamDefinition"].Text(_this.plugin.config.get(_mol_plugin_config__WEBPACK_IMPORTED_MODULE_4__["PluginConfig"].State.CurrentServer))
            }, { isFlat: true })
        };
        _this._mounted = false;
        _this.refresh = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var json, entries, _i, json_1, e, e_1;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        this.setState({ isBusy: true });
                        this.plugin.config.set(_mol_plugin_config__WEBPACK_IMPORTED_MODULE_4__["PluginConfig"].State.CurrentServer, this.state.params.options.serverUrl);
                        return [4 /*yield*/, this.plugin.runTask(this.plugin.fetch({ url: this.serverUrl('list'), type: 'json' }))];
                    case 1:
                        json = (_a.sent()) || [];
                        json.sort(function (a, b) {
                            if (a.isSticky === b.isSticky)
                                return a.timestamp - b.timestamp;
                            return a.isSticky ? -1 : 1;
                        });
                        entries = Object(immutable__WEBPACK_IMPORTED_MODULE_1__["OrderedMap"])().asMutable();
                        for (_i = 0, json_1 = json; _i < json_1.length; _i++) {
                            e = json_1[_i];
                            entries.set(e.id, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, e), { url: this.serverUrl("get/" + e.id), removeUrl: this.serverUrl("remove/" + e.id) }));
                        }
                        if (this._mounted)
                            this.setState({ entries: entries.asImmutable(), isBusy: false });
                        return [3 /*break*/, 3];
                    case 2:
                        e_1 = _a.sent();
                        this.plugin.log.error('Fetching Remote Snapshots: ' + e_1);
                        if (this._mounted)
                            this.setState({ entries: Object(immutable__WEBPACK_IMPORTED_MODULE_1__["OrderedMap"])(), isBusy: false });
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); };
        _this.upload = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.setState({ isBusy: true });
                        this.plugin.config.set(_mol_plugin_config__WEBPACK_IMPORTED_MODULE_4__["PluginConfig"].State.CurrentServer, this.state.params.options.serverUrl);
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Upload(this.plugin, {
                                name: this.state.params.name,
                                description: this.state.params.options.description,
                                playOnLoad: this.state.params.options.playOnLoad,
                                serverUrl: this.state.params.options.serverUrl
                            })];
                    case 1:
                        _a.sent();
                        this.plugin.log.message('Snapshot uploaded.');
                        if (this._mounted) {
                            this.setState({ isBusy: false });
                            this.refresh();
                        }
                        return [2 /*return*/];
                }
            });
        }); };
        _this.fetch = function (e) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var id, entry;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = e.currentTarget.getAttribute('data-id');
                        if (!id)
                            return [2 /*return*/];
                        entry = this.state.entries.get(id);
                        if (!entry)
                            return [2 /*return*/];
                        this.setState({ isBusy: true });
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_3__["PluginCommands"].State.Snapshots.Fetch(this.plugin, { url: entry.url })];
                    case 2:
                        _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        if (this._mounted)
                            this.setState({ isBusy: false });
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        _this.remove = function (e) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var id, entry, _a;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        id = e.currentTarget.getAttribute('data-id');
                        if (!id)
                            return [2 /*return*/];
                        entry = this.state.entries.get(id);
                        if (!entry)
                            return [2 /*return*/];
                        this.setState({ entries: this.state.entries.remove(id) });
                        _b.label = 1;
                    case 1:
                        _b.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, fetch(entry.removeUrl)];
                    case 2:
                        _b.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        _a = _b.sent();
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        return _this;
    }
    RemoteStateSnapshots.prototype.componentDidMount = function () {
        this.refresh();
        // TODO: solve this by using "PluginComponent" with behaviors intead
        this._mounted = true;
        // this.subscribe(UploadedEvent, this.refresh);
    };
    RemoteStateSnapshots.prototype.componentWillUnmount = function () {
        this._mounted = false;
    };
    RemoteStateSnapshots.prototype.serverUrl = function (q) {
        if (!q)
            return this.state.params.options.serverUrl;
        return Object(_mol_util_url__WEBPACK_IMPORTED_MODULE_9__[/* urlCombine */ "a"])(this.state.params.options.serverUrl, q);
    };
    RemoteStateSnapshots.prototype.render = function () {
        var _this = this;
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](react__WEBPACK_IMPORTED_MODULE_2__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["SectionHeader"], { title: 'Remote States', accent: 'blue' }),
            !this.props.listOnly && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](react__WEBPACK_IMPORTED_MODULE_2__["Fragment"], null,
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_13__["ParameterControls"], { params: this.Params, values: this.state.params, onEnter: this.upload, onChange: function (p) {
                        var _a;
                        _this.setState({ params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _this.state.params), (_a = {}, _a[p.name] = p.value, _a)) });
                    }, isDisabled: this.state.isBusy }),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-flex-row' },
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { onClick: this.refresh, disabled: this.state.isBusy, svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RefreshSvg"] }),
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["CloudUploadSvg"], onClick: this.upload, disabled: this.state.isBusy, commit: true }, "Upload"))),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](RemoteStateSnapshotList, { entries: this.state.entries, isBusy: this.state.isBusy, serverUrl: this.state.params.options.serverUrl, fetch: this.fetch, remove: this.props.listOnly ? void 0 : this.remove }),
            this.props.listOnly && react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { style: { marginTop: '10px' } },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_13__["ParameterControls"], { params: this.ListOnlyParams, values: this.state.params, onEnter: this.upload, onChange: function (p) {
                        var _a;
                        _this.setState({ params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _this.state.params), (_a = {}, _a[p.name] = p.value, _a)) });
                    }, isDisabled: this.state.isBusy }),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-flex-row' },
                    react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { onClick: this.refresh, disabled: this.state.isBusy, icon: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["RefreshSvg"] }, "Refresh"))));
    };
    return RemoteStateSnapshots;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PluginUIComponent"]));

var RemoteStateSnapshotList = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(RemoteStateSnapshotList, _super);
    function RemoteStateSnapshotList() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.open = function (e) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var id, entry, url, qi;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                id = e.currentTarget.getAttribute('data-id');
                if (!id)
                    return [2 /*return*/];
                entry = this.props.entries.get(id);
                if (!entry)
                    return [2 /*return*/];
                e.preventDefault();
                url = "" + window.location, qi = url.indexOf('?');
                if (qi > 0)
                    url = url.substr(0, qi);
                window.open(url + "?snapshot-url=" + encodeURIComponent(entry.url), '_blank');
                return [2 /*return*/];
            });
        }); };
        return _this;
    }
    RemoteStateSnapshotList.prototype.render = function () {
        var _this = this;
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("ul", { style: { listStyle: 'none', marginTop: '10px' }, className: 'msp-state-list' }, this.props.entries.valueSeq().map(function (e) { return react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("li", { key: e.id, className: 'msp-flex-row' },
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["Button"], { "data-id": e.id, onClick: _this.props.fetch, disabled: _this.props.isBusy, onContextMenu: _this.open, title: 'Click to download, right-click to open in a new tab.' },
                e.name || new Date(e.timestamp).toLocaleString(),
                " ",
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("small", null, e.description)),
            !e.isSticky && _this.props.remove && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_11__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_12__["DeleteOutlinedSvg"], "data-id": e.id, title: 'Remove', onClick: _this.props.remove, disabled: _this.props.isBusy, small: true })); }));
    };
    return RemoteStateSnapshotList;
}(_base__WEBPACK_IMPORTED_MODULE_10__["PurePluginUIComponent"]));
//# sourceMappingURL=snapshots.js.map

/***/ }),
/* 286 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ subscribeTo; });

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeToArray.js
var subscribeToArray = __webpack_require__(374);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/hostReportError.js
var hostReportError = __webpack_require__(248);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeToPromise.js
/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */

var subscribeToPromise = function (promise) {
    return function (subscriber) {
        promise.then(function (value) {
            if (!subscriber.closed) {
                subscriber.next(value);
                subscriber.complete();
            }
        }, function (err) { return subscriber.error(err); })
            .then(null, hostReportError["a" /* hostReportError */]);
        return subscriber;
    };
};
//# sourceMappingURL=subscribeToPromise.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/iterator.js
var symbol_iterator = __webpack_require__(197);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeToIterable.js
/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */

var subscribeToIterable = function (iterable) {
    return function (subscriber) {
        var iterator = iterable[symbol_iterator["a" /* iterator */]]();
        do {
            var item = iterator.next();
            if (item.done) {
                subscriber.complete();
                break;
            }
            subscriber.next(item.value);
            if (subscriber.closed) {
                break;
            }
        } while (true);
        if (typeof iterator.return === 'function') {
            subscriber.add(function () {
                if (iterator.return) {
                    iterator.return();
                }
            });
        }
        return subscriber;
    };
};
//# sourceMappingURL=subscribeToIterable.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/observable.js
var observable = __webpack_require__(203);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeToObservable.js
/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */

var subscribeToObservable = function (obj) {
    return function (subscriber) {
        var obs = obj[observable["a" /* observable */]]();
        if (typeof obs.subscribe !== 'function') {
            throw new TypeError('Provided object does not correctly implement Symbol.observable');
        }
        else {
            return obs.subscribe(subscriber);
        }
    };
};
//# sourceMappingURL=subscribeToObservable.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isArrayLike.js
var isArrayLike = __webpack_require__(373);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isPromise.js
var isPromise = __webpack_require__(375);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isObject.js
var isObject = __webpack_require__(301);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/subscribeTo.js
/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */









var subscribeTo = function (result) {
    if (!!result && typeof result[observable["a" /* observable */]] === 'function') {
        return subscribeToObservable(result);
    }
    else if (Object(isArrayLike["a" /* isArrayLike */])(result)) {
        return Object(subscribeToArray["a" /* subscribeToArray */])(result);
    }
    else if (Object(isPromise["a" /* isPromise */])(result)) {
        return subscribeToPromise(result);
    }
    else if (!!result && typeof result[symbol_iterator["a" /* iterator */]] === 'function') {
        return subscribeToIterable(result);
    }
    else {
        var value = Object(isObject["a" /* isObject */])(result) ? 'an invalid object' : "'" + result + "'";
        var msg = "You provided " + value + " where a stream was expected."
            + ' You can provide an Observable, Promise, Array, or Iterable.';
        throw new TypeError(msg);
    }
};
//# sourceMappingURL=subscribeTo.js.map


/***/ }),
/* 287 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StateTransformParameters; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TransformControlBase; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32);
/* harmony import */ var _controls_parameters__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(66);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(60);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(14);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(19);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */









var StateTransformParameters = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateTransformParameters, _super);
    function StateTransformParameters() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onChange = function (_a) {
            var _b;
            var name = _a.name, value = _a.value;
            var params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _this.props.params), (_b = {}, _b[name] = value, _b));
            _this.props.events.onChange(params, _this.areInitial(params), _this.validate(params));
        };
        return _this;
    }
    StateTransformParameters.prototype.validate = function (params) {
        // TODO
        return void 0;
    };
    StateTransformParameters.prototype.areInitial = function (params) {
        return _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].areEqual(this.props.info.params, params, this.props.info.initialValues);
    };
    StateTransformParameters.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_3__["ParameterControls"], { params: this.props.info.params, values: this.props.params, onChange: this.onChange, onEnter: this.props.events.onEnter, isDisabled: this.props.isDisabled });
    };
    return StateTransformParameters;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PurePluginUIComponent"]));
(function (StateTransformParameters) {
    function areParamsEmpty(params) {
        var keys = Object.keys(params);
        for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) {
            var k = keys_1[_i];
            if (!params[k].isHidden)
                return false;
        }
        return true;
    }
    function infoFromAction(plugin, state, action, nodeRef) {
        var source = state.cells.get(nodeRef).obj;
        var params = action.definition.params ? action.definition.params(source, plugin) : {};
        var initialValues = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(params);
        return {
            initialValues: initialValues,
            params: params,
            isEmpty: areParamsEmpty(params)
        };
    }
    StateTransformParameters.infoFromAction = infoFromAction;
    function infoFromTransform(plugin, state, transform) {
        var cell = state.cells.get(transform.ref);
        // const source: StateObjectCell | undefined = (cell.sourceRef && state.cells.get(cell.sourceRef)!) || void 0;
        // const create = transform.transformer.definition.params;
        // const params = create ? create((source && source.obj) as any, plugin) : { };
        var params = (cell.params && cell.params.definition) || {};
        var initialValues = (cell.params && cell.params.values) || {};
        return {
            initialValues: initialValues,
            params: params,
            isEmpty: areParamsEmpty(params)
        };
    }
    StateTransformParameters.infoFromTransform = infoFromTransform;
})(StateTransformParameters || (StateTransformParameters = {}));
var TransformControlBase = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TransformControlBase, _super);
    function TransformControlBase() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.busy = new rxjs__WEBPACK_IMPORTED_MODULE_5__[/* Subject */ "a"]();
        _this.onEnter = function () {
            if (_this.state.error)
                return;
            _this.apply();
        };
        _this.autoApplyHandle = void 0;
        _this.events = {
            onEnter: _this.onEnter,
            onChange: function (params, isInitial, errors) {
                _this.clearAutoApply();
                _this.setState({ params: params, isInitial: isInitial, error: errors && errors[0] }, function () {
                    if (!isInitial && !_this.state.error && _this.canAutoApply(params)) {
                        _this.clearAutoApply();
                        _this.autoApplyHandle = setTimeout(_this.apply, 50);
                    }
                });
            }
        };
        _this.apply = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var _a;
            var _b, _c;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        this.clearAutoApply();
                        this.setState({ busy: true });
                        _d.label = 1;
                    case 1:
                        _d.trys.push([1, 3, 4, 5]);
                        return [4 /*yield*/, this.applyAction()];
                    case 2:
                        _d.sent();
                        return [3 /*break*/, 5];
                    case 3:
                        _a = _d.sent();
                        return [3 /*break*/, 5];
                    case 4:
                        (_c = (_b = this.props).onApply) === null || _c === void 0 ? void 0 : _c.call(_b);
                        this.busy.next(false);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        }); };
        _this.refresh = function () {
            _this.setState({ params: _this.getInfo().initialValues, isInitial: true, error: void 0 });
        };
        _this.setDefault = function () {
            var info = _this.getInfo();
            var params = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(info.params);
            _this.setState({ params: params, isInitial: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].areEqual(info.params, params, info.initialValues), error: void 0 });
        };
        _this.toggleExpanded = function () {
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
        };
        return _this;
    }
    TransformControlBase.prototype.clearAutoApply = function () {
        if (this.autoApplyHandle !== void 0) {
            clearTimeout(this.autoApplyHandle);
            this.autoApplyHandle = void 0;
        }
    };
    TransformControlBase.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.state.isBusy, function (b) {
            if (_this.state.busy !== b)
                _this.busy.next(b);
        });
        this.subscribe(this.busy, function (busy) {
            if (_this.state.busy !== busy)
                _this.setState({ busy: busy });
        });
    };
    TransformControlBase.prototype.renderApply = function () {
        var canApply = this.canApply();
        if (this.props.autoHideApply && (!canApply || this.canAutoApply(this.state.params)))
            return null;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-transform-apply-wrap' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_6__["RefreshSvg"], className: 'msp-transform-default-params', onClick: this.setDefault, disabled: this.state.busy, title: 'Set default params' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: "msp-transform-apply-wider" },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["Button"], { icon: canApply ? _controls_icons__WEBPACK_IMPORTED_MODULE_6__["CheckSvg"] : void 0, className: "msp-btn-commit msp-btn-commit-" + (canApply ? 'on' : 'off'), onClick: this.apply, disabled: !canApply }, this.props.applyLabel || this.applyText())));
    };
    TransformControlBase.prototype.renderDefault = function () {
        var info = this.getInfo();
        var isEmpty = info.isEmpty && this.isUpdate();
        var display = this.getHeader();
        var tId = this.getTransformerId();
        var ParamEditor = this.plugin.customParamEditors.has(tId)
            ? this.plugin.customParamEditors.get(tId)
            : StateTransformParameters;
        var wrapClass = this.state.isCollapsed
            ? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
            : 'msp-transform-wrapper';
        var params = null;
        if (!isEmpty && !this.state.isCollapsed) {
            var _a = this.getSourceAndTarget(), a = _a.a, b = _a.b, bCell = _a.bCell;
            var applyControl = this.renderApply();
            params = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ParamEditor, { info: info, a: a, b: b, bCell: bCell, events: this.events, params: this.state.params, isDisabled: this.state.busy }),
                applyControl);
        }
        var ctrl = react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: wrapClass, style: { marginBottom: this.props.noMargin ? 0 : void 0 } },
            display !== 'none' && !this.props.wrapInExpander && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-transform-header' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["Button"], { onClick: this.toggleExpanded, title: display.description },
                    !isEmpty && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_6__["Icon"], { svg: this.state.isCollapsed ? _controls_icons__WEBPACK_IMPORTED_MODULE_6__["ArrowRightSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_6__["ArrowDropDownSvg"] }),
                    display.name)),
            params);
        if (isEmpty || !this.props.wrapInExpander)
            return ctrl;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["ExpandGroup"], { header: this.isUpdate() ? "Update " + (display === 'none' ? '' : display.name) : "Apply " + (display === 'none' ? '' : display.name), headerLeftMargin: this.props.expanderHeaderLeftMargin }, ctrl);
    };
    TransformControlBase.prototype.renderSimple = function () {
        var _a, _b, _c;
        var info = this.getInfo();
        var canApply = this.canApply();
        var apply = react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["Button"], { icon: (_a = this.props.simpleApply) === null || _a === void 0 ? void 0 : _a.icon, title: (_b = this.props.simpleApply) === null || _b === void 0 ? void 0 : _b.title, disabled: this.state.busy || !canApply, onClick: this.apply, className: 'msp-btn-apply-simple' }, (_c = this.props.simpleApply) === null || _c === void 0 ? void 0 : _c.header),
            !info.isEmpty && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_7__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_6__["TuneSvg"], label: '', title: 'Options', toggle: this.toggleExpanded, isSelected: !this.state.isCollapsed, disabled: this.state.busy, style: { flex: '0 0 40px', padding: 0 } }));
        if (this.state.isCollapsed)
            return apply;
        var tId = this.getTransformerId();
        var ParamEditor = this.plugin.customParamEditors.has(tId)
            ? this.plugin.customParamEditors.get(tId)
            : StateTransformParameters;
        var _d = this.getSourceAndTarget(), a = _d.a, b = _d.b, bCell = _d.bCell;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            apply,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ParamEditor, { info: info, a: a, b: b, bCell: bCell, events: this.events, params: this.state.params, isDisabled: this.state.busy }));
    };
    TransformControlBase.prototype.render = function () {
        // console.log('rendering', ((this.props as any)?.transform?.transformer || (this.props as any)?.action)?.definition.display.name, +new Date)
        return this.props.simpleApply ? this.renderSimple() : this.renderDefault();
    };
    return TransformControlBase;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PurePluginUIComponent"]));
//# sourceMappingURL=common.js.map

/***/ }),
/* 288 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Download", function() { return /* binding */ Download; });
__webpack_require__.d(__webpack_exports__, "DownloadBlob", function() { return /* binding */ DownloadBlob; });
__webpack_require__.d(__webpack_exports__, "RawData", function() { return /* binding */ RawData; });
__webpack_require__.d(__webpack_exports__, "ReadFile", function() { return /* binding */ ReadFile; });
__webpack_require__.d(__webpack_exports__, "ParseBlob", function() { return /* binding */ ParseBlob; });
__webpack_require__.d(__webpack_exports__, "ParseCif", function() { return /* binding */ ParseCif; });
__webpack_require__.d(__webpack_exports__, "ParseCube", function() { return /* binding */ ParseCube; });
__webpack_require__.d(__webpack_exports__, "ParsePsf", function() { return /* binding */ ParsePsf; });
__webpack_require__.d(__webpack_exports__, "ParsePly", function() { return /* binding */ ParsePly; });
__webpack_require__.d(__webpack_exports__, "ParseCcp4", function() { return /* binding */ ParseCcp4; });
__webpack_require__.d(__webpack_exports__, "ParseDsn6", function() { return /* binding */ ParseDsn6; });
__webpack_require__.d(__webpack_exports__, "ParseDx", function() { return /* binding */ ParseDx; });
__webpack_require__.d(__webpack_exports__, "ImportString", function() { return /* binding */ ImportString; });
__webpack_require__.d(__webpack_exports__, "ImportJson", function() { return /* binding */ ImportJson; });
__webpack_require__.d(__webpack_exports__, "ParseJson", function() { return /* binding */ ParseJson; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db/column-helpers.js
var column_helpers = __webpack_require__(186);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/ccp4/parser.js
var parser = __webpack_require__(365);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js + 8 modules
var cif = __webpack_require__(31);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/result.js
var reader_result = __webpack_require__(67);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/file-handle.js
var file_handle = __webpack_require__(366);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/simple-buffer.js
var simple_buffer = __webpack_require__(192);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/dsn6/parser.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var dsn6HeaderSize = 512;
function parseBrixHeader(str) {
    return {
        xStart: parseInt(str.substr(10, 5)),
        yStart: parseInt(str.substr(15, 5)),
        zStart: parseInt(str.substr(20, 5)),
        xExtent: parseInt(str.substr(32, 5)),
        yExtent: parseInt(str.substr(38, 5)),
        zExtent: parseInt(str.substr(42, 5)),
        xRate: parseInt(str.substr(52, 5)),
        yRate: parseInt(str.substr(58, 5)),
        zRate: parseInt(str.substr(62, 5)),
        xlen: parseFloat(str.substr(73, 10)),
        ylen: parseFloat(str.substr(83, 10)),
        zlen: parseFloat(str.substr(93, 10)),
        alpha: parseFloat(str.substr(103, 10)),
        beta: parseFloat(str.substr(113, 10)),
        gamma: parseFloat(str.substr(123, 10)),
        divisor: parseFloat(str.substr(138, 12)),
        summand: parseInt(str.substr(155, 8)),
        sigma: parseFloat(str.substr(170, 12))
    };
}
function parseDsn6Header(buffer, littleEndian) {
    var readInt = littleEndian ? function (o) { return buffer.readInt16LE(o * 2); } : function (o) { return buffer.readInt16BE(o * 2); };
    var factor = 1 / readInt(17);
    return {
        xStart: readInt(0),
        yStart: readInt(1),
        zStart: readInt(2),
        xExtent: readInt(3),
        yExtent: readInt(4),
        zExtent: readInt(5),
        xRate: readInt(6),
        yRate: readInt(7),
        zRate: readInt(8),
        xlen: readInt(9) * factor,
        ylen: readInt(10) * factor,
        zlen: readInt(11) * factor,
        alpha: readInt(12) * factor,
        beta: readInt(13) * factor,
        gamma: readInt(14) * factor,
        divisor: readInt(15) / 100,
        summand: readInt(16),
        sigma: undefined
    };
}
function getBlocks(header) {
    var xExtent = header.xExtent, yExtent = header.yExtent, zExtent = header.zExtent;
    var xBlocks = Math.ceil(xExtent / 8);
    var yBlocks = Math.ceil(yExtent / 8);
    var zBlocks = Math.ceil(zExtent / 8);
    return { xBlocks: xBlocks, yBlocks: yBlocks, zBlocks: zBlocks };
}
function readDsn6Header(file) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var buffer, brixStr, isBrix, littleEndian, header;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, file.readBuffer(0, dsn6HeaderSize)];
                case 1:
                    buffer = (_a.sent()).buffer;
                    brixStr = String.fromCharCode.apply(null, buffer);
                    isBrix = brixStr.startsWith(':-)');
                    littleEndian = isBrix || buffer.readInt16LE(18 * 2) === 100;
                    header = isBrix ? parseBrixHeader(brixStr) : parseDsn6Header(buffer, littleEndian);
                    return [2 /*return*/, { header: header, littleEndian: littleEndian }];
            }
        });
    });
}
function parseDsn6Values(header, source, target, littleEndian) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var divisor, summand, xExtent, yExtent, zExtent, _a, xBlocks, yBlocks, zBlocks, offset, zz, yy, xx, k, z, j, y, i, x, idx;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            if (!littleEndian) {
                // even though the values are one byte they need to be swapped like they are 2
                simple_buffer["a" /* SimpleBuffer */].flipByteOrderInPlace2(source.buffer);
            }
            divisor = header.divisor, summand = header.summand, xExtent = header.xExtent, yExtent = header.yExtent, zExtent = header.zExtent;
            _a = getBlocks(header), xBlocks = _a.xBlocks, yBlocks = _a.yBlocks, zBlocks = _a.zBlocks;
            offset = 0;
            // loop over blocks
            for (zz = 0; zz < zBlocks; ++zz) {
                for (yy = 0; yy < yBlocks; ++yy) {
                    for (xx = 0; xx < xBlocks; ++xx) {
                        // loop inside block
                        for (k = 0; k < 8; ++k) {
                            z = 8 * zz + k;
                            for (j = 0; j < 8; ++j) {
                                y = 8 * yy + j;
                                for (i = 0; i < 8; ++i) {
                                    x = 8 * xx + i;
                                    // check if remaining slice-part contains values
                                    if (x < xExtent && y < yExtent && z < zExtent) {
                                        idx = ((((x * yExtent) + y) * zExtent) + z);
                                        target[idx] = (source[offset] - summand) / divisor;
                                        ++offset;
                                    }
                                    else {
                                        offset += 8 - i;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return [2 /*return*/];
        });
    });
}
function getDsn6Counts(header) {
    var xExtent = header.xExtent, yExtent = header.yExtent, zExtent = header.zExtent;
    var _a = getBlocks(header), xBlocks = _a.xBlocks, yBlocks = _a.yBlocks, zBlocks = _a.zBlocks;
    var valueCount = xExtent * yExtent * zExtent;
    var count = xBlocks * 8 * yBlocks * 8 * zBlocks * 8;
    var elementByteSize = 1;
    var byteCount = count * elementByteSize;
    return { count: count, byteCount: byteCount, valueCount: valueCount };
}
function parseInternal(file, size, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _a, header, littleEndian, buffer, valueCount, values, result;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, ctx.update({ message: 'Parsing DSN6/BRIX file...' })];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, readDsn6Header(file)];
                case 2:
                    _a = _b.sent(), header = _a.header, littleEndian = _a.littleEndian;
                    return [4 /*yield*/, file.readBuffer(dsn6HeaderSize, size - dsn6HeaderSize)];
                case 3:
                    buffer = (_b.sent()).buffer;
                    valueCount = getDsn6Counts(header).valueCount;
                    values = new Float32Array(valueCount);
                    return [4 /*yield*/, parseDsn6Values(header, buffer, values, littleEndian)];
                case 4:
                    _b.sent();
                    result = { header: header, values: values, name: file.name };
                    return [2 /*return*/, result];
            }
        });
    });
}
function parseFile(file, size) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse DSN6/BRIX', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var _a, _b, e_1;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    _c.trys.push([0, 2, , 3]);
                    _b = (_a = reader_result["a" /* ReaderResult */]).success;
                    return [4 /*yield*/, parseInternal(file, size, ctx)];
                case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
                case 2:
                    e_1 = _c.sent();
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].error(e_1)];
                case 3: return [2 /*return*/];
            }
        });
    }); });
}
function parse(buffer, name) {
    return parseFile(file_handle["a" /* FileHandle */].fromBuffer(simple_buffer["a" /* SimpleBuffer */].fromUint8Array(buffer), name), buffer.length);
}
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/ply/schema.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// http://paulbourke.net/dataformats/ply/
// https://en.wikipedia.org/wiki/PLY_(file_format)
var PlyTypeByteLength = {
    'char': 1,
    'uchar': 1,
    'short': 2,
    'ushort': 2,
    'int': 4,
    'uint': 4,
    'float': 4,
    'double': 8,
    'int8': 1,
    'uint8': 1,
    'int16': 2,
    'uint16': 2,
    'int32': 4,
    'uint32': 4,
    'float32': 4,
    'float64': 8
};
var PlyTypes = new Set(Object.keys(PlyTypeByteLength));
function PlyType(str) {
    if (!PlyTypes.has(str))
        throw new Error("unknown ply type '" + str + "'");
    return str;
}
function PlyFile(elements, elementNames, comments) {
    var elementMap = new Map();
    for (var i = 0, il = elementNames.length; i < il; ++i) {
        elementMap.set(elementNames[i], elements[i]);
    }
    return {
        comments: comments,
        elementNames: elementNames,
        getElement: function (name) {
            return elementMap.get(name);
        }
    };
}
//# sourceMappingURL=schema.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/tokenizer.js
var text_tokenizer = __webpack_require__(20);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/column/token.js
var token = __webpack_require__(73);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/ply/parser.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







function State(data, runtimeCtx) {
    var tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
    return {
        data: data,
        tokenizer: tokenizer,
        runtimeCtx: runtimeCtx,
        comments: [],
        elementSpecs: [],
        elements: []
    };
}
function markHeader(tokenizer) {
    var endHeaderIndex = tokenizer.data.indexOf('end_header', tokenizer.position);
    if (endHeaderIndex === -1)
        throw new Error("no 'end_header' record found");
    // TODO set `tokenizer.lineNumber` correctly
    tokenizer.tokenStart = tokenizer.position;
    tokenizer.tokenEnd = endHeaderIndex;
    tokenizer.position = endHeaderIndex;
    text_tokenizer["b" /* Tokenizer */].eatLine(tokenizer);
}
function parseHeader(state) {
    var tokenizer = state.tokenizer, comments = state.comments, elementSpecs = state.elementSpecs;
    markHeader(tokenizer);
    var headerLines = text_tokenizer["b" /* Tokenizer */].getTokenString(tokenizer).split(/\r?\n/);
    if (headerLines[0] !== 'ply')
        throw new Error("data not starting with 'ply'");
    if (headerLines[1] !== 'format ascii 1.0')
        throw new Error("format not 'ascii 1.0'");
    var currentName;
    var currentCount;
    var currentProperties;
    function addCurrentElementSchema() {
        if (currentName !== undefined && currentCount !== undefined && currentProperties !== undefined) {
            var isList = false;
            for (var i = 0, il = currentProperties.length; i < il; ++i) {
                var p = currentProperties[i];
                if (p.kind === 'list') {
                    isList = true;
                    break;
                }
            }
            if (isList && currentProperties.length !== 1) {
                // TODO handle lists with appended properties
                //      currently only the list part will be accessible
            }
            if (isList) {
                elementSpecs.push({
                    kind: 'list',
                    name: currentName,
                    count: currentCount,
                    property: currentProperties[0]
                });
            }
            else {
                elementSpecs.push({
                    kind: 'table',
                    name: currentName,
                    count: currentCount,
                    properties: currentProperties
                });
            }
        }
    }
    for (var i = 2, il = headerLines.length; i < il; ++i) {
        var l = headerLines[i];
        var ls = l.split(' ');
        if (l.startsWith('comment')) {
            comments.push(l.substr(8));
        }
        else if (l.startsWith('element')) {
            addCurrentElementSchema();
            currentProperties = [];
            currentName = ls[1];
            currentCount = parseInt(ls[2]);
        }
        else if (l.startsWith('property')) {
            if (currentProperties === undefined)
                throw new Error("properties outside of element");
            if (ls[1] === 'list') {
                currentProperties.push({
                    kind: 'list',
                    countType: PlyType(ls[2]),
                    dataType: PlyType(ls[3]),
                    name: ls[4]
                });
            }
            else {
                currentProperties.push({
                    kind: 'column',
                    type: PlyType(ls[1]),
                    name: ls[2]
                });
            }
        }
        else if (l.startsWith('end_header')) {
            addCurrentElementSchema();
        }
        else {
            console.warn('unknown header line');
        }
    }
}
function parseElements(state) {
    var elementSpecs = state.elementSpecs;
    for (var i = 0, il = elementSpecs.length; i < il; ++i) {
        var spec = elementSpecs[i];
        if (spec.kind === 'table')
            parseTableElement(state, spec);
        else if (spec.kind === 'list')
            parseListElement(state, spec);
    }
}
function getColumnSchema(type) {
    switch (type) {
        case 'char':
        case 'uchar':
        case 'int8':
        case 'uint8':
        case 'short':
        case 'ushort':
        case 'int16':
        case 'uint16':
        case 'int':
        case 'uint':
        case 'int32':
        case 'uint32':
            return db["Column"].Schema.int;
        case 'float':
        case 'double':
        case 'float32':
        case 'float64':
            return db["Column"].Schema.float;
    }
}
function parseTableElement(state, spec) {
    var elements = state.elements, tokenizer = state.tokenizer;
    var count = spec.count, properties = spec.properties;
    var propertyCount = properties.length;
    var propertyNames = [];
    var propertyTypes = [];
    var propertyTokens = [];
    var propertyColumns = new Map();
    for (var i = 0, il = propertyCount; i < il; ++i) {
        var tokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
        propertyTokens.push(tokens);
    }
    for (var i = 0, il = count; i < il; ++i) {
        for (var j = 0, jl = propertyCount; j < jl; ++j) {
            text_tokenizer["b" /* Tokenizer */].skipWhitespace(tokenizer);
            text_tokenizer["b" /* Tokenizer */].markStart(tokenizer);
            text_tokenizer["b" /* Tokenizer */].eatValue(tokenizer);
            text_tokenizer["a" /* TokenBuilder */].addUnchecked(propertyTokens[j], tokenizer.tokenStart, tokenizer.tokenEnd);
        }
    }
    for (var i = 0, il = propertyCount; i < il; ++i) {
        var _a = properties[i], type = _a.type, name_1 = _a.name;
        var column = Object(token["a" /* TokenColumn */])(propertyTokens[i], getColumnSchema(type));
        propertyNames.push(name_1);
        propertyTypes.push(type);
        propertyColumns.set(name_1, column);
    }
    elements.push({
        kind: 'table',
        rowCount: count,
        propertyNames: propertyNames,
        propertyTypes: propertyTypes,
        getProperty: function (name) { return propertyColumns.get(name); }
    });
}
function parseListElement(state, spec) {
    var elements = state.elements, tokenizer = state.tokenizer;
    var count = spec.count, property = spec.property;
    // initial tokens size assumes triangle index data
    var tokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2 * 3);
    var offsets = new Uint32Array(count + 1);
    var entryCount = 0;
    for (var i = 0, il = count; i < il; ++i) {
        text_tokenizer["b" /* Tokenizer */].skipWhitespace(tokenizer);
        text_tokenizer["b" /* Tokenizer */].markStart(tokenizer);
        while (text_tokenizer["b" /* Tokenizer */].skipWhitespace(tokenizer) !== 10) {
            ++entryCount;
            text_tokenizer["b" /* Tokenizer */].markStart(tokenizer);
            text_tokenizer["b" /* Tokenizer */].eatValue(tokenizer);
            text_tokenizer["a" /* TokenBuilder */].addToken(tokens, tokenizer);
        }
        offsets[i + 1] = entryCount;
    }
    /** holds row value entries transiently */
    var listValue = {
        entries: [],
        count: 0
    };
    var column = Object(token["a" /* TokenColumn */])(tokens, getColumnSchema(property.dataType));
    elements.push({
        kind: 'list',
        rowCount: count,
        name: property.name,
        type: property.dataType,
        value: function (row) {
            var offset = offsets[row] + 1;
            var count = column.value(offset - 1);
            for (var i = offset, il = offset + count; i < il; ++i) {
                listValue.entries[i - offset] = column.value(i);
            }
            listValue.count = count;
            return listValue;
        }
    });
}
function parser_parseInternal(data, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var state, elements, elementSpecs, comments, elementNames, result;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            state = State(data, ctx);
            ctx.update({ message: 'Parsing...', current: 0, max: data.length });
            parseHeader(state);
            parseElements(state);
            elements = state.elements, elementSpecs = state.elementSpecs, comments = state.comments;
            elementNames = elementSpecs.map(function (s) { return s.name; });
            result = PlyFile(elements, elementNames, comments);
            return [2 /*return*/, reader_result["a" /* ReaderResult */].success(result)];
        });
    });
}
function parser_parse(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse PLY', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, parser_parseInternal(data, ctx)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
/* harmony default export */ var ply_parser = (parser_parse);
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/psf/parser.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var readLine = text_tokenizer["b" /* Tokenizer */].readLine, skipWhitespace = text_tokenizer["b" /* Tokenizer */].skipWhitespace, eatValue = text_tokenizer["b" /* Tokenizer */].eatValue, eatLine = text_tokenizer["b" /* Tokenizer */].eatLine, markStart = text_tokenizer["b" /* Tokenizer */].markStart;
var parser_reWhitespace = /\s+/;
var reTitle = /(^\*|REMARK)*/;
function parser_State(tokenizer, runtimeCtx) {
    return {
        tokenizer: tokenizer,
        runtimeCtx: runtimeCtx,
    };
}
function handleAtoms(state, count) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, atomId, segmentName, residueId, residueName, atomName, atomType, charge, mass, length, linesAlreadyRead;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = state.tokenizer;
                    atomId = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    segmentName = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    residueId = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    residueName = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    atomName = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    atomType = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    charge = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    mass = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    length = tokenizer.length;
                    linesAlreadyRead = 0;
                    return [4 /*yield*/, Object(mol_task["c" /* chunkedSubtask */])(state.runtimeCtx, 10, void 0, function (chunkSize) {
                            var linesToRead = Math.min(count - linesAlreadyRead, chunkSize);
                            for (var i = 0; i < linesToRead; ++i) {
                                for (var j = 0; j < 8; ++j) {
                                    skipWhitespace(tokenizer);
                                    markStart(tokenizer);
                                    eatValue(tokenizer);
                                    switch (j) {
                                        case 0:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomId, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 1:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(segmentName, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 2:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(residueId, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 3:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(residueName, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 4:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomName, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 5:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomType, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 6:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(charge, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 7:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(mass, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                    }
                                }
                                // ignore any extra columns
                                eatLine(tokenizer);
                                markStart(tokenizer);
                            }
                            linesAlreadyRead += linesToRead;
                            return linesToRead;
                        }, function (ctx) { return ctx.update({ message: 'Parsing...', current: tokenizer.position, max: length }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, {
                            count: count,
                            atomId: Object(token["c" /* default */])(atomId)(db["Column"].Schema.int),
                            segmentName: Object(token["c" /* default */])(segmentName)(db["Column"].Schema.str),
                            residueId: Object(token["c" /* default */])(residueId)(db["Column"].Schema.int),
                            residueName: Object(token["c" /* default */])(residueName)(db["Column"].Schema.str),
                            atomName: Object(token["c" /* default */])(atomName)(db["Column"].Schema.str),
                            atomType: Object(token["c" /* default */])(atomType)(db["Column"].Schema.str),
                            charge: Object(token["c" /* default */])(charge)(db["Column"].Schema.float),
                            mass: Object(token["c" /* default */])(mass)(db["Column"].Schema.float)
                        }];
            }
        });
    });
}
function handleBonds(state, count) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, atomIdA, atomIdB, length, bondsAlreadyRead;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = state.tokenizer;
                    atomIdA = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    atomIdB = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
                    length = tokenizer.length;
                    bondsAlreadyRead = 0;
                    return [4 /*yield*/, Object(mol_task["c" /* chunkedSubtask */])(state.runtimeCtx, 10, void 0, function (chunkSize) {
                            var bondsToRead = Math.min(count - bondsAlreadyRead, chunkSize);
                            for (var i = 0; i < bondsToRead; ++i) {
                                for (var j = 0; j < 2; ++j) {
                                    skipWhitespace(tokenizer);
                                    markStart(tokenizer);
                                    eatValue(tokenizer);
                                    switch (j) {
                                        case 0:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomIdA, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 1:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomIdB, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                    }
                                }
                            }
                            bondsAlreadyRead += bondsToRead;
                            return bondsToRead;
                        }, function (ctx) { return ctx.update({ message: 'Parsing...', current: tokenizer.position, max: length }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, {
                            count: count,
                            atomIdA: Object(token["c" /* default */])(atomIdA)(db["Column"].Schema.int),
                            atomIdB: Object(token["c" /* default */])(atomIdB)(db["Column"].Schema.int),
                        }];
            }
        });
    });
}
function parseTitle(state, count) {
    var title = [];
    for (var i = 0; i < count; ++i) {
        var line = readLine(state.tokenizer);
        title.push(line.replace(reTitle, '').trim());
    }
    return title;
}
function psf_parser_parseInternal(data, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, state, title, atoms, bonds, id, line, numTitle, numAtoms, numBonds, result;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
                    state = parser_State(tokenizer, ctx);
                    title = undefined;
                    atoms = undefined;
                    bonds = undefined;
                    id = readLine(state.tokenizer).trim();
                    _a.label = 1;
                case 1:
                    if (!(tokenizer.tokenEnd < tokenizer.length)) return [3 /*break*/, 8];
                    line = readLine(state.tokenizer).trim();
                    if (!line.includes('!NTITLE')) return [3 /*break*/, 2];
                    numTitle = parseInt(line.split(parser_reWhitespace)[0]);
                    title = parseTitle(state, numTitle);
                    return [3 /*break*/, 7];
                case 2:
                    if (!line.includes('!NATOM')) return [3 /*break*/, 4];
                    numAtoms = parseInt(line.split(parser_reWhitespace)[0]);
                    return [4 /*yield*/, handleAtoms(state, numAtoms)];
                case 3:
                    atoms = _a.sent();
                    return [3 /*break*/, 7];
                case 4:
                    if (!line.includes('!NBOND')) return [3 /*break*/, 6];
                    numBonds = parseInt(line.split(parser_reWhitespace)[0]);
                    return [4 /*yield*/, handleBonds(state, numBonds)];
                case 5:
                    bonds = _a.sent();
                    return [3 /*break*/, 8]; // TODO: don't break when the below are implemented
                case 6:
                    if (line.includes('!NTHETA')) {
                        // TODO
                    }
                    else if (line.includes('!NPHI')) {
                        // TODO
                    }
                    else if (line.includes('!NIMPHI')) {
                        // TODO
                    }
                    else if (line.includes('!NDON')) {
                        // TODO
                    }
                    else if (line.includes('!NACC')) {
                        // TODO
                    }
                    else if (line.includes('!NNB')) {
                        // TODO
                    }
                    else if (line.includes('!NGRP NST2')) {
                        // TODO
                    }
                    else if (line.includes('!MOLNT')) {
                        // TODO
                    }
                    else if (line.includes('!NUMLP NUMLPH')) {
                        // TODO
                    }
                    else if (line.includes('!NCRTERM')) {
                        // TODO
                    }
                    _a.label = 7;
                case 7: return [3 /*break*/, 1];
                case 8:
                    if (title === undefined) {
                        title = [];
                    }
                    if (atoms === undefined) {
                        return [2 /*return*/, reader_result["a" /* ReaderResult */].error('no atoms data')];
                    }
                    if (bonds === undefined) {
                        return [2 /*return*/, reader_result["a" /* ReaderResult */].error('no bonds data')];
                    }
                    result = {
                        id: id,
                        title: title,
                        atoms: atoms,
                        bonds: bonds
                    };
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success(result)];
            }
        });
    });
}
function parsePsf(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse PSF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, psf_parser_parseInternal(data, ctx)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/data-source.js
var data_source = __webpack_require__(177);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/assets.js
var mol_util_assets = __webpack_require__(114);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/number-parser.js
var number_parser = __webpack_require__(97);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/cube/parser.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from NGL.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var bohrToAngstromFactor = 0.529177210859;
function readHeader(tokenizer) {
    var headerLines = text_tokenizer["b" /* Tokenizer */].readLines(tokenizer, 6);
    var h = function (k, l) {
        var field = +headerLines[k].trim().split(/\s+/g)[l];
        return Number.isNaN(field) ? 0 : field;
    };
    var basis = function (i) {
        var n = h(i + 2, 0);
        var s = bohrToAngstromFactor;
        return [Math.abs(n), linear_algebra["Vec3"].create(h(i + 2, 1) * s, h(i + 2, 2) * s, h(i + 2, 3) * s), n];
    };
    var comment1 = headerLines[0].trim();
    var comment2 = headerLines[1].trim();
    var _a = basis(0), atomCount = _a[0], origin = _a[1], rawAtomCount = _a[2];
    var _b = basis(1), NVX = _b[0], basisX = _b[1];
    var _c = basis(2), NVY = _c[0], basisY = _c[1];
    var _d = basis(3), NVZ = _d[0], basisZ = _d[1];
    var atoms = readAtoms(tokenizer, atomCount, bohrToAngstromFactor);
    var dataSetIds = [];
    if (rawAtomCount >= 0) {
        var nVal = h(2, 4);
        if (nVal === 0)
            nVal = 1;
        for (var i = 0; i < nVal; i++)
            dataSetIds.push(i);
    }
    else {
        var counts = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim().split(/\s+/g);
        for (var i = 0, _i = +counts[0]; i < _i; i++)
            dataSetIds.push(+counts[i + 1]);
    }
    var header = { orbitals: rawAtomCount < 0, comment1: comment1, comment2: comment2, atomCount: atomCount, origin: origin, dim: linear_algebra["Vec3"].create(NVX, NVY, NVZ), basisX: basisX, basisY: basisY, basisZ: basisZ, dataSetIds: dataSetIds };
    return { header: header, atoms: atoms };
}
function readAtoms(tokenizer, count, scaleFactor) {
    var number = new Int32Array(count);
    var value = new Float64Array(count);
    var x = new Float32Array(count);
    var y = new Float32Array(count);
    var z = new Float32Array(count);
    for (var i = 0; i < count; i++) {
        var fields = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim().split(/\s+/g);
        number[i] = +fields[0];
        value[i] = +fields[1];
        x[i] = +fields[2] * scaleFactor;
        y[i] = +fields[3] * scaleFactor;
        z[i] = +fields[4] * scaleFactor;
    }
    return {
        count: count,
        number: db["Column"].ofArray({ array: number, schema: db["Column"].Schema.int }),
        nuclearCharge: db["Column"].ofArray({ array: value, schema: db["Column"].Schema.float }),
        x: db["Column"].ofArray({ array: x, schema: db["Column"].Schema.float }),
        y: db["Column"].ofArray({ array: y, schema: db["Column"].Schema.float }),
        z: db["Column"].ofArray({ array: z, schema: db["Column"].Schema.float })
    };
}
function readValues(ctx, tokenizer, header) {
    var N = header.dim[0] * header.dim[1] * header.dim[2] * header.dataSetIds.length;
    var chunkSize = 100 * 100 * 100;
    var data = new Float64Array(N);
    var offset = 0;
    return Object(mol_task["c" /* chunkedSubtask */])(ctx, chunkSize, data, function (count, data) {
        var max = Math.min(N, offset + count);
        for (var i = offset; i < max; i++) {
            text_tokenizer["b" /* Tokenizer */].skipWhitespace(tokenizer);
            tokenizer.tokenStart = tokenizer.position;
            text_tokenizer["b" /* Tokenizer */].eatValue(tokenizer);
            data[i] = Object(number_parser["b" /* parseFloat */])(tokenizer.data, tokenizer.tokenStart, tokenizer.tokenEnd);
        }
        offset = max;
        return max === N ? 0 : chunkSize;
    }, function (ctx, _, i) { return ctx.update({ current: Math.min(i, N), max: N }); });
}
function parseCube(data, name) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse Cube', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var tokenizer, _a, header, atoms, values;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, taskCtx.update('Reading header...')];
                case 1:
                    _b.sent();
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
                    _a = readHeader(tokenizer), header = _a.header, atoms = _a.atoms;
                    return [4 /*yield*/, readValues(taskCtx, tokenizer, header)];
                case 2:
                    values = _b.sent();
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success({ header: header, atoms: atoms, values: values, name: name })];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/utf8.js
var utf8 = __webpack_require__(157);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/dx/parser.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from NGL.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







function parser_readHeader(tokenizer) {
    var header = { h: Object(linear_algebra["Vec3"])() };
    var headerByteCount = 0;
    var deltaLineCount = 0;
    var reWhitespace = /\s+/g;
    while (true) {
        var line = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer);
        var ls = void 0;
        if (line.startsWith('object 1')) {
            ls = line.split(reWhitespace);
            header.dim = linear_algebra["Vec3"].create(parseInt(ls[5]), parseInt(ls[6]), parseInt(ls[7]));
        }
        else if (line.startsWith('origin')) {
            ls = line.split(reWhitespace);
            header.min = linear_algebra["Vec3"].create(parseFloat(ls[1]), parseFloat(ls[2]), parseFloat(ls[3]));
        }
        else if (line.startsWith('delta')) {
            ls = line.split(reWhitespace);
            if (deltaLineCount === 0) {
                header.h[0] = parseFloat(ls[1]);
            }
            else if (deltaLineCount === 1) {
                header.h[1] = parseFloat(ls[2]);
            }
            else if (deltaLineCount === 2) {
                header.h[2] = parseFloat(ls[3]);
            }
            deltaLineCount += 1;
        }
        else if (line.startsWith('object 3')) {
            headerByteCount += line.length + 1;
            break;
        }
        headerByteCount += line.length + 1;
    }
    return { header: header, headerByteCount: headerByteCount };
}
function readValuesText(ctx, tokenizer, header) {
    var N = header.dim[0] * header.dim[1] * header.dim[2];
    var chunkSize = 100 * 100 * 100;
    var data = new Float64Array(N);
    var offset = 0;
    return Object(mol_task["c" /* chunkedSubtask */])(ctx, chunkSize, data, function (count, data) {
        var max = Math.min(N, offset + count);
        for (var i = offset; i < max; i++) {
            text_tokenizer["b" /* Tokenizer */].skipWhitespace(tokenizer);
            tokenizer.tokenStart = tokenizer.position;
            text_tokenizer["b" /* Tokenizer */].eatValue(tokenizer);
            data[i] = Object(number_parser["b" /* parseFloat */])(tokenizer.data, tokenizer.tokenStart, tokenizer.tokenEnd);
        }
        offset = max;
        return max === N ? 0 : chunkSize;
    }, function (ctx, _, i) { return ctx.update({ current: Math.min(i, N), max: N }); });
}
function parseText(taskCtx, data, name) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, header, values;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, taskCtx.update('Reading header...')];
                case 1:
                    _a.sent();
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
                    header = parser_readHeader(tokenizer).header;
                    return [4 /*yield*/, taskCtx.update('Reading values...')];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, readValuesText(taskCtx, tokenizer, header)];
                case 3:
                    values = _a.sent();
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success({ header: header, values: values, name: name })];
            }
        });
    });
}
function parseBinary(taskCtx, data, name) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var headerString, tokenizer, _a, header, headerByteCount, size, dv, values, i;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, taskCtx.update('Reading header...')];
                case 1:
                    _b.sent();
                    headerString = Object(utf8["b" /* utf8Read */])(data, 0, 1000);
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(headerString);
                    _a = parser_readHeader(tokenizer), header = _a.header, headerByteCount = _a.headerByteCount;
                    return [4 /*yield*/, taskCtx.update('Reading values...')];
                case 2:
                    _b.sent();
                    size = header.dim[0] * header.dim[1] * header.dim[2];
                    dv = new DataView(data.buffer, data.byteOffset + headerByteCount);
                    values = new Float64Array(size);
                    for (i = 0; i < size; i++) {
                        values[i] = dv.getFloat64(i * 8, true);
                    }
                    // TODO: why doesnt this work? throw "attempting to construct out-of-bounds TypedArray"
                    // const values = new Float64Array(data.buffer, data.byteOffset + headerByteCount, header.dim[0] * header.dim[1] * header.dim[2]);
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success({ header: header, values: values, name: name })];
            }
        });
    });
}
function parseDx(data, name) {
    return mol_task["b" /* Task */].create('Parse Cube', function (taskCtx) {
        if (typeof data === 'string')
            return parseText(taskCtx, data, name);
        return parseBinary(taskCtx, data, name);
    });
}
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/data.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






























var Download = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'download',
    display: { name: 'Download', description: 'Download string or binary data from the specified URL' },
    from: [objects["a" /* PluginStateObject */].Root],
    to: [objects["a" /* PluginStateObject */].Data.String, objects["a" /* PluginStateObject */].Data.Binary],
    params: {
        url: param_definition["ParamDefinition"].Url('https://www.ebi.ac.uk/pdbe/static/entry/1cbs_updated.cif', { description: 'Resource URL. Must be the same domain or support CORS.' }),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('')),
        isBinary: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { description: 'If true, download data as binary (string otherwise)' }))
    }
})({
    apply: function (_a, plugin) {
        var _this = this;
        var p = _a.params, cache = _a.cache;
        return mol_task["b" /* Task */].create('Download', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var url, asset;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = mol_util_assets["Asset"].getUrlAsset(plugin.managers.asset, p.url);
                        return [4 /*yield*/, plugin.managers.asset.resolve(url, p.isBinary ? 'binary' : 'string').runInContext(ctx)];
                    case 1:
                        asset = _a.sent();
                        cache.asset = asset;
                        return [2 /*return*/, p.isBinary
                                ? new objects["a" /* PluginStateObject */].Data.Binary(asset.data, { label: p.label ? p.label : url.url })
                                : new objects["a" /* PluginStateObject */].Data.String(asset.data, { label: p.label ? p.label : url.url })];
                }
            });
        }); });
    },
    dispose: function (_a) {
        var _b, _c;
        var cache = _a.cache;
        (_c = (_b = cache) === null || _b === void 0 ? void 0 : _b.asset) === null || _c === void 0 ? void 0 : _c.dispose();
    },
    update: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (oldParams.url !== newParams.url || oldParams.isBinary !== newParams.isBinary)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.label !== newParams.label) {
            b.label = newParams.label || ((typeof newParams.url === 'string') ? newParams.url : newParams.url.url);
            return mol_state["StateTransformer"].UpdateResult.Updated;
        }
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    }
});
var DownloadBlob = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'download-blob',
    display: { name: 'Download Blob', description: 'Download multiple string or binary data from the specified URLs.' },
    from: objects["a" /* PluginStateObject */].Root,
    to: objects["a" /* PluginStateObject */].Data.Blob,
    params: {
        sources: param_definition["ParamDefinition"].ObjectList({
            id: param_definition["ParamDefinition"].Text('', { label: 'Unique ID' }),
            url: param_definition["ParamDefinition"].Url('https://www.ebi.ac.uk/pdbe/static/entry/1cbs_updated.cif', { description: 'Resource URL. Must be the same domain or support CORS.' }),
            isBinary: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { description: 'If true, download data as binary (string otherwise)' })),
            canFail: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { description: 'Indicate whether the download can fail and not be included in the blob as a result.' }))
        }, function (e) { return e.id + ": " + e.url; }),
        maxConcurrency: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Numeric(4, { min: 1, max: 12, step: 1 }, { description: 'The maximum number of concurrent downloads.' }))
    }
})({
    apply: function (_a, plugin) {
        var _this = this;
        var params = _a.params, cache = _a.cache;
        return mol_task["b" /* Task */].create('Download Blob', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var entries, data, assets, i, r, src;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        entries = [];
                        return [4 /*yield*/, Object(data_source["b" /* ajaxGetMany */])(ctx, plugin.managers.asset, params.sources, params.maxConcurrency || 4)];
                    case 1:
                        data = _a.sent();
                        assets = [];
                        for (i = 0; i < data.length; i++) {
                            r = data[i], src = params.sources[i];
                            if (r.kind === 'error')
                                plugin.log.warn("Download " + r.id + " (" + src.url + ") failed: " + r.error);
                            else {
                                assets.push(r.result);
                                entries.push(src.isBinary
                                    ? { id: r.id, kind: 'binary', data: r.result.data }
                                    : { id: r.id, kind: 'string', data: r.result.data });
                            }
                        }
                        cache.assets = assets;
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Data.Blob(entries, { label: 'Data Blob', description: entries.length + " " + (entries.length === 1 ? 'entry' : 'entries') })];
                }
            });
        }); });
    },
    dispose: function (_a, plugin) {
        var _b;
        var cache = _a.cache;
        var assets = (_b = cache) === null || _b === void 0 ? void 0 : _b.assets;
        if (!assets)
            return;
        for (var _i = 0, assets_1 = assets; _i < assets_1.length; _i++) {
            var a = assets_1[_i];
            a.dispose();
        }
    }
    // TODO: ??
    // update({ oldParams, newParams, b }) {
    //     return 0 as any;
    //     // if (oldParams.url !== newParams.url || oldParams.isBinary !== newParams.isBinary) return StateTransformer.UpdateResult.Recreate;
    //     // if (oldParams.label !== newParams.label) {
    //     //     (b.label as string) = newParams.label || newParams.url;
    //     //     return StateTransformer.UpdateResult.Updated;
    //     // }
    //     // return StateTransformer.UpdateResult.Unchanged;
    // }
});
var RawData = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'raw-data',
    display: { name: 'Raw Data', description: 'Raw data supplied by value.' },
    from: [objects["a" /* PluginStateObject */].Root],
    to: [objects["a" /* PluginStateObject */].Data.String, objects["a" /* PluginStateObject */].Data.Binary],
    params: {
        data: param_definition["ParamDefinition"].Value('', { isHidden: true }),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(''))
    }
})({
    apply: function (_a) {
        var _this = this;
        var p = _a.params;
        return mol_task["b" /* Task */].create('Raw Data', function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                if (typeof p.data !== 'string' && Object(column_helpers["isTypedArray"])(p.data)) {
                    throw new Error('Supplied binary data must be a plain array.');
                }
                return [2 /*return*/, typeof p.data === 'string'
                        ? new objects["a" /* PluginStateObject */].Data.String(p.data, { label: p.label ? p.label : 'String' })
                        : new objects["a" /* PluginStateObject */].Data.Binary(new Uint8Array(p.data), { label: p.label ? p.label : 'Binary' })];
            });
        }); });
    },
    update: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (oldParams.data !== newParams.data)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.label !== newParams.label) {
            b.label = newParams.label || b.label;
            return mol_state["StateTransformer"].UpdateResult.Updated;
        }
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    }
});
var ReadFile = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'read-file',
    display: { name: 'Read File', description: 'Read string or binary data from the specified file' },
    from: objects["a" /* PluginStateObject */].Root,
    to: [objects["a" /* PluginStateObject */].Data.String, objects["a" /* PluginStateObject */].Data.Binary],
    params: {
        file: param_definition["ParamDefinition"].File(),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('')),
        isBinary: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { description: 'If true, open file as as binary (string otherwise)' }))
    }
})({
    apply: function (_a, plugin) {
        var _this = this;
        var p = _a.params, cache = _a.cache;
        return mol_task["b" /* Task */].create('Open File', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var asset, o;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (p.file === null) {
                            plugin.log.error('No file(s) selected');
                            return [2 /*return*/, mol_state["StateObject"].Null];
                        }
                        return [4 /*yield*/, plugin.managers.asset.resolve(p.file, p.isBinary ? 'binary' : 'string').runInContext(ctx)];
                    case 1:
                        asset = _a.sent();
                        cache.asset = asset;
                        o = p.isBinary
                            ? new objects["a" /* PluginStateObject */].Data.Binary(asset.data, { label: p.label ? p.label : p.file.name })
                            : new objects["a" /* PluginStateObject */].Data.String(asset.data, { label: p.label ? p.label : p.file.name });
                        return [2 /*return*/, o];
                }
            });
        }); });
    },
    dispose: function (_a) {
        var _b, _c;
        var cache = _a.cache;
        (_c = (_b = cache) === null || _b === void 0 ? void 0 : _b.asset) === null || _c === void 0 ? void 0 : _c.dispose();
    },
    update: function (_a) {
        var _b;
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (oldParams.label !== newParams.label) {
            b.label = newParams.label || ((_b = oldParams.file) === null || _b === void 0 ? void 0 : _b.name) || '';
            return mol_state["StateTransformer"].UpdateResult.Updated;
        }
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    },
    isSerializable: function () { return ({ isSerializable: false, reason: 'Cannot serialize user loaded files.' }); }
});
var ParseBlob = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-blob',
    display: { name: 'Parse Blob', description: 'Parse multiple data enties' },
    from: objects["a" /* PluginStateObject */].Data.Blob,
    to: objects["a" /* PluginStateObject */].Format.Blob,
    params: {
        formats: param_definition["ParamDefinition"].ObjectList({
            id: param_definition["ParamDefinition"].Text('', { label: 'Unique ID' }),
            format: param_definition["ParamDefinition"].Select('cif', [['cif', 'cif']])
        }, function (e) { return e.id + ": " + e.format; })
    }
})({
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Parse Blob', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var map, _i, _a, f, entries, _b, _c, e, parsed;
            return Object(tslib_es6["__generator"])(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        map = new Map();
                        for (_i = 0, _a = params.formats; _i < _a.length; _i++) {
                            f = _a[_i];
                            map.set(f.id, f.format);
                        }
                        entries = [];
                        _b = 0, _c = a.data;
                        _d.label = 1;
                    case 1:
                        if (!(_b < _c.length)) return [3 /*break*/, 4];
                        e = _c[_b];
                        if (!map.has(e.id))
                            return [3 /*break*/, 3];
                        return [4 /*yield*/, (e.kind === 'string' ? cif["a" /* CIF */].parse(e.data) : cif["a" /* CIF */].parseBinary(e.data)).runInContext(ctx)];
                    case 2:
                        parsed = _d.sent();
                        if (parsed.isError)
                            throw new Error(e.id + ": " + parsed.message);
                        entries.push({ id: e.id, kind: 'cif', data: parsed.result });
                        _d.label = 3;
                    case 3:
                        _b++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Blob(entries, { label: 'Format Blob', description: entries.length + " " + (entries.length === 1 ? 'entry' : 'entries') })];
                }
            });
        }); });
    },
});
var ParseCif = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-cif',
    display: { name: 'Parse CIF', description: 'Parse CIF from String or Binary data' },
    from: [objects["a" /* PluginStateObject */].Data.String, objects["a" /* PluginStateObject */].Data.Binary],
    to: objects["a" /* PluginStateObject */].Format.Cif
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse CIF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (objects["a" /* PluginStateObject */].Data.String.is(a) ? cif["a" /* CIF */].parse(a.data) : cif["a" /* CIF */].parseBinary(a.data)).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Cif(parsed.result)];
                }
            });
        }); });
    }
});
var ParseCube = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-cube',
    display: { name: 'Parse Cube', description: 'Parse Cube from String data' },
    from: objects["a" /* PluginStateObject */].Data.String,
    to: objects["a" /* PluginStateObject */].Format.Cube
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse Cube', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseCube(a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Cube(parsed.result)];
                }
            });
        }); });
    }
});
var ParsePsf = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-psf',
    display: { name: 'Parse PSF', description: 'Parse PSF from String data' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Format.Psf
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse PSF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parsePsf(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Psf(parsed.result)];
                }
            });
        }); });
    }
});
var ParsePly = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-ply',
    display: { name: 'Parse PLY', description: 'Parse PLY from String data' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Format.Ply
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse PLY', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parser_parse(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Ply(parsed.result, { label: parsed.result.comments[0] || 'PLY Data' })];
                }
            });
        }); });
    }
});
var ParseCcp4 = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-ccp4',
    display: { name: 'Parse CCP4/MRC/MAP', description: 'Parse CCP4/MRC/MAP from Binary data' },
    from: [objects["a" /* PluginStateObject */].Data.Binary],
    to: objects["a" /* PluginStateObject */].Format.Ccp4
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse CCP4/MRC/MAP', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parser["b" /* parse */](a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Ccp4(parsed.result)];
                }
            });
        }); });
    }
});
var ParseDsn6 = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-dsn6',
    display: { name: 'Parse DSN6/BRIX', description: 'Parse CCP4/BRIX from Binary data' },
    from: [objects["a" /* PluginStateObject */].Data.Binary],
    to: objects["a" /* PluginStateObject */].Format.Dsn6
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse DSN6/BRIX', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parse(a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Dsn6(parsed.result)];
                }
            });
        }); });
    }
});
var ParseDx = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-dx',
    display: { name: 'Parse DX', description: 'Parse DX from Binary/String data' },
    from: [objects["a" /* PluginStateObject */].Data.Binary, objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Format.Dx
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse DX', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseDx(a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Dx(parsed.result)];
                }
            });
        }); });
    }
});
var ImportString = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'import-string',
    display: { name: 'Import String', description: 'Import given data as a string' },
    from: objects["a" /* PluginStateObject */].Root,
    to: objects["a" /* PluginStateObject */].Data.String,
    params: {
        data: param_definition["ParamDefinition"].Value(''),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('')),
    }
})({
    apply: function (_a) {
        var _b = _a.params, data = _b.data, label = _b.label;
        return new objects["a" /* PluginStateObject */].Data.String(data, { label: label || '' });
    },
    update: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (oldParams.data !== newParams.data)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.label !== newParams.label) {
            b.label = newParams.label || '';
            return mol_state["StateTransformer"].UpdateResult.Updated;
        }
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    },
    isSerializable: function () { return ({ isSerializable: false, reason: 'Cannot serialize user imported strings.' }); }
});
var ImportJson = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'import-json',
    display: { name: 'Import JSON', description: 'Import given data as a JSON' },
    from: objects["a" /* PluginStateObject */].Root,
    to: objects["a" /* PluginStateObject */].Format.Json,
    params: {
        data: param_definition["ParamDefinition"].Value({}),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('')),
    }
})({
    apply: function (_a) {
        var _b = _a.params, data = _b.data, label = _b.label;
        return new objects["a" /* PluginStateObject */].Format.Json(data, { label: label || '' });
    },
    update: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams, b = _a.b;
        if (oldParams.data !== newParams.data)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (oldParams.label !== newParams.label) {
            b.label = newParams.label || '';
            return mol_state["StateTransformer"].UpdateResult.Updated;
        }
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    },
    isSerializable: function () { return ({ isSerializable: false, reason: 'Cannot serialize user imported JSON.' }); }
});
var ParseJson = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'parse-json',
    display: { name: 'Parse JSON', description: 'Parse JSON from String data' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Format.Json
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse JSON', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var json;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, (new Response(a.data)).json()];
                    case 1:
                        json = _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Format.Json(json)];
                }
            });
        }); });
    }
});
//# sourceMappingURL=data.js.map

/***/ }),
/* 289 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ ExecuteObservable; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ CreateObservableCtx; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ ExecuteInContext; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ ExecuteObservableChild; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/task.js
var mol_task_task = __webpack_require__(256);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/util/scheduler.js
var scheduler = __webpack_require__(339);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/util/user-timing.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var hasPerformance = (typeof performance !== 'undefined') && performance.mark && performance.measure;
var timingEnabled = hasPerformance && !debug["b" /* isProductionMode */];
var UserTiming;
(function (UserTiming) {
    function startMarkName(task) { return "startTask" + task.id; }
    function endMarkName(task) { return "endTask" + task.id; }
    function markStart(task) {
        if (timingEnabled)
            performance.mark(startMarkName(task));
    }
    UserTiming.markStart = markStart;
    function markEnd(task) {
        if (timingEnabled)
            performance.mark(endMarkName(task));
    }
    UserTiming.markEnd = markEnd;
    function measure(task) {
        if (timingEnabled)
            performance.measure("\u2733\uFE0F " + task.name, startMarkName(task), endMarkName(task));
    }
    UserTiming.measure = measure;
})(UserTiming || (UserTiming = {}));
//# sourceMappingURL=user-timing.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-task/execution/observable.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






function ExecuteObservable(task, observer, updateRateMs) {
    if (updateRateMs === void 0) { updateRateMs = 250; }
    var info = ProgressInfo(task, observer, updateRateMs);
    var ctx = new observable_ObservableRuntimeContext(info, info.root);
    return execute(task, ctx);
}
function CreateObservableCtx(task, observer, updateRateMs) {
    if (updateRateMs === void 0) { updateRateMs = 250; }
    var info = ProgressInfo(task, observer, updateRateMs);
    return new observable_ObservableRuntimeContext(info, info.root);
}
function ExecuteInContext(ctx, task) {
    return execute(task, ctx);
}
function ExecuteObservableChild(ctx, task, progress) {
    return ctx.runChild(task, progress);
}
function defaultProgress(task) {
    return {
        taskId: task.id,
        taskName: task.name,
        message: '',
        startedTime: 0,
        canAbort: true,
        isIndeterminate: true,
        current: 0,
        max: 0
    };
}
function ProgressInfo(task, observer, updateRateMs) {
    var abortToken = { abortRequested: false, treeAborted: false, reason: '' };
    return {
        updateRateMs: updateRateMs,
        lastNotified: Object(now["b" /* now */])(),
        observer: observer,
        abortToken: abortToken,
        taskId: task.id,
        root: { progress: defaultProgress(task), children: [] },
        tryAbort: createAbortFunction(abortToken)
    };
}
function createAbortFunction(token) {
    return function (reason) {
        token.abortRequested = true;
        token.reason = reason || token.reason;
    };
}
function cloneTree(root) {
    return { progress: Object(tslib_es6["__assign"])({}, root.progress), children: root.children.map(cloneTree) };
}
function canAbort(root) {
    return root.progress.canAbort && root.children.every(canAbort);
}
function snapshotProgress(info) {
    return { root: cloneTree(info.root), canAbort: canAbort(info.root), requestAbort: info.tryAbort };
}
function execute(task, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var ret, e_1;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    UserTiming.markStart(task);
                    ctx.node.progress.startedTime = Object(now["b" /* now */])();
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 7]);
                    return [4 /*yield*/, task.f(ctx)];
                case 2:
                    ret = _a.sent();
                    UserTiming.markEnd(task);
                    UserTiming.measure(task);
                    if (ctx.info.abortToken.abortRequested) {
                        abort(ctx.info);
                    }
                    return [2 /*return*/, ret];
                case 3:
                    e_1 = _a.sent();
                    if (!mol_task_task["a" /* Task */].isAbort(e_1)) return [3 /*break*/, 6];
                    ctx.isAborted = true;
                    if (!(ctx.node.children.length > 0)) return [3 /*break*/, 5];
                    return [4 /*yield*/, new Promise(function (res) { ctx.onChildrenFinished = res; })];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    if (task.onAbort) {
                        task.onAbort();
                    }
                    _a.label = 6;
                case 6:
                    if (debug["a" /* isDebugMode */])
                        console.error(e_1);
                    throw e_1;
                case 7: return [2 /*return*/];
            }
        });
    });
}
function abort(info) {
    if (!info.abortToken.treeAborted) {
        info.abortToken.treeAborted = true;
        abortTree(info.root);
        notifyObserver(info, Object(now["b" /* now */])());
    }
    throw mol_task_task["a" /* Task */].Aborted(info.abortToken.reason);
}
function abortTree(root) {
    var progress = root.progress;
    progress.isIndeterminate = true;
    progress.canAbort = false;
    progress.message = 'Aborting...';
    for (var _a = 0, _b = root.children; _a < _b.length; _a++) {
        var c = _b[_a];
        abortTree(c);
    }
}
// function shouldNotify(info: ProgressInfo, time: number) {
//     return time - info.lastNotified > info.updateRateMs;
// }
function notifyObserver(info, time) {
    info.lastNotified = time;
    var snapshot = snapshotProgress(info);
    info.observer(snapshot);
}
var observable_ObservableRuntimeContext = /** @class */ (function () {
    function ObservableRuntimeContext(info, node) {
        this.isSynchronous = false;
        this.isExecuting = true;
        this.lastUpdatedTime = 0;
        // used for waiting for cancelled computation trees
        this.onChildrenFinished = void 0;
        this.node = node;
        this.info = info;
    }
    ObservableRuntimeContext.prototype.checkAborted = function () {
        if (this.info.abortToken.abortRequested) {
            this.isAborted = true;
            abort(this.info);
        }
    };
    Object.defineProperty(ObservableRuntimeContext.prototype, "shouldUpdate", {
        get: function () {
            this.checkAborted();
            return Object(now["b" /* now */])() - this.lastUpdatedTime > this.info.updateRateMs;
        },
        enumerable: false,
        configurable: true
    });
    ObservableRuntimeContext.prototype.updateProgress = function (update) {
        this.checkAborted();
        if (!update)
            return;
        var progress = this.node.progress;
        if (typeof update === 'string') {
            progress.message = update;
            progress.isIndeterminate = true;
        }
        else {
            if (typeof update.canAbort !== 'undefined')
                progress.canAbort = update.canAbort;
            if (typeof update.message !== 'undefined')
                progress.message = update.message;
            if (typeof update.current !== 'undefined')
                progress.current = update.current;
            if (typeof update.max !== 'undefined')
                progress.max = update.max;
            progress.isIndeterminate = typeof progress.current === 'undefined' || typeof progress.max === 'undefined';
            if (typeof update.isIndeterminate !== 'undefined')
                progress.isIndeterminate = update.isIndeterminate;
        }
    };
    ObservableRuntimeContext.prototype.update = function (progress, dontNotify) {
        // The progress tracking and observer notification are separated
        // because the computation can have a tree structure.
        // All nodes of the tree should be regualarly updated at the specified frequency,
        // however, the notification should only be invoked once per the whole tree.
        this.lastUpdatedTime = Object(now["b" /* now */])();
        this.updateProgress(progress);
        // TODO: do the shouldNotify check here?
        if (!!dontNotify /* || !shouldNotify(this.info, this.lastUpdatedTime)*/)
            return;
        notifyObserver(this.info, this.lastUpdatedTime);
        // The computation could have been aborted during the notifycation phase.
        this.checkAborted();
        return scheduler["a" /* Scheduler */].immediatePromise();
    };
    ObservableRuntimeContext.prototype.runChild = function (task, progress) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var node, children, ctx, e_2, idx, i, _i;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.updateProgress(progress);
                        node = { progress: defaultProgress(task), children: [] };
                        children = this.node.children;
                        children.push(node);
                        ctx = new ObservableRuntimeContext(this.info, node);
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, 4, 5]);
                        return [4 /*yield*/, execute(task, ctx)];
                    case 2: return [2 /*return*/, _a.sent()];
                    case 3:
                        e_2 = _a.sent();
                        if (mol_task_task["a" /* Task */].isAbort(e_2)) {
                            // need to catch the error here because otherwise
                            // promises for running child tasks in a tree-like computation
                            // will get orphaned and cause "uncaught error in Promise".
                            if (this.isAborted)
                                return [2 /*return*/, void 0];
                        }
                        throw e_2;
                    case 4:
                        idx = children.indexOf(node);
                        if (idx >= 0) {
                            for (i = idx, _i = children.length - 1; i < _i; i++) {
                                children[i] = children[i + 1];
                            }
                            children.pop();
                        }
                        if (children.length === 0 && this.onChildrenFinished)
                            this.onChildrenFinished();
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    return ObservableRuntimeContext;
}());
//# sourceMappingURL=observable.js.map

/***/ }),
/* 290 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var ArrayIteratorImpl = /** @class */ (function () {
    function ArrayIteratorImpl(xs) {
        this.xs = [];
        this.index = -1;
        this.length = 0;
        this.hasNext = false;
        this.length = xs.length;
        this.hasNext = xs.length > 0;
        this.xs = xs;
        this.index = -1;
        // try to avoid deoptimization with undefined values
        this.lastValue = xs.length > 0 ? xs[0] : void 0;
    }
    ArrayIteratorImpl.prototype.move = function () {
        ++this.index;
        this.lastValue = this.xs[this.index];
        this.hasNext = this.index < this.length - 1;
        return this.lastValue;
    };
    return ArrayIteratorImpl;
}());
var RangeIteratorImpl = /** @class */ (function () {
    function RangeIteratorImpl(min, max) {
        this.max = max;
        this.value = 0;
        this.hasNext = false;
        this.value = min - 1;
        this.hasNext = max >= min;
    }
    RangeIteratorImpl.prototype.move = function () {
        ++this.value;
        this.hasNext = this.value < this.max;
        return this.value;
    };
    return RangeIteratorImpl;
}());
var ValueIterator = /** @class */ (function () {
    function ValueIterator(value) {
        this.value = value;
        this.hasNext = true;
    }
    ValueIterator.prototype.move = function () { this.hasNext = false; return this.value; };
    return ValueIterator;
}());
var MapIteratorImpl = /** @class */ (function () {
    function MapIteratorImpl(base, f) {
        this.base = base;
        this.f = f;
        this.hasNext = false;
        this.hasNext = base.hasNext;
    }
    MapIteratorImpl.prototype.move = function () {
        var v = this.f(this.base.move());
        this.hasNext = this.base.hasNext;
        return v;
    };
    return MapIteratorImpl;
}());
var FilterIteratorImpl = /** @class */ (function () {
    function FilterIteratorImpl(base, p) {
        this.base = base;
        this.p = p;
        this.hasNext = this.findNext();
    }
    FilterIteratorImpl.prototype.move = function () {
        var ret = this.next;
        this.hasNext = this.findNext();
        return ret;
    };
    FilterIteratorImpl.prototype.findNext = function () {
        while (this.base.hasNext) {
            this.next = this.base.move();
            if (this.p(this.next))
                return true;
        }
        return false;
    };
    return FilterIteratorImpl;
}());
var Iterator;
(function (Iterator) {
    Iterator.Empty = new RangeIteratorImpl(0, -1);
    function Array(xs) { return new ArrayIteratorImpl(xs); }
    Iterator.Array = Array;
    function Value(value) { return new ValueIterator(value); }
    Iterator.Value = Value;
    function Range(min, max) { return new RangeIteratorImpl(min, max); }
    Iterator.Range = Range;
    function map(base, f) { return new MapIteratorImpl(base, f); }
    Iterator.map = map;
    function filter(base, p) { return new FilterIteratorImpl(base, p); }
    Iterator.filter = filter;
    // Iterate until first truthy value is returned.
    function forEach(it, f, ctx) {
        while (it.hasNext) {
            var c = f(it.move(), ctx);
            if (c)
                return ctx;
        }
        return ctx;
    }
    Iterator.forEach = forEach;
})(Iterator || (Iterator = {}));
/* harmony default export */ __webpack_exports__["a"] = (Iterator);
//# sourceMappingURL=iterator.js.map

/***/ }),
/* 291 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Assembly; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Symmetry; });
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(9);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(11);
/* harmony import */ var _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(113);
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(46);
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var Assembly = /** @class */ (function () {
    function Assembly(id, details, operatorsProvider) {
        this.operatorsProvider = operatorsProvider;
        this.id = id;
        this.details = details;
    }
    Object.defineProperty(Assembly.prototype, "operatorGroups", {
        get: function () {
            if (this._operators)
                return this._operators;
            this._operators = this.operatorsProvider();
            return this._operators;
        },
        enumerable: false,
        configurable: true
    });
    return Assembly;
}());

(function (Assembly) {
    function create(id, details, operatorsProvider) {
        return new Assembly(id, details, operatorsProvider);
    }
    Assembly.create = create;
})(Assembly || (Assembly = {}));
var Symmetry;
(function (Symmetry) {
    Symmetry.Default = { assemblies: [], spacegroup: _mol_math_geometry__WEBPACK_IMPORTED_MODULE_1__[/* Spacegroup */ "e"].ZeroP1, isNonStandardCrystalFrame: false };
    function findAssembly(model, id) {
        var _id = id.toLocaleLowerCase();
        var symmetry = _mol_model_formats_structure_property_symmetry__WEBPACK_IMPORTED_MODULE_2__[/* ModelSymmetry */ "a"].Provider.get(model);
        return symmetry ? Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_0__[/* arrayFind */ "c"])(symmetry.assemblies, function (a) { return a.id.toLowerCase() === _id; }) : undefined;
    }
    Symmetry.findAssembly = findAssembly;
    function getUnitcellLabel(symmetry) {
        var _a = symmetry.spacegroup, cell = _a.cell, name = _a.name, num = _a.num;
        var size = cell.size, anglesInRadians = cell.anglesInRadians;
        var a = size[0].toFixed(2);
        var b = size[1].toFixed(2);
        var c = size[2].toFixed(2);
        var alpha = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_3__[/* radToDeg */ "f"])(anglesInRadians[0]).toFixed(2);
        var beta = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_3__[/* radToDeg */ "f"])(anglesInRadians[1]).toFixed(2);
        var gamma = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_3__[/* radToDeg */ "f"])(anglesInRadians[2]).toFixed(2);
        var label = [];
        // name
        label.push("Unit Cell <b>" + name + "</b> #" + num);
        // sizes
        label.push(a + "\u00D7" + b + "\u00D7" + c + " \u212B");
        // angles
        label.push("\u03B1=" + alpha + "\u00B0 \u03B2=" + beta + "\u00B0 \u03B3=" + gamma + "\u00B0");
        return label.join(' | ');
    }
    Symmetry.getUnitcellLabel = getUnitcellLabel;
})(Symmetry || (Symmetry = {}));

//# sourceMappingURL=symmetry.js.map

/***/ }),
/* 292 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mergeAll; });
/* harmony import */ var _mergeMap__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(213);
/* harmony import */ var _util_identity__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(181);
/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */


function mergeAll(concurrent) {
    if (concurrent === void 0) {
        concurrent = Number.POSITIVE_INFINITY;
    }
    return Object(_mergeMap__WEBPACK_IMPORTED_MODULE_0__[/* mergeMap */ "a"])(_util_identity__WEBPACK_IMPORTED_MODULE_1__[/* identity */ "a"], concurrent);
}
//# sourceMappingURL=mergeAll.js.map


/***/ }),
/* 293 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return take; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/* harmony import */ var _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(214);
/* harmony import */ var _observable_empty__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(133);
/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */




function take(count) {
    return function (source) {
        if (count === 0) {
            return Object(_observable_empty__WEBPACK_IMPORTED_MODULE_3__[/* empty */ "b"])();
        }
        else {
            return source.lift(new TakeOperator(count));
        }
    };
}
var TakeOperator = /*@__PURE__*/ (function () {
    function TakeOperator(total) {
        this.total = total;
        if (this.total < 0) {
            throw new _util_ArgumentOutOfRangeError__WEBPACK_IMPORTED_MODULE_2__[/* ArgumentOutOfRangeError */ "a"];
        }
    }
    TakeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new TakeSubscriber(subscriber, this.total));
    };
    return TakeOperator;
}());
var TakeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](TakeSubscriber, _super);
    function TakeSubscriber(destination, total) {
        var _this = _super.call(this, destination) || this;
        _this.total = total;
        _this.count = 0;
        return _this;
    }
    TakeSubscriber.prototype._next = function (value) {
        var total = this.total;
        var count = ++this.count;
        if (count <= total) {
            this.destination.next(value);
            if (count === total) {
                this.destination.complete();
                this.unsubscribe();
            }
        }
    };
    return TakeSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
//# sourceMappingURL=take.js.map


/***/ }),
/* 294 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return combineLatest; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CombineLatestOperator; });
/* unused harmony export CombineLatestSubscriber */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(122);
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(100);
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(52);
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(50);
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(224);
/** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */






var NONE = {};
function combineLatest() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    var resultSelector = null;
    var scheduler = null;
    if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_1__[/* isScheduler */ "a"])(observables[observables.length - 1])) {
        scheduler = observables.pop();
    }
    if (typeof observables[observables.length - 1] === 'function') {
        resultSelector = observables.pop();
    }
    if (observables.length === 1 && Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__[/* isArray */ "a"])(observables[0])) {
        observables = observables[0];
    }
    return Object(_fromArray__WEBPACK_IMPORTED_MODULE_5__[/* fromArray */ "a"])(observables, scheduler).lift(new CombineLatestOperator(resultSelector));
}
var CombineLatestOperator = /*@__PURE__*/ (function () {
    function CombineLatestOperator(resultSelector) {
        this.resultSelector = resultSelector;
    }
    CombineLatestOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector));
    };
    return CombineLatestOperator;
}());

var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](CombineLatestSubscriber, _super);
    function CombineLatestSubscriber(destination, resultSelector) {
        var _this = _super.call(this, destination) || this;
        _this.resultSelector = resultSelector;
        _this.active = 0;
        _this.values = [];
        _this.observables = [];
        return _this;
    }
    CombineLatestSubscriber.prototype._next = function (observable) {
        this.values.push(NONE);
        this.observables.push(observable);
    };
    CombineLatestSubscriber.prototype._complete = function () {
        var observables = this.observables;
        var len = observables.length;
        if (len === 0) {
            this.destination.complete();
        }
        else {
            this.active = len;
            this.toRespond = len;
            for (var i = 0; i < len; i++) {
                var observable = observables[i];
                this.add(Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__[/* subscribeToResult */ "a"])(this, observable, observable, i));
            }
        }
    };
    CombineLatestSubscriber.prototype.notifyComplete = function (unused) {
        if ((this.active -= 1) === 0) {
            this.destination.complete();
        }
    };
    CombineLatestSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        var values = this.values;
        var oldVal = values[outerIndex];
        var toRespond = !this.toRespond
            ? 0
            : oldVal === NONE ? --this.toRespond : this.toRespond;
        values[outerIndex] = innerValue;
        if (toRespond === 0) {
            if (this.resultSelector) {
                this._tryResultSelector(values);
            }
            else {
                this.destination.next(values.slice());
            }
        }
    };
    CombineLatestSubscriber.prototype._tryResultSelector = function (values) {
        var result;
        try {
            result = this.resultSelector.apply(this, values);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(result);
    };
    return CombineLatestSubscriber;
}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__[/* OuterSubscriber */ "a"]));

//# sourceMappingURL=combineLatest.js.map


/***/ }),
/* 295 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return throwError; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */

function throwError(error, scheduler) {
    if (!scheduler) {
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) { return subscriber.error(error); });
    }
    else {
        return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); });
    }
}
function dispatch(_a) {
    var error = _a.error, subscriber = _a.subscriber;
    subscriber.error(error);
}
//# sourceMappingURL=throwError.js.map


/***/ }),
/* 296 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return refCount; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */


function refCount() {
    return function refCountOperatorFunction(source) {
        return source.lift(new RefCountOperator(source));
    };
}
var RefCountOperator = /*@__PURE__*/ (function () {
    function RefCountOperator(connectable) {
        this.connectable = connectable;
    }
    RefCountOperator.prototype.call = function (subscriber, source) {
        var connectable = this.connectable;
        connectable._refCount++;
        var refCounter = new RefCountSubscriber(subscriber, connectable);
        var subscription = source.subscribe(refCounter);
        if (!refCounter.closed) {
            refCounter.connection = connectable.connect();
        }
        return subscription;
    };
    return RefCountOperator;
}());
var RefCountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](RefCountSubscriber, _super);
    function RefCountSubscriber(destination, connectable) {
        var _this = _super.call(this, destination) || this;
        _this.connectable = connectable;
        return _this;
    }
    RefCountSubscriber.prototype._unsubscribe = function () {
        var connectable = this.connectable;
        if (!connectable) {
            this.connection = null;
            return;
        }
        this.connectable = null;
        var refCount = connectable._refCount;
        if (refCount <= 0) {
            this.connection = null;
            return;
        }
        connectable._refCount = refCount - 1;
        if (refCount > 1) {
            this.connection = null;
            return;
        }
        var connection = this.connection;
        var sharedConnection = connectable._connection;
        this.connection = null;
        if (sharedConnection && (!connection || sharedConnection === connection)) {
            sharedConnection.unsubscribe();
        }
    };
    return RefCountSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
//# sourceMappingURL=refCount.js.map


/***/ }),
/* 297 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ReplaySubject; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(60);
/* harmony import */ var _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(351);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(70);
/* harmony import */ var _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(347);
/* harmony import */ var _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(208);
/* harmony import */ var _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(353);
/** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */







var ReplaySubject = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ReplaySubject, _super);
    function ReplaySubject(bufferSize, windowTime, scheduler) {
        if (bufferSize === void 0) {
            bufferSize = Number.POSITIVE_INFINITY;
        }
        if (windowTime === void 0) {
            windowTime = Number.POSITIVE_INFINITY;
        }
        var _this = _super.call(this) || this;
        _this.scheduler = scheduler;
        _this._events = [];
        _this._infiniteTimeWindow = false;
        _this._bufferSize = bufferSize < 1 ? 1 : bufferSize;
        _this._windowTime = windowTime < 1 ? 1 : windowTime;
        if (windowTime === Number.POSITIVE_INFINITY) {
            _this._infiniteTimeWindow = true;
            _this.next = _this.nextInfiniteTimeWindow;
        }
        else {
            _this.next = _this.nextTimeWindow;
        }
        return _this;
    }
    ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) {
        var _events = this._events;
        _events.push(value);
        if (_events.length > this._bufferSize) {
            _events.shift();
        }
        _super.prototype.next.call(this, value);
    };
    ReplaySubject.prototype.nextTimeWindow = function (value) {
        this._events.push(new ReplayEvent(this._getNow(), value));
        this._trimBufferThenGetEvents();
        _super.prototype.next.call(this, value);
    };
    ReplaySubject.prototype._subscribe = function (subscriber) {
        var _infiniteTimeWindow = this._infiniteTimeWindow;
        var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents();
        var scheduler = this.scheduler;
        var len = _events.length;
        var subscription;
        if (this.closed) {
            throw new _util_ObjectUnsubscribedError__WEBPACK_IMPORTED_MODULE_5__[/* ObjectUnsubscribedError */ "a"]();
        }
        else if (this.isStopped || this.hasError) {
            subscription = _Subscription__WEBPACK_IMPORTED_MODULE_3__[/* Subscription */ "a"].EMPTY;
        }
        else {
            this.observers.push(subscriber);
            subscription = new _SubjectSubscription__WEBPACK_IMPORTED_MODULE_6__[/* SubjectSubscription */ "a"](this, subscriber);
        }
        if (scheduler) {
            subscriber.add(subscriber = new _operators_observeOn__WEBPACK_IMPORTED_MODULE_4__[/* ObserveOnSubscriber */ "a"](subscriber, scheduler));
        }
        if (_infiniteTimeWindow) {
            for (var i = 0; i < len && !subscriber.closed; i++) {
                subscriber.next(_events[i]);
            }
        }
        else {
            for (var i = 0; i < len && !subscriber.closed; i++) {
                subscriber.next(_events[i].value);
            }
        }
        if (this.hasError) {
            subscriber.error(this.thrownError);
        }
        else if (this.isStopped) {
            subscriber.complete();
        }
        return subscription;
    };
    ReplaySubject.prototype._getNow = function () {
        return (this.scheduler || _scheduler_queue__WEBPACK_IMPORTED_MODULE_2__[/* queue */ "a"]).now();
    };
    ReplaySubject.prototype._trimBufferThenGetEvents = function () {
        var now = this._getNow();
        var _bufferSize = this._bufferSize;
        var _windowTime = this._windowTime;
        var _events = this._events;
        var eventsCount = _events.length;
        var spliceCount = 0;
        while (spliceCount < eventsCount) {
            if ((now - _events[spliceCount].time) < _windowTime) {
                break;
            }
            spliceCount++;
        }
        if (eventsCount > _bufferSize) {
            spliceCount = Math.max(spliceCount, eventsCount - _bufferSize);
        }
        if (spliceCount > 0) {
            _events.splice(0, spliceCount);
        }
        return _events;
    };
    return ReplaySubject;
}(_Subject__WEBPACK_IMPORTED_MODULE_1__[/* Subject */ "a"]));

var ReplayEvent = /*@__PURE__*/ (function () {
    function ReplayEvent(time, value) {
        this.time = time;
        this.value = value;
    }
    return ReplayEvent;
}());
//# sourceMappingURL=ReplaySubject.js.map


/***/ }),
/* 298 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return defer; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _from__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(140);
/* harmony import */ var _empty__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(133);
/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */



function defer(observableFactory) {
    return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) {
        var input;
        try {
            input = observableFactory();
        }
        catch (err) {
            subscriber.error(err);
            return undefined;
        }
        var source = input ? Object(_from__WEBPACK_IMPORTED_MODULE_1__[/* from */ "a"])(input) : Object(_empty__WEBPACK_IMPORTED_MODULE_2__[/* empty */ "b"])();
        return source.subscribe(subscriber);
    });
}
//# sourceMappingURL=defer.js.map


/***/ }),
/* 299 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return zip; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ZipOperator; });
/* unused harmony export ZipSubscriber */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(224);
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(100);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35);
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(52);
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(50);
/* harmony import */ var _internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(197);
/** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_OuterSubscriber,_util_subscribeToResult,_.._internal_symbol_iterator PURE_IMPORTS_END */







function zip() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    var resultSelector = observables[observables.length - 1];
    if (typeof resultSelector === 'function') {
        observables.pop();
    }
    return Object(_fromArray__WEBPACK_IMPORTED_MODULE_1__[/* fromArray */ "a"])(observables, undefined).lift(new ZipOperator(resultSelector));
}
var ZipOperator = /*@__PURE__*/ (function () {
    function ZipOperator(resultSelector) {
        this.resultSelector = resultSelector;
    }
    ZipOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector));
    };
    return ZipOperator;
}());

var ZipSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ZipSubscriber, _super);
    function ZipSubscriber(destination, resultSelector, values) {
        if (values === void 0) {
            values = Object.create(null);
        }
        var _this = _super.call(this, destination) || this;
        _this.iterators = [];
        _this.active = 0;
        _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : null;
        _this.values = values;
        return _this;
    }
    ZipSubscriber.prototype._next = function (value) {
        var iterators = this.iterators;
        if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_2__[/* isArray */ "a"])(value)) {
            iterators.push(new StaticArrayIterator(value));
        }
        else if (typeof value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__[/* iterator */ "a"]] === 'function') {
            iterators.push(new StaticIterator(value[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__[/* iterator */ "a"]]()));
        }
        else {
            iterators.push(new ZipBufferIterator(this.destination, this, value));
        }
    };
    ZipSubscriber.prototype._complete = function () {
        var iterators = this.iterators;
        var len = iterators.length;
        this.unsubscribe();
        if (len === 0) {
            this.destination.complete();
            return;
        }
        this.active = len;
        for (var i = 0; i < len; i++) {
            var iterator = iterators[i];
            if (iterator.stillUnsubscribed) {
                var destination = this.destination;
                destination.add(iterator.subscribe(iterator, i));
            }
            else {
                this.active--;
            }
        }
    };
    ZipSubscriber.prototype.notifyInactive = function () {
        this.active--;
        if (this.active === 0) {
            this.destination.complete();
        }
    };
    ZipSubscriber.prototype.checkIterators = function () {
        var iterators = this.iterators;
        var len = iterators.length;
        var destination = this.destination;
        for (var i = 0; i < len; i++) {
            var iterator = iterators[i];
            if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) {
                return;
            }
        }
        var shouldComplete = false;
        var args = [];
        for (var i = 0; i < len; i++) {
            var iterator = iterators[i];
            var result = iterator.next();
            if (iterator.hasCompleted()) {
                shouldComplete = true;
            }
            if (result.done) {
                destination.complete();
                return;
            }
            args.push(result.value);
        }
        if (this.resultSelector) {
            this._tryresultSelector(args);
        }
        else {
            destination.next(args);
        }
        if (shouldComplete) {
            destination.complete();
        }
    };
    ZipSubscriber.prototype._tryresultSelector = function (args) {
        var result;
        try {
            result = this.resultSelector.apply(this, args);
        }
        catch (err) {
            this.destination.error(err);
            return;
        }
        this.destination.next(result);
    };
    return ZipSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__[/* Subscriber */ "a"]));

var StaticIterator = /*@__PURE__*/ (function () {
    function StaticIterator(iterator) {
        this.iterator = iterator;
        this.nextResult = iterator.next();
    }
    StaticIterator.prototype.hasValue = function () {
        return true;
    };
    StaticIterator.prototype.next = function () {
        var result = this.nextResult;
        this.nextResult = this.iterator.next();
        return result;
    };
    StaticIterator.prototype.hasCompleted = function () {
        var nextResult = this.nextResult;
        return nextResult && nextResult.done;
    };
    return StaticIterator;
}());
var StaticArrayIterator = /*@__PURE__*/ (function () {
    function StaticArrayIterator(array) {
        this.array = array;
        this.index = 0;
        this.length = 0;
        this.length = array.length;
    }
    StaticArrayIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__[/* iterator */ "a"]] = function () {
        return this;
    };
    StaticArrayIterator.prototype.next = function (value) {
        var i = this.index++;
        var array = this.array;
        return i < this.length ? { value: array[i], done: false } : { value: null, done: true };
    };
    StaticArrayIterator.prototype.hasValue = function () {
        return this.array.length > this.index;
    };
    StaticArrayIterator.prototype.hasCompleted = function () {
        return this.array.length === this.index;
    };
    return StaticArrayIterator;
}());
var ZipBufferIterator = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ZipBufferIterator, _super);
    function ZipBufferIterator(destination, parent, observable) {
        var _this = _super.call(this, destination) || this;
        _this.parent = parent;
        _this.observable = observable;
        _this.stillUnsubscribed = true;
        _this.buffer = [];
        _this.isComplete = false;
        return _this;
    }
    ZipBufferIterator.prototype[_internal_symbol_iterator__WEBPACK_IMPORTED_MODULE_6__[/* iterator */ "a"]] = function () {
        return this;
    };
    ZipBufferIterator.prototype.next = function () {
        var buffer = this.buffer;
        if (buffer.length === 0 && this.isComplete) {
            return { value: null, done: true };
        }
        else {
            return { value: buffer.shift(), done: false };
        }
    };
    ZipBufferIterator.prototype.hasValue = function () {
        return this.buffer.length > 0;
    };
    ZipBufferIterator.prototype.hasCompleted = function () {
        return this.buffer.length === 0 && this.isComplete;
    };
    ZipBufferIterator.prototype.notifyComplete = function () {
        if (this.buffer.length > 0) {
            this.isComplete = true;
            this.parent.notifyInactive();
        }
        else {
            this.destination.complete();
        }
    };
    ZipBufferIterator.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        this.buffer.push(innerValue);
        this.parent.checkIterators();
    };
    ZipBufferIterator.prototype.subscribe = function (value, index) {
        return Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_5__[/* subscribeToResult */ "a"])(this, this.observable, this, index);
    };
    return ZipBufferIterator;
}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_4__[/* OuterSubscriber */ "a"]));
//# sourceMappingURL=zip.js.map


/***/ }),
/* 300 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "InitVolumeStreaming", function() { return /* binding */ InitVolumeStreaming; });
__webpack_require__.d(__webpack_exports__, "BoxifyVolumeStreaming", function() { return /* binding */ BoxifyVolumeStreaming; });
__webpack_require__.d(__webpack_exports__, "CreateVolumeStreamingInfo", function() { return /* binding */ CreateVolumeStreamingInfo; });
__webpack_require__.d(__webpack_exports__, "CreateVolumeStreamingBehavior", function() { return /* binding */ CreateVolumeStreamingBehavior; });
__webpack_require__.d(__webpack_exports__, "VolumeStreamingVisual", function() { return /* binding */ VolumeStreamingVisual; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/model.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var model_VolumeServerInfo = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(VolumeServerInfo, _super);
    function VolumeServerInfo() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return VolumeServerInfo;
}(objects["a" /* PluginStateObject */].Create({ name: 'Volume Streaming', typeClass: 'Object' })));

var VolumeServerHeader;
(function (VolumeServerHeader) {
    var ValueType;
    (function (ValueType) {
        ValueType.Float32 = 'float32';
        ValueType.Int8 = 'int8';
    })(ValueType = VolumeServerHeader.ValueType || (VolumeServerHeader.ValueType = {}));
})(VolumeServerHeader || (VolumeServerHeader = {}));
//# sourceMappingURL=model.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/url.js
var url = __webpack_require__(262);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/isosurface.js
var isosurface = __webpack_require__(241);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/volume.js
var volume = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/config.js
var config = __webpack_require__(101);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/util.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getStreamingMethod(s, defaultKind) {
    if (defaultKind === void 0) { defaultKind = 'x-ray'; }
    if (!s)
        return defaultKind;
    var model = s.models[0];
    if (!mmcif["MmcifFormat"].is(model.sourceData))
        return defaultKind;
    // Prefer EMDB entries over structure-factors (SF) e.g. for 'ELECTRON CRYSTALLOGRAPHY' entries
    // like 6AXZ or 6KJ3 for which EMDB entries are available but map calculation from SF is hard.
    if (structure["Model"].hasEmMap(model))
        return 'em';
    if (structure["Model"].hasXrayMap(model))
        return 'x-ray';
    // Fallbacks based on experimental method
    if (structure["Model"].isFromEm(model))
        return 'em';
    if (structure["Model"].isFromXray(model))
        return 'x-ray';
    return defaultKind;
}
/** Returns EMD ID when available, otherwise falls back to PDB ID */
function getEmIds(model) {
    var ids = [];
    if (!mmcif["MmcifFormat"].is(model.sourceData))
        return [model.entryId];
    var _a = model.sourceData.data.db.pdbx_database_related, db_id = _a.db_id, db_name = _a.db_name, content_type = _a.content_type;
    if (!db_name.isDefined)
        return [model.entryId];
    for (var i = 0, il = db_name.rowCount; i < il; ++i) {
        if (db_name.value(i).toUpperCase() === 'EMDB' && content_type.value(i) === 'associated EM volume') {
            ids.push(db_id.value(i));
        }
    }
    return ids;
}
function getXrayIds(model) {
    return [model.entryId];
}
function getIds(method, s) {
    if (!s || !s.models.length)
        return [];
    var model = s.models[0];
    switch (method) {
        case 'em': return getEmIds(model);
        case 'x-ray': return getXrayIds(model);
    }
}
function getContourLevel(provider, plugin, taskCtx, emdbId) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (provider) {
                case 'emdb': return [2 /*return*/, getContourLevelEmdb(plugin, taskCtx, emdbId)];
                case 'pdbe': return [2 /*return*/, getContourLevelPdbe(plugin, taskCtx, emdbId)];
            }
            return [2 /*return*/];
        });
    });
}
function getContourLevelEmdb(plugin, taskCtx, emdbId) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var emdbHeaderServer, header, map, contourLevel;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    emdbHeaderServer = plugin.config.get(config["PluginConfig"].VolumeStreaming.EmdbHeaderServer);
                    return [4 /*yield*/, plugin.fetch({ url: emdbHeaderServer + "/" + emdbId.toUpperCase() + "/header/" + emdbId.toLowerCase() + ".xml", type: 'xml' }).runInContext(taskCtx)];
                case 1:
                    header = _a.sent();
                    map = header.getElementsByTagName('map')[0];
                    contourLevel = parseFloat(map.getElementsByTagName('contourLevel')[0].textContent);
                    return [2 /*return*/, contourLevel];
            }
        });
    });
}
function getContourLevelPdbe(plugin, taskCtx, emdbId) {
    var _a, _b, _c;
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var header, emdbEntry, contourLevel;
        return Object(tslib_es6["__generator"])(this, function (_d) {
            switch (_d.label) {
                case 0:
                    emdbId = emdbId.toUpperCase();
                    return [4 /*yield*/, plugin.fetch({ url: "https://www.ebi.ac.uk/pdbe/api/emdb/entry/map/" + emdbId, type: 'json' }).runInContext(taskCtx)];
                case 1:
                    header = _d.sent();
                    emdbEntry = header === null || header === void 0 ? void 0 : header[emdbId];
                    contourLevel = void 0;
                    if (((_c = (_b = (_a = emdbEntry === null || emdbEntry === void 0 ? void 0 : emdbEntry[0]) === null || _a === void 0 ? void 0 : _a.map) === null || _b === void 0 ? void 0 : _b.contour_level) === null || _c === void 0 ? void 0 : _c.value) !== void 0) {
                        contourLevel = +emdbEntry[0].map.contour_level.value;
                    }
                    return [2 /*return*/, contourLevel];
            }
        });
    });
}
function getEmdbIds(plugin, taskCtx, pdbId) {
    var _a;
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var summary, summaryEntry, emdbIds, emdb;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, plugin.fetch({ url: "https://www.ebi.ac.uk/pdbe/api/pdb/entry/summary/" + pdbId, type: 'json' }).runInContext(taskCtx)];
                case 1:
                    summary = _b.sent();
                    summaryEntry = summary === null || summary === void 0 ? void 0 : summary[pdbId];
                    emdbIds = [];
                    if ((_a = summaryEntry === null || summaryEntry === void 0 ? void 0 : summaryEntry[0]) === null || _a === void 0 ? void 0 : _a.related_structures) {
                        emdb = summaryEntry[0].related_structures.filter(function (s) { return s.resource === 'EMDB' && s.relationship === 'associated EM volume'; });
                        if (!emdb.length) {
                            throw new Error("No related EMDB entry found for '" + pdbId + "'.");
                        }
                        emdbIds.push.apply(emdbIds, emdb.map(function (e) { return e.accession; }));
                    }
                    else {
                        throw new Error("No related EMDB entry found for '" + pdbId + "'.");
                    }
                    return [2 /*return*/, emdbIds];
            }
        });
    });
}
//# sourceMappingURL=util.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/behavior.js + 1 modules
var volume_streaming_behavior = __webpack_require__(160);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/representation.js + 13 modules
var representation = __webpack_require__(198);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/registry.js + 1 modules
var registry = __webpack_require__(379);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/theme.js
var theme = __webpack_require__(89);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/volume-streaming/transformers.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















function addEntry(entries, method, dataId, emDefaultContourLevel) {
    entries.push({
        source: method === 'em'
            ? { name: 'em', params: { isoValue: volume["b" /* Volume */].IsoValue.absolute(emDefaultContourLevel || 0) } }
            : { name: 'x-ray', params: {} },
        dataId: dataId
    });
}
var InitVolumeStreaming = mol_state["StateAction"].build({
    display: { name: 'Volume Streaming' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: function (a, plugin) {
        var method = getStreamingMethod(a && a.data);
        var ids = getIds(method, a && a.data);
        return {
            method: param_definition["ParamDefinition"].Select(method, [['em', 'EM'], ['x-ray', 'X-Ray']]),
            entries: param_definition["ParamDefinition"].ObjectList({ id: param_definition["ParamDefinition"].Text(ids[0] || '') }, function (_a) {
                var id = _a.id;
                return id;
            }, { defaultValue: ids.map(function (id) { return ({ id: id }); }) }),
            defaultView: param_definition["ParamDefinition"].Select(method === 'em' ? 'cell' : 'selection-box', volume_streaming_behavior["a" /* VolumeStreaming */].ViewTypeOptions),
            options: param_definition["ParamDefinition"].Group({
                serverUrl: param_definition["ParamDefinition"].Text(plugin.config.get(config["PluginConfig"].VolumeStreaming.DefaultServer) || 'https://ds.litemol.org'),
                behaviorRef: param_definition["ParamDefinition"].Text('', { isHidden: true }),
                emContourProvider: param_definition["ParamDefinition"].Select('emdb', [['emdb', 'EMDB'], ['pdbe', 'PDBe']], { isHidden: true }),
                channelParams: param_definition["ParamDefinition"].Value({}, { isHidden: true })
            })
        };
    },
    isApplicable: function (a, _, plugin) {
        var canStreamTest = plugin.config.get(config["PluginConfig"].VolumeStreaming.CanStream);
        if (canStreamTest)
            return canStreamTest(a.data, plugin);
        return a.data.models.length === 1 && structure["Model"].probablyHasDensityMap(a.data.models[0]);
    }
})(function (_a, plugin) {
    var ref = _a.ref, state = _a.state, params = _a.params;
    return mol_task["b" /* Task */].create('Volume Streaming', function (taskCtx) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var entries, i, il, dataId, emDefaultContourLevel, emdbIds, j, jl, emdbId, contourLevel, e_1, e_2, infoTree, info, children, infoObj, behTree;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    entries = [];
                    i = 0, il = params.entries.length;
                    _a.label = 1;
                case 1:
                    if (!(i < il)) return [3 /*break*/, 16];
                    dataId = params.entries[i].id.toLowerCase();
                    emDefaultContourLevel = void 0;
                    if (!(params.method === 'em')) return [3 /*break*/, 14];
                    if (!!dataId.toUpperCase().startsWith('EMD')) return [3 /*break*/, 11];
                    return [4 /*yield*/, taskCtx.update('Getting EMDB info...')];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, getEmdbIds(plugin, taskCtx, dataId)];
                case 3:
                    emdbIds = _a.sent();
                    j = 0, jl = emdbIds.length;
                    _a.label = 4;
                case 4:
                    if (!(j < jl)) return [3 /*break*/, 10];
                    emdbId = emdbIds[j];
                    contourLevel = void 0;
                    _a.label = 5;
                case 5:
                    _a.trys.push([5, 7, , 8]);
                    return [4 /*yield*/, getContourLevel(params.options.emContourProvider, plugin, taskCtx, emdbId)];
                case 6:
                    contourLevel = _a.sent();
                    return [3 /*break*/, 8];
                case 7:
                    e_1 = _a.sent();
                    console.info("Could not get map info for " + emdbId + ": " + e_1);
                    return [3 /*break*/, 9];
                case 8:
                    addEntry(entries, params.method, emdbId, contourLevel || 0);
                    _a.label = 9;
                case 9:
                    ++j;
                    return [3 /*break*/, 4];
                case 10: return [3 /*break*/, 15];
                case 11:
                    _a.trys.push([11, 13, , 14]);
                    return [4 /*yield*/, getContourLevel(params.options.emContourProvider, plugin, taskCtx, dataId)];
                case 12:
                    emDefaultContourLevel = _a.sent();
                    return [3 /*break*/, 14];
                case 13:
                    e_2 = _a.sent();
                    console.info("Could not get map info for " + dataId + ": " + e_2);
                    return [3 /*break*/, 15];
                case 14:
                    addEntry(entries, params.method, dataId, emDefaultContourLevel || 0);
                    _a.label = 15;
                case 15:
                    ++i;
                    return [3 /*break*/, 1];
                case 16:
                    infoTree = state.build().to(ref)
                        .applyOrUpdateTagged(volume_streaming_behavior["a" /* VolumeStreaming */].RootTag, CreateVolumeStreamingInfo, {
                        serverUrl: params.options.serverUrl,
                        entries: entries
                    });
                    return [4 /*yield*/, infoTree.commit()];
                case 17:
                    _a.sent();
                    info = infoTree.selector;
                    if (!info.isOk)
                        return [2 /*return*/];
                    children = state.tree.children.get(info.ref);
                    if (!((children === null || children === void 0 ? void 0 : children.size) > 0)) return [3 /*break*/, 19];
                    return [4 /*yield*/, plugin.managers.structure.hierarchy.remove(children === null || children === void 0 ? void 0 : children.toArray())];
                case 18:
                    _a.sent();
                    _a.label = 19;
                case 19:
                    infoObj = info.cell.obj;
                    behTree = state.build().to(infoTree.ref).apply(CreateVolumeStreamingBehavior, param_definition["ParamDefinition"].getDefaultValues(volume_streaming_behavior["a" /* VolumeStreaming */].createParams({ data: infoObj.data, defaultView: params.defaultView, channelParams: params.options.channelParams })), { ref: params.options.behaviorRef ? params.options.behaviorRef : void 0 });
                    if (params.method === 'em') {
                        behTree.apply(VolumeStreamingVisual, { channel: 'em' }, { state: { isGhost: true }, tags: 'em' });
                    }
                    else {
                        behTree.apply(VolumeStreamingVisual, { channel: '2fo-fc' }, { state: { isGhost: true }, tags: '2fo-fc' });
                        behTree.apply(VolumeStreamingVisual, { channel: 'fo-fc(+ve)' }, { state: { isGhost: true }, tags: 'fo-fc(+ve)' });
                        behTree.apply(VolumeStreamingVisual, { channel: 'fo-fc(-ve)' }, { state: { isGhost: true }, tags: 'fo-fc(-ve)' });
                    }
                    return [4 /*yield*/, state.updateTree(behTree).runInContext(taskCtx)];
                case 20:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    }); });
});
var BoxifyVolumeStreaming = mol_state["StateAction"].build({
    display: { name: 'Boxify Volume Streaming', description: 'Make the current box permanent.' },
    from: volume_streaming_behavior["a" /* VolumeStreaming */],
    isApplicable: function (a) { return a.data.params.entry.params.view.name === 'selection-box'; }
})(function (_a, plugin) {
    var a = _a.a, ref = _a.ref, state = _a.state;
    var params = a.data.params;
    if (params.entry.params.view.name !== 'selection-box')
        return;
    var box = geometry["b" /* Box3D */].create(linear_algebra["Vec3"].clone(params.entry.params.view.params.bottomLeft), linear_algebra["Vec3"].clone(params.entry.params.view.params.topRight));
    var r = params.entry.params.view.params.radius;
    geometry["b" /* Box3D */].expand(box, box, linear_algebra["Vec3"].create(r, r, r));
    var newParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params), { entry: {
            name: params.entry.name,
            params: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, params.entry.params), { view: {
                    name: 'box',
                    params: {
                        bottomLeft: box.min,
                        topRight: box.max
                    }
                } })
        } });
    return state.updateTree(state.build().to(ref).update(newParams));
});
var InfoEntryParams = {
    dataId: param_definition["ParamDefinition"].Text(''),
    source: param_definition["ParamDefinition"].MappedStatic('x-ray', {
        'em': param_definition["ParamDefinition"].Group({
            isoValue: Object(isosurface["c" /* createIsoValueParam */])(volume["b" /* Volume */].IsoValue.relative(1))
        }),
        'x-ray': param_definition["ParamDefinition"].Group({})
    })
};

var CreateVolumeStreamingInfo = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'create-volume-streaming-info',
    display: { name: 'Volume Streaming Info' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: model_VolumeServerInfo,
    params: function (a) {
        return {
            serverUrl: param_definition["ParamDefinition"].Text('https://ds.litemol.org'),
            entries: param_definition["ParamDefinition"].ObjectList(InfoEntryParams, function (_a) {
                var dataId = _a.dataId;
                return dataId;
            }, {
                defaultValue: [{ dataId: '', source: { name: 'x-ray', params: {} } }]
            }),
        };
    }
})({
    apply: function (_a, plugin) {
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('', function (taskCtx) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
            var entries, i, il, e, dataId, emDefaultContourLevel, header, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        entries = [];
                        i = 0, il = params.entries.length;
                        _a.label = 1;
                    case 1:
                        if (!(i < il)) return [3 /*break*/, 5];
                        e = params.entries[i];
                        dataId = e.dataId;
                        emDefaultContourLevel = e.source.name === 'em' ? e.source.params.isoValue : volume["b" /* Volume */].IsoValue.relative(1);
                        return [4 /*yield*/, taskCtx.update('Getting server header...')];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, plugin.fetch({ url: Object(url["a" /* urlCombine */])(params.serverUrl, e.source.name + "/" + dataId.toLocaleLowerCase()), type: 'json' }).runInContext(taskCtx)];
                    case 3:
                        header = _a.sent();
                        entries.push({
                            dataId: dataId,
                            kind: e.source.name,
                            header: header,
                            emDefaultContourLevel: emDefaultContourLevel
                        });
                        _a.label = 4;
                    case 4:
                        ++i;
                        return [3 /*break*/, 1];
                    case 5:
                        data = {
                            serverUrl: params.serverUrl,
                            entries: entries,
                            structure: a.data
                        };
                        return [2 /*return*/, new model_VolumeServerInfo(data, { label: 'Volume Server', description: "" + entries.map(function (e) { return e.dataId; }).join(', ') })];
                }
            });
        }); });
    }
});

var CreateVolumeStreamingBehavior = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'create-volume-streaming-behavior',
    display: { name: 'Volume Streaming Behavior' },
    from: model_VolumeServerInfo,
    to: volume_streaming_behavior["a" /* VolumeStreaming */],
    params: function (a) {
        return volume_streaming_behavior["a" /* VolumeStreaming */].createParams({ data: a && a.data });
    }
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return oldParams.entry.params.view === newParams.entry.params.view
            || newParams.entry.params.view.name === 'selection-box'
            || newParams.entry.params.view.name === 'off';
    },
    apply: function (_a, plugin) {
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Volume streaming', function (_) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
            var behavior;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        behavior = new volume_streaming_behavior["a" /* VolumeStreaming */].Behavior(plugin, a.data);
                        return [4 /*yield*/, behavior.update(params)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, new volume_streaming_behavior["a" /* VolumeStreaming */](behavior, { label: 'Volume Streaming', description: behavior.getDescription() })];
                }
            });
        }); });
    },
    update: function (_a) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Update Volume Streaming', function (_) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var emDefaultContourLevel, ret;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (oldParams.entry.name !== newParams.entry.name) {
                            if ('em' in newParams.entry.params.channels) {
                                emDefaultContourLevel = b.data.infoMap.get(newParams.entry.name).emDefaultContourLevel;
                                if (emDefaultContourLevel) {
                                    newParams.entry.params.channels['em'].isoValue = emDefaultContourLevel;
                                }
                            }
                        }
                        return [4 /*yield*/, b.data.update(newParams)];
                    case 1:
                        ret = (_a.sent()) ? mol_state["StateTransformer"].UpdateResult.Updated : mol_state["StateTransformer"].UpdateResult.Unchanged;
                        b.description = b.data.getDescription();
                        return [2 /*return*/, ret];
                }
            });
        }); });
    }
});

var VolumeStreamingVisual = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'create-volume-streaming-visual',
    display: { name: 'Volume Streaming Visual' },
    from: volume_streaming_behavior["a" /* VolumeStreaming */],
    to: objects["a" /* PluginStateObject */].Volume.Representation3D,
    params: {
        channel: param_definition["ParamDefinition"].Select('em', volume_streaming_behavior["a" /* VolumeStreaming */].ChannelTypeOptions, { isHidden: true })
    }
})({
    apply: function (_a, plugin) {
        var a = _a.a, srcParams = _a.params;
        return mol_task["b" /* Task */].create('Volume Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
            var channel, params, provider, props, repr;
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        channel = a.data.channels[srcParams.channel];
                        if (!channel)
                            return [2 /*return*/, mol_state["StateObject"].Null];
                        params = createVolumeProps(a.data, srcParams.channel);
                        provider = registry["a" /* VolumeRepresentationRegistry */].BuiltIn.isosurface;
                        props = params.type.params || {};
                        repr = provider.factory(Object(tslib_es6["__assign"])({ webgl: (_a = plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl }, plugin.representation.volume.themes), provider.getParams);
                        repr.setTheme(theme["a" /* Theme */].create(plugin.representation.volume.themes, { volume: channel.data }, params));
                        return [4 /*yield*/, repr.createOrUpdate(props, channel.data).runInContext(ctx)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Volume.Representation3D({ repr: repr, source: a }, { label: Math.round(channel.isoValue.relativeValue * 100) / 100 + " \u03C3 [" + srcParams.channel + "]" })];
                }
            });
        }); });
    },
    update: function (_a, plugin) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Volume Representation', function (ctx) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
            var channel, params, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        channel = a.data.channels[newParams.channel];
                        // TODO: is this correct behavior?
                        if (!channel)
                            return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Unchanged];
                        params = createVolumeProps(a.data, newParams.channel);
                        props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, b.data.repr.props), params.type.params);
                        b.data.repr.setTheme(theme["a" /* Theme */].create(plugin.representation.volume.themes, { volume: channel.data }, params));
                        return [4 /*yield*/, b.data.repr.createOrUpdate(props, channel.data).runInContext(ctx)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    }
});
function createVolumeProps(streaming, channelName) {
    var channel = streaming.channels[channelName];
    return representation["VolumeRepresentation3DHelpers"].getDefaultParamsStatic(streaming.plugin, 'isosurface', { isoValue: channel.isoValue, alpha: channel.opacity, visuals: channel.wireframe ? ['wireframe'] : ['solid'] }, 'uniform', { value: channel.color });
}
//# sourceMappingURL=transformers.js.map

/***/ }),
/* 301 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isObject; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isObject(x) {
    return x !== null && typeof x === 'object';
}
//# sourceMappingURL=isObject.js.map


/***/ }),
/* 302 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return canReportError; });
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(35);
/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */

function canReportError(observer) {
    while (observer) {
        var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped;
        if (closed_1 || isStopped) {
            return false;
        }
        else if (destination && destination instanceof _Subscriber__WEBPACK_IMPORTED_MODULE_0__[/* Subscriber */ "a"]) {
            observer = destination;
        }
        else {
            observer = null;
        }
    }
    return true;
}
//# sourceMappingURL=canReportError.js.map


/***/ }),
/* 303 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StateTreeSpine; });
/* harmony import */ var _transform__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(76);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var StateTreeSpine;
(function (StateTreeSpine) {
    var Impl = /** @class */ (function () {
        function Impl(cells) {
            this.cells = cells;
            this._current = void 0;
        }
        Object.defineProperty(Impl.prototype, "current", {
            get: function () { return this._current; },
            set: function (cell) { this._current = cell; },
            enumerable: false,
            configurable: true
        });
        Impl.prototype.getAncestorOfType = function (t) {
            if (!this._current)
                return void 0;
            var cell = this._current;
            while (true) {
                cell = this.cells.get(cell.transform.parent);
                if (!cell.obj)
                    return void 0;
                if (cell.obj.type === t.type)
                    return cell.obj;
                if (cell.transform.ref === _transform__WEBPACK_IMPORTED_MODULE_0__[/* StateTransform */ "a"].RootRef)
                    return void 0;
            }
        };
        Impl.prototype.getRootOfType = function (t) {
            if (!this._current)
                return void 0;
            var cell = this._current; // check current first
            var ret = void 0;
            while (true) {
                if (!cell.obj)
                    return void 0;
                if (cell.obj.type === t.type) {
                    ret = cell;
                }
                if (cell.transform.ref === _transform__WEBPACK_IMPORTED_MODULE_0__[/* StateTransform */ "a"].RootRef)
                    return ret ? ret.obj : void 0;
                cell = this.cells.get(cell.transform.parent); // assign parent for next check
            }
        };
        return Impl;
    }());
    StateTreeSpine.Impl = Impl;
    function getDecoratorChain(state, currentRef) {
        var cells = state.cells;
        var current = cells.get(currentRef);
        var ret = [current];
        while (current === null || current === void 0 ? void 0 : current.transform.transformer.definition.isDecorator) {
            current = cells.get(current.transform.parent);
            ret.push(current);
        }
        return ret;
    }
    StateTreeSpine.getDecoratorChain = getDecoratorChain;
    function getRootOfType(state, t, ref) {
        var ret = void 0;
        var cell = state.cells.get(ref);
        if (!cell)
            return void 0;
        while (true) {
            if (!cell.obj)
                return void 0;
            if (cell.obj.type === t.type) {
                ret = cell;
            }
            if (cell.transform.ref === _transform__WEBPACK_IMPORTED_MODULE_0__[/* StateTransform */ "a"].RootRef)
                return ret ? ret.obj : void 0;
            cell = state.cells.get(cell.transform.parent); // assign parent for next check
        }
    }
    StateTreeSpine.getRootOfType = getRootOfType;
})(StateTreeSpine || (StateTreeSpine = {}));
//# sourceMappingURL=spine.js.map

/***/ }),
/* 304 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return AtomsSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return ResiduesSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return ChainsSchema; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AtomicIndex; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AtomicHierarchy; });
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/* harmony import */ var _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57);
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var AtomsSchema = {
    /**
     * The chemical element of this atom site.
     * For mmCIF files, this points to atom_type.symbol in the ATOM_TYPE category.
     */
    type_symbol: _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].Schema.Aliased(_mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.type_symbol),
    /**
     * A component of the identifier for this atom site.
     * This is a standardized name for the atom within its residue.
     * For mmCIF files, this points to chem_comp_atom.atom_id in the CHEM_COMP_ATOM category.
     */
    label_atom_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_atom_id,
    /**
     * An alternative identifier for label_atom_id that may be provided by an author
     * in order to match the identification used in the publication that describes the structure.
     */
    auth_atom_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_atom_id,
    /**
     * A component of the identifier for this atom site.
     * Identifies an alternative conformation for this atom site.
     */
    label_alt_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_alt_id,
    /**
     * A component of the identifier for this atom site.
     * For mmCIF files, this points to chem_comp.id in the CHEM_COMP category.
     */
    label_comp_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_comp_id,
    /**
     * An alternative identifier for atom_site.label_comp_id that may be provided by an author
     * in order to match the identification used in the publication that describes the structure.
     */
    auth_comp_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_comp_id,
    /**
     * The net integer charge assigned to this atom.
     * This is the formal charge assignment normally found in chemical diagrams.
     */
    pdbx_formal_charge: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.pdbx_formal_charge,
    /**
     * The index of this atom in the input data.
     * Required because of sorting of atoms.
     */
    sourceIndex: _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].Schema.int
    // id, occupancy and B_iso_or_equiv are part of conformation
};
var ResiduesSchema = {
    /**
     * The group of atoms to which the atom site belongs. This data item is provided for
     * compatibility with the original Protein Data Bank format, and only for that purpose.
     */
    group_PDB: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.group_PDB,
    /**
     * For mmCIF files, this points to entity_poly_seq.num in the ENTITY_POLY_SEQ category.
     */
    label_seq_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_seq_id,
    /**
     * An alternative identifier for atom_site.label_seq_id that may be provided by an author
     * in order to match the identification used in the publication that describes the structure.
     */
    auth_seq_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_seq_id,
    /**
     * PDB insertion code.
     */
    pdbx_PDB_ins_code: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.pdbx_PDB_ins_code,
};
var ChainsSchema = {
    /**
     * A component of the identifier for this atom site.
     * For mmCIF files, this points to struct_asym.id in the STRUCT_ASYM category.
     */
    label_asym_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_asym_id,
    /**
     * An alternative identifier for atomsite.label_asym_id that may be provided by an author
     * in order to match the identification used in the publication that describes the structure.
     */
    auth_asym_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_asym_id,
    /**
     * For mmCIF files, this points to _entity.id in the ENTITY category.
     */
    label_entity_id: _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_entity_id
};
var AtomicIndex;
(function (AtomicIndex) {
    function EmptyResidueKey() { return { label_entity_id: '', label_asym_id: '', auth_seq_id: 0, pdbx_PDB_ins_code: void 0 }; }
    AtomicIndex.EmptyResidueKey = EmptyResidueKey;
})(AtomicIndex || (AtomicIndex = {}));
var AtomicHierarchy;
(function (AtomicHierarchy) {
    /** Start residue inclusive */
    function chainStartResidueIndex(segs, cI) {
        return segs.residueAtomSegments.index[segs.chainAtomSegments.offsets[cI]];
    }
    AtomicHierarchy.chainStartResidueIndex = chainStartResidueIndex;
    /** End residue exclusive */
    function chainEndResidueIndexExcl(segs, cI) {
        return segs.residueAtomSegments.index[segs.chainAtomSegments.offsets[cI + 1] - 1] + 1;
    }
    AtomicHierarchy.chainEndResidueIndexExcl = chainEndResidueIndexExcl;
    function chainResidueCount(segs, cI) {
        return chainEndResidueIndexExcl(segs, cI) - chainStartResidueIndex(segs, cI);
    }
    AtomicHierarchy.chainResidueCount = chainResidueCount;
})(AtomicHierarchy || (AtomicHierarchy = {}));
//# sourceMappingURL=hierarchy.js.map

/***/ }),
/* 305 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return AtomicNumbers; });
/* unused harmony export ElementVdwRadii */
/* unused harmony export ElementAtomWeights */
/* unused harmony export DefaultVdwRadius */
/* unused harmony export DefaultAtomWeight */
/* unused harmony export DefaultAtomNumber */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return VdwRadius; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return AtomWeight; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AtomNumber; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var AtomicNumbers = {
    'H': 1, 'D': 1, 'T': 1, 'HE': 2, 'LI': 3, 'BE': 4, 'B': 5, 'C': 6, 'N': 7, 'O': 8, 'F': 9, 'NE': 10, 'NA': 11, 'MG': 12, 'AL': 13, 'SI': 14, 'P': 15, 'S': 16, 'CL': 17, 'AR': 18, 'K': 19, 'CA': 20, 'SC': 21, 'TI': 22, 'V': 23, 'CR': 24, 'MN': 25, 'FE': 26, 'CO': 27, 'NI': 28, 'CU': 29, 'ZN': 30, 'GA': 31, 'GE': 32, 'AS': 33, 'SE': 34, 'BR': 35, 'KR': 36, 'RB': 37, 'SR': 38, 'Y': 39, 'ZR': 40, 'NB': 41, 'MO': 42, 'TC': 43, 'RU': 44, 'RH': 45, 'PD': 46, 'AG': 47, 'CD': 48, 'IN': 49, 'SN': 50, 'SB': 51, 'TE': 52, 'I': 53, 'XE': 54, 'CS': 55, 'BA': 56, 'LA': 57, 'CE': 58, 'PR': 59, 'ND': 60, 'PM': 61, 'SM': 62, 'EU': 63, 'GD': 64, 'TB': 65, 'DY': 66, 'HO': 67, 'ER': 68, 'TM': 69, 'YB': 70, 'LU': 71, 'HF': 72, 'TA': 73, 'W': 74, 'RE': 75, 'OS': 76, 'IR': 77, 'PT': 78, 'AU': 79, 'HG': 80, 'TL': 81, 'PB': 82, 'BI': 83, 'PO': 84, 'AT': 85, 'RN': 86, 'FR': 87, 'RA': 88, 'AC': 89, 'TH': 90, 'PA': 91, 'U': 92, 'NP': 93, 'PU': 94, 'AM': 95, 'CM': 96, 'BK': 97, 'CF': 98, 'ES': 99, 'FM': 100, 'MD': 101, 'NO': 102, 'LR': 103, 'RF': 104, 'DB': 105, 'SG': 106, 'BH': 107, 'HS': 108, 'MT': 109
};
// http://dx.doi.org/10.1021/jp8111556 (or 2.0)
var ElementVdwRadii = {
    1: 1.1, 2: 1.4, 3: 1.81, 4: 1.53, 5: 1.92, 6: 1.7, 7: 1.55, 8: 1.52, 9: 1.47, 10: 1.54, 11: 2.27, 12: 1.73, 13: 1.84, 14: 2.1, 15: 1.8, 16: 1.8, 17: 1.75, 18: 1.88, 19: 2.75, 20: 2.31, 21: 2.3, 22: 2.15, 23: 2.05, 24: 2.05, 25: 2.05, 26: 2.05, 27: 2.0, 28: 2.0, 29: 2.0, 30: 2.1, 31: 1.87, 32: 2.11, 33: 1.85, 34: 1.9, 35: 1.83, 36: 2.02, 37: 3.03, 38: 2.49, 39: 2.4, 40: 2.3, 41: 2.15, 42: 2.1, 43: 2.05, 44: 2.05, 45: 2.0, 46: 2.05, 47: 2.1, 48: 2.2, 49: 2.2, 50: 1.93, 51: 2.17, 52: 2.06, 53: 1.98, 54: 2.16, 55: 3.43, 56: 2.68, 57: 2.5, 58: 2.48, 59: 2.47, 60: 2.45, 61: 2.43, 62: 2.42, 63: 2.4, 64: 2.38, 65: 2.37, 66: 2.35, 67: 2.33, 68: 2.32, 69: 2.3, 70: 2.28, 71: 2.27, 72: 2.25, 73: 2.2, 74: 2.1, 75: 2.05, 76: 2.0, 77: 2.0, 78: 2.05, 79: 2.1, 80: 2.05, 81: 1.96, 82: 2.02, 83: 2.07, 84: 1.97, 85: 2.02, 86: 2.2, 87: 3.48, 88: 2.83, 89: 2.0, 90: 2.4, 91: 2.0, 92: 2.3, 93: 2.0, 94: 2.0, 95: 2.0, 96: 2.0, 97: 2.0, 98: 2.0, 99: 2.0, 100: 2.0, 101: 2.0, 102: 2.0, 103: 2.0, 104: 2.0, 105: 2.0, 106: 2.0, 107: 2.0, 108: 2.0, 109: 2.0
};
// https://doi.org/10.1515/pac-2015-0305 (table 2, 3, and 4)
var ElementAtomWeights = {
    1: 1.008, 2: 4.0026, 3: 6.94, 4: 9.0122, 5: 10.81, 6: 10.81, 7: 14.007, 8: 15.999, 9: 18.998, 10: 20.180, 11: 22.990, 12: 24.305, 13: 26.982, 14: 28.085, 15: 30.974, 16: 32.06, 17: 35.45, 18: 39.948, 19: 39.098, 20: 40.078, 21: 44.956, 22: 47.867, 23: 50.942, 24: 51.996, 25: 54.938, 26: 55.845, 27: 58.933, 28: 58.693, 29: 63.546, 30: 65.38, 31: 69.723, 32: 72.630, 33: 74.922, 34: 78.971, 35: 79.904, 36: 83.798, 37: 85.468, 38: 87.62, 39: 88.906, 40: 91.224, 41: 92.906, 42: 95.95, 43: 96.906, 44: 101.07, 45: 102.91, 46: 106.42, 47: 107.87, 48: 112.41, 49: 114.82, 50: 118.71, 51: 121.76, 52: 127.60, 53: 127.60, 54: 131.29, 55: 132.91, 56: 137.33, 57: 138.91, 58: 140.12, 59: 140.91, 60: 144.24, 61: 144.912, 62: 150.36, 63: 151.96, 64: 157.25, 65: 158.93, 66: 162.50, 67: 164.93, 68: 167.26, 69: 168.93, 70: 173.05, 71: 174.97, 72: 178.49, 73: 180.95, 74: 183.84, 75: 186.21, 76: 190.23, 77: 192.22, 78: 195.08, 79: 196.97, 80: 200.59, 81: 204.38, 82: 207.2, 83: 208.98, 84: 1.97, 85: 2.02, 86: 2.2, 87: 3.48, 88: 2.83, 89: 2.0, 90: 232.04, 91: 231.04, 92: 238.03, 93: 237.048, 94: 244.064, 95: 243.061, 96: 247.070, 97: 247.070, 98: 251.079, 99: 252.083, 100: 257.095, 101: 258.098, 102: 259.101, 103: 262.110, 104: 267.122, 105: 270.131, 106: 271.134, 107: 270.133, 108: 270.134, 109: 278.156
};
var DefaultVdwRadius = 1.7; // C
var DefaultAtomWeight = 10.81; // C
var DefaultAtomNumber = 0;
function VdwRadius(element) {
    var i = AtomicNumbers[element];
    return i === void 0 ? DefaultVdwRadius : ElementVdwRadii[i];
}
function AtomWeight(element) {
    var i = AtomicNumbers[element];
    return i === void 0 ? DefaultAtomWeight : ElementAtomWeights[i];
}
function AtomNumber(element) {
    var i = AtomicNumbers[element];
    return i === void 0 ? DefaultAtomNumber : i;
}
//# sourceMappingURL=measures.js.map

/***/ }),
/* 306 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return getIntraBondOrderFromTable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getInterBondOrderFromTable; });
/* harmony import */ var _types__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(22);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/**
 * Map of intra component bond orders in aminoacids and nucleotides assuming standard IUPAC naming.
 * The key is constructed as `${compId}|${atomId1}|${atomId2}` with `atomId1 < atomId2`.
 */
var IntraBondOrderTable = new Map([
    ['HIS|CD2|CG', 2],
    ['HIS|CE1|ND1', 2],
    ['ARG|CZ|NH2', 2],
    ['PHE|CE1|CZ', 2],
    ['PHE|CD2|CE2', 2],
    ['PHE|CD1|CG', 2],
    ['TRP|CD1|CG', 2],
    ['TRP|CD2|CE2', 2],
    ['TRP|CE3|CZ3', 2],
    ['TRP|CH2|CZ2', 2],
    ['ASN|CG|OD1', 2],
    ['GLN|CD|OE1', 2],
    ['TYR|CD1|CG', 2],
    ['TYR|CD2|CE2', 2],
    ['TYR|CE1|CZ', 2],
    ['ASP|CG|OD1', 2],
    ['GLU|CD|OE1', 2],
    ['G|C8|N7', 2],
    ['G|C4|C5', 2],
    ['G|C2|N3', 2],
    ['G|C6|O6', 2],
    ['C|C4|N3', 2],
    ['C|C5|C6', 2],
    ['C|C2|O2', 2],
    ['A|C2|N3', 2],
    ['A|C6|N1', 2],
    ['A|C4|C5', 2],
    ['A|C8|N7', 2],
    ['U|C5|C6', 2],
    ['U|C2|O2', 2],
    ['U|C4|O4', 2],
    ['DG|C8|N7', 2],
    ['DG|C4|C5', 2],
    ['DG|C2|N3', 2],
    ['DG|C6|O6', 2],
    ['DC|C4|N3', 2],
    ['DC|C5|C6', 2],
    ['DC|C2|O2', 2],
    ['DA|C2|N3', 2],
    ['DA|C6|N1', 2],
    ['DA|C4|C5', 2],
    ['DA|C8|N7', 2],
    ['DT|C5|C6', 2],
    ['DT|C2|O2', 2],
    ['DT|C4|O4', 2]
]);
/**
 * Get order for bonds in aminoacids and nucleotides assuming standard IUPAC naming
 */
function getIntraBondOrderFromTable(compId, atomId1, atomId2) {
    var _a;
    _a = atomId1 < atomId2 ? [atomId1, atomId2] : [atomId2, atomId1], atomId1 = _a[0], atomId2 = _a[1];
    if (_types__WEBPACK_IMPORTED_MODULE_0__["AminoAcidNames"].has(compId) && atomId1 === 'C' && atomId2 === 'O')
        return 2;
    if (_types__WEBPACK_IMPORTED_MODULE_0__["BaseNames"].has(compId) && atomId1 === 'OP1' && atomId2 === 'P')
        return 2;
    return IntraBondOrderTable.get(compId + "|" + atomId1 + "|" + atomId2) || 1;
}
/**
 * Map of inter component bond orders assuming PDBx/mmCIF naming.
 * The key is constructed as `${compId1}|${compId2}|${atomId1}|${atomId2}` with `compId1 < compId2`.
 */
var InterBondOrderTable = new Map([
    ['LYS|NZ|RET|C15', 2] // Schiff base in Rhodopsin and Bacteriorhodopsin
]);
/**
 * Get order for bonds between component assuming PDBx/mmCIF naming.
 */
function getInterBondOrderFromTable(compId1, atomId1, compId2, atomId2) {
    var _a, _b;
    if (compId1 > compId2) {
        _a = [compId2, compId1], compId1 = _a[0], compId2 = _a[1];
        _b = [atomId2, atomId1], atomId1 = _b[0], atomId2 = _b[1];
    }
    return InterBondOrderTable.get(compId1 + "|" + atomId1 + "|" + compId2 + "|" + atomId2) || 1;
}
//# sourceMappingURL=bonds.js.map

/***/ }),
/* 307 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementSymbolColors", function() { return ElementSymbolColors; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementSymbolColorThemeParams", function() { return ElementSymbolColorThemeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getElementSymbolColorThemeParams", function() { return getElementSymbolColorThemeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "elementSymbolColor", function() { return elementSymbolColor; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementSymbolColorTheme", function() { return ElementSymbolColorTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ElementSymbolColorThemeProvider", function() { return ElementSymbolColorThemeProvider; });
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/* harmony import */ var _mol_util_legend__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(141);
/* harmony import */ var _mol_util_color_color__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(43);
/* harmony import */ var _chain_id__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(327);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






// from Jmol http://jmol.sourceforge.net/jscolors/ (or 0xFFFFFF)
var ElementSymbolColors = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["ColorMap"])({
    'H': 0xFFFFFF, 'D': 0xFFFFC0, 'T': 0xFFFFA0, 'HE': 0xD9FFFF, 'LI': 0xCC80FF, 'BE': 0xC2FF00, 'B': 0xFFB5B5, 'C': 0x909090, 'N': 0x3050F8, 'O': 0xFF0D0D, 'F': 0x90E050, 'NE': 0xB3E3F5, 'NA': 0xAB5CF2, 'MG': 0x8AFF00, 'AL': 0xBFA6A6, 'SI': 0xF0C8A0, 'P': 0xFF8000, 'S': 0xFFFF30, 'CL': 0x1FF01F, 'AR': 0x80D1E3, 'K': 0x8F40D4, 'CA': 0x3DFF00, 'SC': 0xE6E6E6, 'TI': 0xBFC2C7, 'V': 0xA6A6AB, 'CR': 0x8A99C7, 'MN': 0x9C7AC7, 'FE': 0xE06633, 'CO': 0xF090A0, 'NI': 0x50D050, 'CU': 0xC88033, 'ZN': 0x7D80B0, 'GA': 0xC28F8F, 'GE': 0x668F8F, 'AS': 0xBD80E3, 'SE': 0xFFA100, 'BR': 0xA62929, 'KR': 0x5CB8D1, 'RB': 0x702EB0, 'SR': 0x00FF00, 'Y': 0x94FFFF, 'ZR': 0x94E0E0, 'NB': 0x73C2C9, 'MO': 0x54B5B5, 'TC': 0x3B9E9E, 'RU': 0x248F8F, 'RH': 0x0A7D8C, 'PD': 0x006985, 'AG': 0xC0C0C0, 'CD': 0xFFD98F, 'IN': 0xA67573, 'SN': 0x668080, 'SB': 0x9E63B5, 'TE': 0xD47A00, 'I': 0x940094, 'XE': 0x940094, 'CS': 0x57178F, 'BA': 0x00C900, 'LA': 0x70D4FF, 'CE': 0xFFFFC7, 'PR': 0xD9FFC7, 'ND': 0xC7FFC7, 'PM': 0xA3FFC7, 'SM': 0x8FFFC7, 'EU': 0x61FFC7, 'GD': 0x45FFC7, 'TB': 0x30FFC7, 'DY': 0x1FFFC7, 'HO': 0x00FF9C, 'ER': 0x00E675, 'TM': 0x00D452, 'YB': 0x00BF38, 'LU': 0x00AB24, 'HF': 0x4DC2FF, 'TA': 0x4DA6FF, 'W': 0x2194D6, 'RE': 0x267DAB, 'OS': 0x266696, 'IR': 0x175487, 'PT': 0xD0D0E0, 'AU': 0xFFD123, 'HG': 0xB8B8D0, 'TL': 0xA6544D, 'PB': 0x575961, 'BI': 0x9E4FB5, 'PO': 0xAB5C00, 'AT': 0x754F45, 'RN': 0x428296, 'FR': 0x420066, 'RA': 0x007D00, 'AC': 0x70ABFA, 'TH': 0x00BAFF, 'PA': 0x00A1FF, 'U': 0x008FFF, 'NP': 0x0080FF, 'PU': 0x006BFF, 'AM': 0x545CF2, 'CM': 0x785CE3, 'BK': 0x8A4FE3, 'CF': 0xA136D4, 'ES': 0xB31FD4, 'FM': 0xB31FBA, 'MD': 0xB30DA6, 'NO': 0xBD0D87, 'LR': 0xC70066, 'RF': 0xCC0059, 'DB': 0xD1004F, 'SG': 0xD90045, 'BH': 0xE00038, 'HS': 0xE6002E, 'MT': 0xEB0026, 'DS': 0xFFFFFF, 'RG': 0xFFFFFF, 'CN': 0xFFFFFF, 'UUT': 0xFFFFFF, 'FL': 0xFFFFFF, 'UUP': 0xFFFFFF, 'LV': 0xFFFFFF, 'UUH': 0xFFFFFF
});
var DefaultElementSymbolColor = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["Color"])(0xFFFFFF);
var Description = 'Assigns a color to every atom according to its chemical element.';
var ElementSymbolColorThemeParams = {
    carbonByChainId: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Boolean(true),
    saturation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Numeric(0, { min: -6, max: 6, step: 0.1 }),
    lightness: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Numeric(0.2, { min: -6, max: 6, step: 0.1 })
};
function getElementSymbolColorThemeParams(ctx) {
    return ElementSymbolColorThemeParams; // TODO return copy
}
function elementSymbolColor(colorMap, element) {
    var c = colorMap[element];
    return c === undefined ? DefaultElementSymbolColor : c;
}
function ElementSymbolColorTheme(ctx, props) {
    var colorMap = Object(_mol_util_color_color__WEBPACK_IMPORTED_MODULE_4__["getAdjustedColorMap"])(ElementSymbolColors, props.saturation, props.lightness);
    var chainIdColor = Object(_chain_id__WEBPACK_IMPORTED_MODULE_5__[/* ChainIdColorTheme */ "a"])(ctx, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(Object(_chain_id__WEBPACK_IMPORTED_MODULE_5__[/* getChainIdColorThemeParams */ "c"])(ctx))).color;
    function elementColor(element, location) {
        return (props.carbonByChainId && element === 'C')
            ? chainIdColor(location, false)
            : elementSymbolColor(colorMap, element);
    }
    function color(location) {
        if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.is(location)) {
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isAtomic(location.unit)) {
                var type_symbol = location.unit.model.atomicHierarchy.atoms.type_symbol;
                return elementColor(type_symbol.value(location.element), location);
            }
        }
        else if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Bond"].isLocation(location)) {
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Unit"].isAtomic(location.aUnit)) {
                var type_symbol = location.aUnit.model.atomicHierarchy.atoms.type_symbol;
                var element = type_symbol.value(location.aUnit.elements[location.aIndex]);
                return elementColor(element, location);
            }
        }
        return DefaultElementSymbolColor;
    }
    return {
        factory: ElementSymbolColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: Description,
        legend: Object(_mol_util_legend__WEBPACK_IMPORTED_MODULE_3__[/* TableLegend */ "b"])(Object.keys(ElementSymbolColors).map(function (name) {
            return [name, ElementSymbolColors[name]];
        }))
    };
}
var ElementSymbolColorThemeProvider = {
    name: 'element-symbol',
    label: 'Element Symbol',
    category: "Atom Property" /* Atom */,
    factory: ElementSymbolColorTheme,
    getParams: getElementSymbolColorThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(ElementSymbolColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=element-symbol.js.map

/***/ }),
/* 308 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "dateToUtcString", function() { return dateToUtcString; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "getFormattedTime", function() { return getFormattedTime; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function dateToUtcString(date) {
    return date.toISOString().replace(/T/, ' ').replace(/\..+/, '');
}
function getFormattedTime() {
    var today = new Date();
    var y = today.getFullYear();
    var m = today.getMonth() + 1;
    var d = today.getDate();
    var h = today.getHours();
    var mi = today.getMinutes();
    var s = today.getSeconds();
    return y + '-' + m + '-' + d + '-' + h + '-' + mi + '-' + s;
}
//# sourceMappingURL=date.js.map

/***/ }),
/* 309 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return addEllipsoid; });
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(1);
/* harmony import */ var _mesh_builder__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(34);
/* harmony import */ var _sphere__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(75);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var tmpEllipsoidMat = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].identity();
var tmpVec = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"])();
function setEllipsoidMat(m, center, dirMajor, dirMinor, radiusScale) {
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Vec3"].add(tmpVec, center, dirMajor);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].targetTo(m, center, tmpVec, dirMinor);
    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].setTranslation(m, center);
    return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_0__["Mat4"].scale(m, m, radiusScale);
}
function addEllipsoid(state, center, dirMajor, dirMinor, radiusScale, detail) {
    _mesh_builder__WEBPACK_IMPORTED_MODULE_1__[/* MeshBuilder */ "a"].addPrimitive(state, setEllipsoidMat(tmpEllipsoidMat, center, dirMajor, dirMinor, radiusScale), Object(_sphere__WEBPACK_IMPORTED_MODULE_2__[/* getSphere */ "b"])(detail));
}
//# sourceMappingURL=ellipsoid.js.map

/***/ }),
/* 310 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ApplyActionControl; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(26);
/* harmony import */ var _mol_util_memoize__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(155);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(287);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var ApplyActionControl = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ApplyActionControl, _super);
    function ApplyActionControl() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this._getInfo = Object(_mol_util_memoize__WEBPACK_IMPORTED_MODULE_2__[/* memoizeLatest */ "b"])(function (t, v) { return _common__WEBPACK_IMPORTED_MODULE_3__[/* StateTransformParameters */ "a"].infoFromAction(_this.plugin, _this.props.state, _this.props.action, _this.props.nodeRef); });
        _this.state = { plugin: _this.plugin, ref: _this.props.nodeRef, version: _this.props.state.transforms.get(_this.props.nodeRef).version, error: void 0, isInitial: true, params: _this.getInfo().initialValues, busy: false, isCollapsed: _this.props.initiallyCollapsed };
        return _this;
    }
    ApplyActionControl.prototype.applyAction = function () {
        return _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_1__["PluginCommands"].State.ApplyAction(this.plugin, {
            state: this.props.state,
            action: this.props.action.create(this.state.params),
            ref: this.props.nodeRef
        });
    };
    ApplyActionControl.prototype.getInfo = function () { return this._getInfo(this.props.nodeRef, this.props.state.transforms.get(this.props.nodeRef).version); };
    ApplyActionControl.prototype.getTransformerId = function () { return this.props.state.transforms.get(this.props.nodeRef).transformer.id; };
    ApplyActionControl.prototype.getHeader = function () { return this.props.hideHeader ? 'none' : this.props.action.definition.display; };
    ApplyActionControl.prototype.canApply = function () { return !this.state.error && !this.state.busy; };
    ApplyActionControl.prototype.canAutoApply = function () { return false; };
    ApplyActionControl.prototype.applyText = function () { return 'Apply'; };
    ApplyActionControl.prototype.isUpdate = function () { return false; };
    ApplyActionControl.prototype.getSourceAndTarget = function () { return { a: this.props.state.cells.get(this.props.nodeRef).obj }; };
    ApplyActionControl.getDerivedStateFromProps = function (props, state) {
        var version = props.state.transforms.get(props.nodeRef).version;
        if (props.nodeRef === state.ref && version === state.version) {
            return null;
        }
        var source = props.state.cells.get(props.nodeRef).obj;
        var params = props.action.definition.params
            ? _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(props.action.definition.params(source, state.plugin))
            : {};
        var newState = {
            plugin: state.plugin,
            ref: props.nodeRef,
            version: version,
            params: params,
            isInitial: true,
            error: void 0
        };
        return newState;
    };
    return ApplyActionControl;
}(_common__WEBPACK_IMPORTED_MODULE_3__[/* TransformControlBase */ "b"]));
//# sourceMappingURL=apply-action.js.map

/***/ }),
/* 311 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return scheduleArray; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70);
/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */


function scheduleArray(input, scheduler) {
    return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) {
        var sub = new _Subscription__WEBPACK_IMPORTED_MODULE_1__[/* Subscription */ "a"]();
        var i = 0;
        sub.add(scheduler.schedule(function () {
            if (i === input.length) {
                subscriber.complete();
                return;
            }
            subscriber.next(input[i++]);
            if (!subscriber.closed) {
                sub.add(this.schedule());
            }
        }));
        return sub;
    });
}
//# sourceMappingURL=scheduleArray.js.map


/***/ }),
/* 312 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ asap; });

// EXTERNAL MODULE: ./node_modules/rxjs/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(21);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/Immediate.js
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var nextHandle = 1;
var RESOLVED = /*@__PURE__*/ (function () { return /*@__PURE__*/ Promise.resolve(); })();
var activeHandles = {};
function findAndClearHandle(handle) {
    if (handle in activeHandles) {
        delete activeHandles[handle];
        return true;
    }
    return false;
}
var Immediate = {
    setImmediate: function (cb) {
        var handle = nextHandle++;
        activeHandles[handle] = true;
        RESOLVED.then(function () { return findAndClearHandle(handle) && cb(); });
        return handle;
    },
    clearImmediate: function (handle) {
        findAndClearHandle(handle);
    },
};
var TestTools = {
    pending: function () {
        return Object.keys(activeHandles).length;
    }
};
//# sourceMappingURL=Immediate.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules
var AsyncAction = __webpack_require__(229);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsapAction.js
/** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */



var AsapAction_AsapAction = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AsapAction, _super);
    function AsapAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (delay !== null && delay > 0) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        scheduler.actions.push(this);
        return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null)));
    };
    AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
            return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay);
        }
        if (scheduler.actions.length === 0) {
            Immediate.clearImmediate(id);
            scheduler.scheduled = undefined;
        }
        return undefined;
    };
    return AsapAction;
}(AsyncAction["a" /* AsyncAction */]));

//# sourceMappingURL=AsapAction.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js
var AsyncScheduler = __webpack_require__(225);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsapScheduler.js
/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */


var AsapScheduler_AsapScheduler = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](AsapScheduler, _super);
    function AsapScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    AsapScheduler.prototype.flush = function (action) {
        this.active = true;
        this.scheduled = undefined;
        var actions = this.actions;
        var error;
        var index = -1;
        var count = actions.length;
        action = action || actions.shift();
        do {
            if (error = action.execute(action.state, action.delay)) {
                break;
            }
        } while (++index < count && (action = actions.shift()));
        this.active = false;
        if (error) {
            while (++index < count && (action = actions.shift())) {
                action.unsubscribe();
            }
            throw error;
        }
    };
    return AsapScheduler;
}(AsyncScheduler["a" /* AsyncScheduler */]));

//# sourceMappingURL=AsapScheduler.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/asap.js
/** PURE_IMPORTS_START _AsapAction,_AsapScheduler PURE_IMPORTS_END */


var asap = /*@__PURE__*/ new AsapScheduler_AsapScheduler(AsapAction_AsapAction);
//# sourceMappingURL=asap.js.map


/***/ }),
/* 313 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return empty; });
/* harmony import */ var _config__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(175);
/* harmony import */ var _util_hostReportError__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(248);
/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */


var empty = {
    closed: true,
    next: function (value) { },
    error: function (err) {
        if (_config__WEBPACK_IMPORTED_MODULE_0__[/* config */ "a"].useDeprecatedSynchronousErrorHandling) {
            throw err;
        }
        else {
            Object(_util_hostReportError__WEBPACK_IMPORTED_MODULE_1__[/* hostReportError */ "a"])(err);
        }
    },
    complete: function () { }
};
//# sourceMappingURL=Observer.js.map


/***/ }),
/* 314 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PLUGIN_VERSION; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return PLUGIN_VERSION_DATE; });
const PLUGIN_VERSION = '1.1.1';
const PLUGIN_VERSION_DATE = new Date( true ? 1634651451261 : undefined);

/***/ }),
/* 315 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createVolumeRepresentationParams; });
/* unused harmony export getVolumeThemeTypes */
/* unused harmony export createVolumeColorThemeParams */
/* unused harmony export createVolumeSizeThemeParams */
/* harmony import */ var _mol_model_volume__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(36);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function createVolumeRepresentationParams(ctx, volume, props) {
    if (props === void 0) { props = {}; }
    var p = props;
    if (typeof p.type === 'string' || typeof p.color === 'string' || typeof p.size === 'string')
        return createParamsByName(ctx, volume || _mol_model_volume__WEBPACK_IMPORTED_MODULE_0__[/* Volume */ "b"].One, props);
    return createParamsProvider(ctx, volume || _mol_model_volume__WEBPACK_IMPORTED_MODULE_0__[/* Volume */ "b"].One, props);
}
function getVolumeThemeTypes(ctx, volume) {
    var themeCtx = ctx.representation.volume.themes;
    if (!volume)
        return themeCtx.colorThemeRegistry.types;
    return themeCtx.colorThemeRegistry.getApplicableTypes({ volume: volume });
}
function createVolumeColorThemeParams(ctx, volume, typeName, themeName, params) {
    var _a = ctx.representation.volume, registry = _a.registry, themes = _a.themes;
    var repr = registry.get(typeName || registry.default.name);
    var color = themes.colorThemeRegistry.get(themeName || repr.defaultColorTheme.name);
    var colorDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(color.getParams({ volume: volume || _mol_model_volume__WEBPACK_IMPORTED_MODULE_0__[/* Volume */ "b"].One }));
    if (color.name === repr.defaultColorTheme.name)
        Object.assign(colorDefaultParams, repr.defaultColorTheme.props);
    return { name: color.name, params: Object.assign(colorDefaultParams, params) };
}
function createVolumeSizeThemeParams(ctx, volume, typeName, themeName, params) {
    var _a = ctx.representation.volume, registry = _a.registry, themes = _a.themes;
    var repr = registry.get(typeName || registry.default.name);
    var size = themes.sizeThemeRegistry.get(themeName || repr.defaultSizeTheme.name);
    var sizeDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(size.getParams({ volume: volume || _mol_model_volume__WEBPACK_IMPORTED_MODULE_0__[/* Volume */ "b"].One }));
    if (size.name === repr.defaultSizeTheme.name)
        Object.assign(sizeDefaultParams, repr.defaultSizeTheme.props);
    return { name: size.name, params: Object.assign(sizeDefaultParams, params) };
}
function createParamsByName(ctx, volume, props) {
    var typeProvider = (props.type && ctx.representation.volume.registry.get(props.type))
        || ctx.representation.volume.registry.default.provider;
    var colorProvider = (props.color && ctx.representation.volume.themes.colorThemeRegistry.get(props.color))
        || ctx.representation.volume.themes.colorThemeRegistry.get(typeProvider.defaultColorTheme.name);
    var sizeProvider = (props.size && ctx.representation.volume.themes.sizeThemeRegistry.get(props.size))
        || ctx.representation.volume.themes.sizeThemeRegistry.get(typeProvider.defaultSizeTheme.name);
    return createParamsProvider(ctx, volume, {
        type: typeProvider,
        typeParams: props.typeParams,
        color: colorProvider,
        colorParams: props.colorParams,
        size: sizeProvider,
        sizeParams: props.sizeParams
    });
}
function createParamsProvider(ctx, volume, props) {
    if (props === void 0) { props = {}; }
    var themeCtx = ctx.representation.volume.themes;
    var themeDataCtx = { volume: volume };
    var repr = props.type || ctx.representation.volume.registry.default.provider;
    var reprDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(repr.getParams(themeCtx, volume));
    var reprParams = Object.assign(reprDefaultParams, props.typeParams);
    var color = props.color || themeCtx.colorThemeRegistry.get(repr.defaultColorTheme.name);
    var colorDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(color.getParams(themeDataCtx));
    if (color.name === repr.defaultColorTheme.name)
        Object.assign(colorDefaultParams, repr.defaultColorTheme.props);
    var colorParams = Object.assign(colorDefaultParams, props.colorParams);
    var size = props.size || themeCtx.sizeThemeRegistry.get(repr.defaultSizeTheme.name);
    var sizeDefaultParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(size.getParams(themeDataCtx));
    if (size.name === repr.defaultSizeTheme.name)
        Object.assign(sizeDefaultParams, repr.defaultSizeTheme.props);
    var sizeParams = Object.assign(sizeDefaultParams, props.sizeParams);
    return ({
        type: { name: repr.name, params: reprParams },
        colorTheme: { name: color.name, params: colorParams },
        sizeTheme: { name: size.name, params: sizeParams }
    });
}
//# sourceMappingURL=volume-representation-params.js.map

/***/ }),
/* 316 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "CoordinatesFromDcd", function() { return /* binding */ CoordinatesFromDcd; });
__webpack_require__.d(__webpack_exports__, "CoordinatesFromXtc", function() { return /* binding */ CoordinatesFromXtc; });
__webpack_require__.d(__webpack_exports__, "TopologyFromPsf", function() { return /* binding */ TopologyFromPsf; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromModelAndCoordinates", function() { return /* binding */ TrajectoryFromModelAndCoordinates; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromBlob", function() { return /* binding */ TrajectoryFromBlob; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromMmCif", function() { return /* binding */ TrajectoryFromMmCif; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromPDB", function() { return /* binding */ TrajectoryFromPDB; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromGRO", function() { return /* binding */ TrajectoryFromGRO; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromMOL", function() { return /* binding */ TrajectoryFromMOL; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromMOL2", function() { return /* binding */ TrajectoryFromMOL2; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromCube", function() { return /* binding */ TrajectoryFromCube; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFromCifCore", function() { return /* binding */ TrajectoryFromCifCore; });
__webpack_require__.d(__webpack_exports__, "TrajectoryFrom3DG", function() { return /* binding */ TrajectoryFrom3DG; });
__webpack_require__.d(__webpack_exports__, "ModelFromTrajectory", function() { return /* binding */ ModelFromTrajectory; });
__webpack_require__.d(__webpack_exports__, "StructureFromTrajectory", function() { return /* binding */ StructureFromTrajectory; });
__webpack_require__.d(__webpack_exports__, "StructureFromModel", function() { return /* binding */ StructureFromModel; });
__webpack_require__.d(__webpack_exports__, "TransformStructureConformation", function() { return /* binding */ TransformStructureConformation; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionFromExpression", function() { return /* binding */ StructureSelectionFromExpression; });
__webpack_require__.d(__webpack_exports__, "MultiStructureSelectionFromExpression", function() { return /* binding */ MultiStructureSelectionFromExpression; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionFromScript", function() { return /* binding */ StructureSelectionFromScript; });
__webpack_require__.d(__webpack_exports__, "StructureSelectionFromBundle", function() { return /* binding */ StructureSelectionFromBundle; });
__webpack_require__.d(__webpack_exports__, "StructureComplexElement", function() { return /* binding */ StructureComplexElement; });
__webpack_require__.d(__webpack_exports__, "StructureComponent", function() { return /* binding */ StructureComponent; });
__webpack_require__.d(__webpack_exports__, "CustomModelProperties", function() { return /* binding */ CustomModelProperties; });
__webpack_require__.d(__webpack_exports__, "CustomStructureProperties", function() { return /* binding */ CustomStructureProperties; });
__webpack_require__.d(__webpack_exports__, "ShapeFromPly", function() { return /* binding */ ShapeFromPly; });
__webpack_require__.d(__webpack_exports__, "StructureComplexElementTypes", function() { return /* binding */ StructureComplexElementTypes; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/result.js
var reader_result = __webpack_require__(67);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/tokenizer.js
var text_tokenizer = __webpack_require__(20);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/data-model.js
var data_model = __webpack_require__(128);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/csv/data-model.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function CsvFile(table) {
    return { table: table };
}
function CsvTable(rowCount, columnNames, columns) {
    return { rowCount: rowCount, columnNames: Object(tslib_es6["__spreadArrays"])(columnNames), getColumn: function (name) { return columns[name]; } };
}
//# sourceMappingURL=data-model.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/csv/field.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var Field = data_model["c" /* CifField */].ofTokens;
//# sourceMappingURL=field.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/csv/parser.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

// import { Column } from 'mol-data/db'





function State(data, runtimeCtx, opts) {
    var tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
    return {
        data: data,
        tokenizer: tokenizer,
        tokenType: 2 /* End */,
        runtimeCtx: runtimeCtx,
        tokens: [],
        fieldCount: 0,
        recordCount: 0,
        columnCount: 0,
        columnNames: [],
        quoteCharCode: opts.quote.charCodeAt(0),
        commentCharCode: opts.comment.charCodeAt(0),
        delimiterCharCode: opts.delimiter.charCodeAt(0),
        noColumnNamesRecord: opts.noColumnNames
    };
}
/**
 * Eat everything until a delimiter or newline occurs.
 * Ignores whitespace at the end of the value, i.e. trim right.
 * Returns true when a newline occurs after the value.
 */
function eatValue(state, delimiterCharCode) {
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        ++state.position;
        switch (c) {
            case 10: // \n
            case 13: // \r
                return true;
            case delimiterCharCode:
                return;
            case 9: // \t
            case 32: // ' '
                break;
            default:
                ++state.tokenEnd;
                break;
        }
    }
}
/**
 * Eats a quoted value. Can contain a newline.
 * Returns true when a newline occurs after the quoted value.
 *
 * Embedded quotes are represented by a pair of double quotes:
 * - ""xx"" => "xx"
 */
function eatQuoted(state, quoteCharCode, delimiterCharCode) {
    ++state.position;
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        if (c === quoteCharCode) {
            var next = state.data.charCodeAt(state.position + 1);
            if (next !== quoteCharCode) {
                // get rid of the quotes.
                state.tokenStart++;
                state.tokenEnd = state.position;
                ++state.position;
                return skipEmpty(state, delimiterCharCode);
            }
        }
        ++state.position;
    }
    state.tokenEnd = state.position;
}
/**
 * Skips empty chars.
 * Returns true when the current char is a newline.
 */
function skipEmpty(state, delimiterCharCode) {
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        if (c !== 9 && c !== 32 && c !== delimiterCharCode) { // \t or ' '
            return c === 10 || c === 13; // \n or \r
        }
        ++state.position;
    }
}
function skipWhitespace(state) {
    var prev = -1;
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        switch (c) {
            case 9: // '\t'
            case 32: // ' '
                prev = c;
                ++state.position;
                break;
            case 10: // \n
                // handle \r\n
                if (prev !== 13) {
                    ++state.lineNumber;
                }
                prev = c;
                ++state.position;
                break;
            case 13: // \r
                prev = c;
                ++state.position;
                ++state.lineNumber;
                break;
            default:
                return;
        }
    }
}
function skipLine(state) {
    while (state.position < state.length) {
        var c = state.data.charCodeAt(state.position);
        if (c === 10 || c === 13)
            return; // \n or \r
        ++state.position;
    }
}
/**
 * Move to the next token.
 * Returns true when the current char is a newline, i.e. indicating a full record.
 */
function moveNextInternal(state) {
    var tokenizer = state.tokenizer;
    skipWhitespace(tokenizer);
    if (tokenizer.position >= tokenizer.length) {
        state.tokenType = 2 /* End */;
        return false;
    }
    tokenizer.tokenStart = tokenizer.position;
    tokenizer.tokenEnd = tokenizer.position;
    var c = state.data.charCodeAt(tokenizer.position);
    switch (c) {
        case state.commentCharCode:
            state.tokenType = 1 /* Comment */;
            skipLine(tokenizer);
            break;
        case state.quoteCharCode:
            state.tokenType = 0 /* Value */;
            return eatQuoted(tokenizer, state.quoteCharCode, state.delimiterCharCode);
        default:
            state.tokenType = 0 /* Value */;
            return eatValue(tokenizer, state.delimiterCharCode);
    }
}
/**
 * Moves to the next non-comment token/line.
 * Returns true when the current char is a newline, i.e. indicating a full record.
 */
function moveNext(state) {
    var newRecord = moveNextInternal(state);
    while (state.tokenType === 1 /* Comment */) {
        newRecord = moveNextInternal(state);
    }
    return newRecord;
}
function readRecordsChunk(chunkSize, state) {
    if (state.tokenType === 2 /* End */)
        return 0;
    var counter = 0;
    var newRecord;
    var tokens = state.tokens, tokenizer = state.tokenizer;
    while (state.tokenType === 0 /* Value */ && counter < chunkSize) {
        text_tokenizer["a" /* TokenBuilder */].add(tokens[state.fieldCount % state.columnCount], tokenizer.tokenStart, tokenizer.tokenEnd);
        ++state.fieldCount;
        newRecord = moveNext(state);
        if (newRecord) {
            ++state.recordCount;
            ++counter;
        }
    }
    return counter;
}
function readRecordsChunks(state) {
    var newRecord = moveNext(state);
    if (newRecord)
        ++state.recordCount;
    return Object(mol_task["c" /* chunkedSubtask */])(state.runtimeCtx, 100000, state, readRecordsChunk, function (ctx, state) { return ctx.update({ message: 'Parsing...', current: state.tokenizer.position, max: state.data.length }); });
}
function addColumn(state) {
    state.columnNames.push(text_tokenizer["b" /* Tokenizer */].getTokenString(state.tokenizer));
    state.tokens.push(text_tokenizer["a" /* TokenBuilder */].create(state.tokenizer.data, state.data.length / 80));
}
function init(state) {
    var newRecord = moveNext(state);
    while (!newRecord) {
        addColumn(state);
        newRecord = moveNext(state);
    }
    addColumn(state);
    state.columnCount = state.columnNames.length;
    if (state.noColumnNamesRecord) {
        state.columnNames.forEach(function (x, i, arr) { return arr[i] = i + ''; });
        text_tokenizer["b" /* Tokenizer */].reset(state.tokenizer);
    }
}
function handleRecords(state) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var columns, i;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    init(state);
                    return [4 /*yield*/, readRecordsChunks(state)];
                case 1:
                    _a.sent();
                    columns = Object.create(null);
                    for (i = 0; i < state.columnCount; ++i) {
                        columns[state.columnNames[i]] = Field(state.tokens[i]);
                    }
                    return [2 /*return*/, CsvTable(state.recordCount, state.columnNames, columns)];
            }
        });
    });
}
function parseInternal(data, ctx, opts) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var state, table, result;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    state = State(data, ctx, opts);
                    ctx.update({ message: 'Parsing...', current: 0, max: data.length });
                    return [4 /*yield*/, handleRecords(state)];
                case 1:
                    table = _a.sent();
                    result = CsvFile(table);
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success(result)];
            }
        });
    });
}
function parseCsv(data, opts) {
    var _this = this;
    var completeOpts = Object.assign({}, { quote: '"', comment: '#', delimiter: ',', noColumnNames: false }, opts);
    return mol_task["b" /* Task */].create('Parse CSV', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, parseInternal(data, ctx, completeOpts)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var mol_data_db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema.js
var cif_schema = __webpack_require__(135);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/3dg/parser.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var Schema = mol_data_db["Column"].Schema;
var Schema3DG = {
    /** Chromosome name */
    chromosome: Schema.str,
    /** Base position */
    position: Schema.int,
    /** X coordinate */
    x: Schema.float,
    /** Y coordinate */
    y: Schema.float,
    /** Z coordinate */
    z: Schema.float,
};
var FieldNames = ['chromosome', 'position', 'x', 'y', 'z'];
function categoryFromTable(name, table) {
    return {
        name: name,
        rowCount: table.rowCount,
        fieldNames: FieldNames,
        getField: function (name) {
            return table.getColumn(FieldNames.indexOf(name).toString());
        }
    };
}
function parse3DG(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse 3DG', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var opts, csvFile, category, table;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    opts = { quote: '', comment: '#', delimiter: '\t', noColumnNames: true };
                    return [4 /*yield*/, parseCsv(data, opts).runInContext(ctx)];
                case 1:
                    csvFile = _a.sent();
                    if (csvFile.isError)
                        return [2 /*return*/, reader_result["a" /* ReaderResult */].error(csvFile.message, csvFile.line)];
                    category = categoryFromTable('3dg', csvFile.result.table);
                    table = Object(cif_schema["toTable"])(Schema3DG, category);
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success({ table: table })];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/spacegroup/cell.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function cell_Cell() {
    return cell_Cell.empty();
}
(function (Cell) {
    function create(size, anglesInRadians) { return { size: size, anglesInRadians: anglesInRadians }; }
    Cell.create = create;
    function empty() { return { size: Object(linear_algebra["Vec3"])(), anglesInRadians: Object(linear_algebra["Vec3"])() }; }
    Cell.empty = empty;
})(cell_Cell || (cell_Cell = {}));
//# sourceMappingURL=cell.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/common/binary.js
var binary = __webpack_require__(324);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/dcd/parser.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






function _parseDcd(data) {
    // http://www.ks.uiuc.edu/Research/vmd/plugins/molfile/dcdplugin.html
    // The DCD format is structured as follows
    //   (FORTRAN UNFORMATTED, with Fortran data type descriptions):
    // HDR     NSET    ISTRT   NSAVC   5-ZEROS NATOM-NFREAT    DELTA   9-ZEROS
    // `CORD'  #files  step 1  step    zeroes  (zero)          timestep  (zeroes)
    //                         interval
    // C*4     INT     INT     INT     5INT    INT             DOUBLE  9INT
    // ==========================================================================
    // NTITLE          TITLE
    // INT (=2)        C*MAXTITL
    //                 (=32)
    // ==========================================================================
    // NATOM
    // #atoms
    // INT
    // ==========================================================================
    // X(I), I=1,NATOM         (DOUBLE)
    // Y(I), I=1,NATOM
    // Z(I), I=1,NATOM
    // ==========================================================================
    var dv = new DataView(data.buffer);
    var header = Object.create(null);
    var frames = [];
    var nextPos = 0;
    // header block
    var intView = new Int32Array(data.buffer, 0, 23);
    var ef = intView[0] !== dv.getInt32(0); // endianess flag
    // swap byte order when big endian (84 indicates little endian)
    if (intView[0] !== 84) {
        var n = data.byteLength;
        for (var i = 0; i < n; i += 4) {
            dv.setFloat32(i, dv.getFloat32(i), true);
        }
    }
    if (intView[0] !== 84) {
        throw new Error('dcd bad format, header block start');
    }
    // format indicator, should read 'CORD'
    var formatString = String.fromCharCode(dv.getUint8(4), dv.getUint8(5), dv.getUint8(6), dv.getUint8(7));
    if (formatString !== 'CORD') {
        throw new Error('dcd bad format, format string');
    }
    var isCharmm = false;
    var extraBlock = false;
    var fourDims = false;
    // version field in charmm, unused in X-PLOR
    if (intView[22] !== 0) {
        isCharmm = true;
        if (intView[12] !== 0)
            extraBlock = true;
        if (intView[13] === 1)
            fourDims = true;
    }
    header.NSET = intView[2];
    header.ISTART = intView[3];
    header.NSAVC = intView[4];
    header.NAMNF = intView[10];
    if (isCharmm) {
        header.DELTA = dv.getFloat32(44, ef);
    }
    else {
        header.DELTA = dv.getFloat64(44, ef);
    }
    if (intView[22] !== 84) {
        throw new Error('dcd bad format, header block end');
    }
    nextPos = nextPos + 21 * 4 + 8;
    // title block
    var titleEnd = dv.getInt32(nextPos, ef);
    var titleStart = nextPos + 1;
    if ((titleEnd - 4) % 80 !== 0) {
        throw new Error('dcd bad format, title block start');
    }
    header.TITLE = Object(binary["c" /* uint8ToString */])(data.subarray(titleStart, titleEnd));
    if (dv.getInt32(titleStart + titleEnd + 4 - 1, ef) !== titleEnd) {
        throw new Error('dcd bad format, title block end');
    }
    nextPos = nextPos + titleEnd + 8;
    // natom block
    if (dv.getInt32(nextPos, ef) !== 4) {
        throw new Error('dcd bad format, natom block start');
    }
    header.NATOM = dv.getInt32(nextPos + 4, ef);
    if (dv.getInt32(nextPos + 8, ef) !== 4) {
        throw new Error('dcd bad format, natom block end');
    }
    nextPos = nextPos + 4 + 8;
    // fixed atoms block
    if (header.NAMNF > 0) {
        // TODO read coordinates and indices of fixed atoms
        throw new Error('dcd format with fixed atoms unsupported, aborting');
    }
    // frames
    var natom = header.NATOM;
    var natom4 = natom * 4;
    for (var i = 0, n = header.NSET; i < n; ++i) {
        var frame = Object.create(null);
        frame.elementCount = natom;
        if (extraBlock) {
            nextPos += 4; // block start
            // TODO this is not standardized and we need to add heuristics to handle more variants
            // cell: A, alpha, B, beta, gamma, C (doubles)
            var size = linear_algebra["Vec3"].create(dv.getFloat64(nextPos, ef), dv.getFloat64(nextPos + 2 * 8, ef), dv.getFloat64(nextPos + 5 * 8, ef));
            var anglesInRadians = linear_algebra["Vec3"].create(dv.getFloat64(nextPos + 1, ef), dv.getFloat64(nextPos + 3 * 8, ef), dv.getFloat64(nextPos + 4 * 8, ef));
            frame.cell = cell_Cell.create(size, anglesInRadians);
            nextPos += 48;
            nextPos += 4; // block end
        }
        // xyz coordinates
        for (var j = 0; j < 3; ++j) {
            if (dv.getInt32(nextPos, ef) !== natom4) {
                throw new Error("dcd bad format, coord block start: " + i + ", " + j);
            }
            nextPos += 4; // block start
            var c = new Float32Array(data.buffer, nextPos, natom);
            if (j === 0)
                frame.x = c;
            else if (j === 1)
                frame.y = c;
            else
                frame.z = c;
            nextPos += natom4;
            if (dv.getInt32(nextPos, ef) !== natom4) {
                throw new Error("dcd bad format, coord block end: " + i + ", " + j);
            }
            nextPos += 4; // block end
        }
        if (fourDims) {
            var bytes = dv.getInt32(nextPos, ef);
            nextPos += 4 + bytes + 4; // block start + skip + block end
        }
        frames.push(frame);
    }
    return { header: header, frames: frames };
}
function parseDcd(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse DCD', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var dcdFile;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            try {
                dcdFile = _parseDcd(data);
                return [2 /*return*/, reader_result["a" /* ReaderResult */].success(dcdFile)];
            }
            catch (e) {
                return [2 /*return*/, reader_result["a" /* ReaderResult */].error(e)];
            }
            return [2 /*return*/];
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/number-parser.js
var number_parser = __webpack_require__(97);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/column/fixed.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



function FixedColumnProvider(lines) {
    return function (offset, width, type) {
        return FixedColumn(lines, offset, width, type);
    };
}
function FixedColumn(lines, offset, width, schema) {
    var data = lines.data, indices = lines.indices, rowCount = lines.count;
    var type = schema.valueType;
    var value = type === 'str' ? function (row) {
        var s = indices[2 * row] + offset, le = indices[2 * row + 1];
        if (s >= le)
            return '';
        var e = s + width;
        if (e > le)
            e = le;
        return Object(text_tokenizer["c" /* trimStr */])(data, s, e);
    } : type === 'int' ? function (row) {
        var s = indices[2 * row] + offset;
        if (s > indices[2 * row + 1])
            return 0;
        return Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(data, s, s + width);
    } : function (row) {
        var s = indices[2 * row] + offset;
        if (s > indices[2 * row + 1])
            return 0;
        return Object(number_parser["c" /* parseFloatSkipLeadingWhitespace */])(data, s, s + width);
    };
    return {
        schema: schema,
        __array: void 0,
        isDefined: true,
        rowCount: rowCount,
        value: value,
        valueKind: function (row) { return 0 /* Present */; },
        toArray: function (params) { return mol_data_db["ColumnHelpers"].createAndFillArray(rowCount, value, params); },
        areValuesEqual: function (rowA, rowB) { return value(rowA) === value(rowB); }
    };
}
//# sourceMappingURL=fixed.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/gro/parser.js
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */






function createEmptyHeader() {
    return {
        title: '',
        timeInPs: 0,
        hasVelocities: false,
        precision: { position: 0, velocity: 0 },
        box: [0, 0, 0]
    };
}
function parser_State(tokenizer, runtimeCtx) {
    return {
        tokenizer: tokenizer,
        header: createEmptyHeader(),
        numberOfAtoms: 0,
        runtimeCtx: runtimeCtx
    };
}
/**
 * title string (free format string, optional time in ps after 't=')
 */
function handleTitleString(state) {
    var tokenizer = state.tokenizer, header = state.header;
    var line = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer);
    // skip potential empty lines...
    if (line.trim().length === 0) {
        line = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer);
    }
    var timeOffset = line.lastIndexOf('t=');
    if (timeOffset >= 0) {
        header.timeInPs = parseFloat(line.substring(timeOffset + 2));
        header.title = line.substring(0, timeOffset).trim();
        if (header.title && header.title[header.title.length - 1] === ',') {
            header.title = header.title.substring(0, header.title.length - 1);
        }
    }
    else {
        header.title = line;
    }
}
/**
 * number of atoms (free format integer)
 */
function handleNumberOfAtoms(state) {
    var tokenizer = state.tokenizer;
    text_tokenizer["b" /* Tokenizer */].markLine(tokenizer);
    var line = text_tokenizer["b" /* Tokenizer */].getTokenString(tokenizer);
    state.numberOfAtoms = parseInt(line);
}
/**
 * This format is fixed, ie. all columns are in a fixed position.
 * Optionally (for now only yet with trjconv) you can write gro files
 * with any number of decimal places, the format will then be n+5
 * positions with n decimal places (n+1 for velocities) in stead
 * of 8 with 3 (with 4 for velocities). Upon reading, the precision
 * will be inferred from the distance between the decimal points
 * (which will be n+5). Columns contain the following information
 * (from left to right):
 *     residue number (5 positions, integer)
 *     residue name (5 characters)
 *     atom name (5 characters)
 *     atom number (5 positions, integer)
 *     position (in nm, x y z in 3 columns, each 8 positions with 3 decimal places)
 *     velocity (in nm/ps (or km/s), x y z in 3 columns, each 8 positions with 4 decimal places)
 */
function handleAtoms(state) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, numberOfAtoms, lines, positionSample, precisions, hasVelocities, pO, pW, vO, vW, col, undef, ret;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = state.tokenizer, numberOfAtoms = state.numberOfAtoms;
                    return [4 /*yield*/, text_tokenizer["b" /* Tokenizer */].readLinesAsync(tokenizer, numberOfAtoms, state.runtimeCtx, 100000)];
                case 1:
                    lines = _a.sent();
                    positionSample = tokenizer.data.substring(lines.indices[0], lines.indices[1]).substring(20);
                    precisions = positionSample.match(/\.\d+/g);
                    hasVelocities = precisions.length === 6;
                    state.header.hasVelocities = hasVelocities;
                    state.header.precision.position = precisions[0].length - 1;
                    state.header.precision.velocity = hasVelocities ? precisions[3].length - 1 : 0;
                    pO = 20;
                    pW = state.header.precision.position + 5;
                    vO = pO + 3 * pW;
                    vW = state.header.precision.velocity + 4;
                    col = FixedColumnProvider(lines);
                    undef = mol_data_db["Column"].Undefined(state.numberOfAtoms, mol_data_db["Column"].Schema.float);
                    ret = {
                        count: state.numberOfAtoms,
                        residueNumber: col(0, 5, mol_data_db["Column"].Schema.int),
                        residueName: col(5, 5, mol_data_db["Column"].Schema.str),
                        atomName: col(10, 5, mol_data_db["Column"].Schema.str),
                        atomNumber: col(15, 5, mol_data_db["Column"].Schema.int),
                        x: col(pO, pW, mol_data_db["Column"].Schema.float),
                        y: col(pO + pW, pW, mol_data_db["Column"].Schema.float),
                        z: col(pO + 2 * pW, pW, mol_data_db["Column"].Schema.float),
                        vx: hasVelocities ? col(vO, vW, mol_data_db["Column"].Schema.float) : undef,
                        vy: hasVelocities ? col(vO + vW, vW, mol_data_db["Column"].Schema.float) : undef,
                        vz: hasVelocities ? col(vO + 2 * vW, vW, mol_data_db["Column"].Schema.float) : undef,
                    };
                    return [2 /*return*/, ret];
            }
        });
    });
}
/**
 * box vectors (free format, space separated reals), values:
 * v1(x) v2(y) v3(z) v1(y) v1(z) v2(x) v2(z) v3(x) v3(y),
 * the last 6 values may be omitted (they will be set to zero).
 * Gromacs only supports boxes with v1(y)=v1(z)=v2(z)=0.
 */
function handleBoxVectors(state) {
    var tokenizer = state.tokenizer;
    var values = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim().split(/\s+/g);
    state.header.box = [+values[0], +values[1], +values[2]];
}
function parser_parseInternal(data, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, structures, state, atoms, result;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
                    return [4 /*yield*/, ctx.update({ message: 'Parsing...', current: 0, max: data.length })];
                case 1:
                    _a.sent();
                    structures = [];
                    _a.label = 2;
                case 2:
                    if (!(tokenizer.position < data.length)) return [3 /*break*/, 4];
                    state = parser_State(tokenizer, ctx);
                    handleTitleString(state);
                    handleNumberOfAtoms(state);
                    return [4 /*yield*/, handleAtoms(state)];
                case 3:
                    atoms = _a.sent();
                    handleBoxVectors(state);
                    structures.push({ header: state.header, atoms: atoms });
                    return [3 /*break*/, 2];
                case 4:
                    result = { structures: structures };
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success(result)];
            }
        });
    });
}
function parseGRO(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse GRO', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, parser_parseInternal(data, ctx)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/pdb/parser.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




function parsePDB(data, id) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse PDB', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () { var _a, _b, _c; return Object(tslib_es6["__generator"])(this, function (_d) {
        switch (_d.label) {
            case 0:
                _b = (_a = reader_result["a" /* ReaderResult */]).success;
                _c = { id: id };
                return [4 /*yield*/, text_tokenizer["b" /* Tokenizer */].readAllLinesAsync(data, ctx)];
            case 1: return [2 /*return*/, _b.apply(_a, [(_c.lines = _d.sent(), _c)])];
        }
    }); }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh-builder.js
var mesh_builder = __webpack_require__(34);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/shape.js + 1 modules
var mol_model_shape = __webpack_require__(49);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/names.js
var names = __webpack_require__(47);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/string.js
var string = __webpack_require__(41);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/shape/ply.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Schäfer, Marco <marco.schaefer@uni-tuebingen.de>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













// TODO support 'edge' element, see https://www.mathworks.com/help/vision/ug/the-ply-format.html
// TODO support missing face element
function createPlyShapeParams(plyFile) {
    var vertex = plyFile && plyFile.getElement('vertex');
    var material = plyFile && plyFile.getElement('material');
    var defaultValues = { group: '', vRed: '', vGreen: '', vBlue: '', mRed: '', mGreen: '', mBlue: '' };
    var groupOptions = [['', '']];
    var colorOptions = [['', '']];
    if (vertex) {
        for (var i = 0, il = vertex.propertyNames.length; i < il; ++i) {
            var name_1 = vertex.propertyNames[i];
            var type = vertex.propertyTypes[i];
            if (type === 'uchar' || type === 'uint8' ||
                type === 'ushort' || type === 'uint16' ||
                type === 'uint' || type === 'uint32' ||
                type === 'int')
                groupOptions.push([name_1, name_1]);
            if (type === 'uchar' || type === 'uint8')
                colorOptions.push([name_1, name_1]);
        }
        // TODO hardcoded as convenience for data provided by MegaMol
        if (vertex.propertyNames.includes('atomid'))
            defaultValues.group = 'atomid';
        else if (vertex.propertyNames.includes('material_index'))
            defaultValues.group = 'material_index';
        if (vertex.propertyNames.includes('red'))
            defaultValues.vRed = 'red';
        if (vertex.propertyNames.includes('green'))
            defaultValues.vGreen = 'green';
        if (vertex.propertyNames.includes('blue'))
            defaultValues.vBlue = 'blue';
    }
    var materialOptions = [['', '']];
    if (material) {
        for (var i = 0, il = material.propertyNames.length; i < il; ++i) {
            var name_2 = material.propertyNames[i];
            var type = material.propertyTypes[i];
            if (type === 'uchar' || type === 'uint8')
                materialOptions.push([name_2, name_2]);
        }
        if (material.propertyNames.includes('red'))
            defaultValues.mRed = 'red';
        if (material.propertyNames.includes('green'))
            defaultValues.mGreen = 'green';
        if (material.propertyNames.includes('blue'))
            defaultValues.mBlue = 'blue';
    }
    var defaultColoring = defaultValues.vRed && defaultValues.vGreen && defaultValues.vBlue ? 'vertex' :
        defaultValues.mRed && defaultValues.mGreen && defaultValues.mBlue ? 'material' : 'uniform';
    return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, mesh_mesh["a" /* Mesh */].Params), { coloring: param_definition["ParamDefinition"].MappedStatic(defaultColoring, {
            vertex: param_definition["ParamDefinition"].Group({
                red: param_definition["ParamDefinition"].Select(defaultValues.vRed, colorOptions, { label: 'Red Property' }),
                green: param_definition["ParamDefinition"].Select(defaultValues.vGreen, colorOptions, { label: 'Green Property' }),
                blue: param_definition["ParamDefinition"].Select(defaultValues.vBlue, colorOptions, { label: 'Blue Property' }),
            }, { isFlat: true }),
            material: param_definition["ParamDefinition"].Group({
                red: param_definition["ParamDefinition"].Select(defaultValues.mRed, materialOptions, { label: 'Red Property' }),
                green: param_definition["ParamDefinition"].Select(defaultValues.mGreen, materialOptions, { label: 'Green Property' }),
                blue: param_definition["ParamDefinition"].Select(defaultValues.mBlue, materialOptions, { label: 'Blue Property' }),
            }, { isFlat: true }),
            uniform: param_definition["ParamDefinition"].Group({
                color: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].grey)
            }, { isFlat: true })
        }), grouping: param_definition["ParamDefinition"].MappedStatic(defaultValues.group ? 'vertex' : 'none', {
            vertex: param_definition["ParamDefinition"].Group({
                group: param_definition["ParamDefinition"].Select(defaultValues.group, groupOptions, { label: 'Group Property' }),
            }, { isFlat: true }),
            none: param_definition["ParamDefinition"].Group({})
        }) });
}
var PlyShapeParams = createPlyShapeParams();
function addVerticesRange(begI, endI, state, vertex, groupIds) {
    var vertices = state.vertices, normals = state.normals, groups = state.groups;
    var x = vertex.getProperty('x');
    var y = vertex.getProperty('y');
    var z = vertex.getProperty('z');
    if (!x || !y || !z)
        throw new Error('missing coordinate properties');
    var nx = vertex.getProperty('nx');
    var ny = vertex.getProperty('ny');
    var nz = vertex.getProperty('nz');
    var hasNormals = !!nx && !!ny && !!nz;
    for (var i = begI; i < endI; ++i) {
        util["a" /* ChunkedArray */].add3(vertices, x.value(i), y.value(i), z.value(i));
        if (hasNormals)
            util["a" /* ChunkedArray */].add3(normals, nx.value(i), ny.value(i), nz.value(i));
        util["a" /* ChunkedArray */].add(groups, groupIds[i]);
    }
}
function addFacesRange(begI, endI, state, face) {
    var indices = state.indices;
    for (var i = begI; i < endI; ++i) {
        var _a = face.value(i), entries = _a.entries, count = _a.count;
        if (count === 3) {
            // triangle
            util["a" /* ChunkedArray */].add3(indices, entries[0], entries[1], entries[2]);
        }
        else if (count === 4) {
            // quadrilateral
            util["a" /* ChunkedArray */].add3(indices, entries[2], entries[1], entries[0]);
            util["a" /* ChunkedArray */].add3(indices, entries[2], entries[0], entries[3]);
        }
    }
}
function getMesh(ctx, vertex, face, groupIds, mesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var builderState, x, y, z, nx, ny, nz, hasNormals, updateChunk, i, il, i, il, m;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    builderState = mesh_builder["a" /* MeshBuilder */].createState(vertex.rowCount, vertex.rowCount / 4, mesh);
                    x = vertex.getProperty('x');
                    y = vertex.getProperty('y');
                    z = vertex.getProperty('z');
                    if (!x || !y || !z)
                        throw new Error('missing coordinate properties');
                    nx = vertex.getProperty('nx');
                    ny = vertex.getProperty('ny');
                    nz = vertex.getProperty('nz');
                    hasNormals = !!nx && !!ny && !!nz;
                    updateChunk = 100000;
                    i = 0, il = vertex.rowCount;
                    _a.label = 1;
                case 1:
                    if (!(i < il)) return [3 /*break*/, 4];
                    addVerticesRange(i, Math.min(i + updateChunk, il), builderState, vertex, groupIds);
                    if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                    return [4 /*yield*/, ctx.update({ message: 'adding ply mesh vertices', current: i, max: il })];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    i += updateChunk;
                    return [3 /*break*/, 1];
                case 4:
                    i = 0, il = face.rowCount;
                    _a.label = 5;
                case 5:
                    if (!(i < il)) return [3 /*break*/, 8];
                    addFacesRange(i, Math.min(i + updateChunk, il), builderState, face);
                    if (!ctx.shouldUpdate) return [3 /*break*/, 7];
                    return [4 /*yield*/, ctx.update({ message: 'adding ply mesh faces', current: i, max: il })];
                case 6:
                    _a.sent();
                    _a.label = 7;
                case 7:
                    i += updateChunk;
                    return [3 /*break*/, 5];
                case 8:
                    m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
                    if (!hasNormals)
                        mesh_mesh["a" /* Mesh */].computeNormals(m);
                    return [2 /*return*/, m];
            }
        });
    });
}
var ply_int = mol_data_db["Column"].Schema.int;
function getGrouping(vertex, props) {
    var grouping = props.grouping;
    var rowCount = vertex.rowCount;
    var column = grouping.name === 'vertex' ? vertex.getProperty(grouping.params.group) : undefined;
    var label = grouping.name === 'vertex' ? Object(string["d" /* stringToWords */])(grouping.params.group) : 'Vertex';
    var ids = column ? column.toArray({ array: Uint32Array }) : Object(array["fillSerial"])(new Uint32Array(rowCount));
    var maxId = column ? Object(array["arrayMax"])(ids) : rowCount - 1; // assumes uint ids
    var map = new Uint32Array(maxId + 1);
    for (var i = 0, il = ids.length; i < il; ++i)
        map[ids[i]] = i;
    return { ids: ids, map: map, label: label };
}
function getColoring(vertex, material, props) {
    var coloring = props.coloring;
    var rowCount = vertex.rowCount;
    var red, green, blue;
    if (coloring.name === 'vertex') {
        red = vertex.getProperty(coloring.params.red) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
        green = vertex.getProperty(coloring.params.green) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
        blue = vertex.getProperty(coloring.params.blue) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
    }
    else if (coloring.name === 'material') {
        red = (material && material.getProperty(coloring.params.red)) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
        green = (material && material.getProperty(coloring.params.green)) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
        blue = (material && material.getProperty(coloring.params.blue)) || mol_data_db["Column"].ofConst(127, rowCount, ply_int);
    }
    else {
        var _a = color["Color"].toRgb(coloring.params.color), r = _a[0], g = _a[1], b = _a[2];
        red = mol_data_db["Column"].ofConst(r, rowCount, ply_int);
        green = mol_data_db["Column"].ofConst(g, rowCount, ply_int);
        blue = mol_data_db["Column"].ofConst(b, rowCount, ply_int);
    }
    return { kind: coloring.name, red: red, green: green, blue: blue };
}
function createShape(plyFile, mesh, coloring, grouping) {
    var kind = coloring.kind, red = coloring.red, green = coloring.green, blue = coloring.blue;
    var ids = grouping.ids, map = grouping.map, label = grouping.label;
    return mol_model_shape["a" /* Shape */].create('ply-mesh', plyFile, mesh, function (groupId) {
        var idx = kind === 'material' ? groupId : map[groupId];
        return color["Color"].fromRgb(red.value(idx), green.value(idx), blue.value(idx));
    }, function () { return 1; }, // size: constant
    function (groupId) {
        return label + " " + ids[groupId];
    });
}
function makeShapeGetter() {
    var _this = this;
    var _plyFile;
    var _props;
    var _shape;
    var _mesh;
    var _coloring;
    var _grouping;
    var getShape = function (ctx, plyFile, props, shape) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var vertex, face, material, newMesh, newColor;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    vertex = plyFile.getElement('vertex');
                    if (!vertex)
                        throw new Error('missing vertex element');
                    face = plyFile.getElement('face');
                    if (!face)
                        throw new Error('missing face element');
                    material = plyFile.getElement('material');
                    newMesh = false;
                    newColor = false;
                    if (!_plyFile || _plyFile !== plyFile) {
                        newMesh = true;
                    }
                    if (!_props || !param_definition["ParamDefinition"].isParamEqual(PlyShapeParams.grouping, _props.grouping, props.grouping)) {
                        newMesh = true;
                    }
                    if (!_props || !param_definition["ParamDefinition"].isParamEqual(PlyShapeParams.coloring, _props.coloring, props.coloring)) {
                        newColor = true;
                    }
                    if (!newMesh) return [3 /*break*/, 2];
                    _coloring = getColoring(vertex, material, props);
                    _grouping = getGrouping(vertex, props);
                    return [4 /*yield*/, getMesh(ctx, vertex, face, _grouping.ids, shape && shape.geometry)];
                case 1:
                    _mesh = _a.sent();
                    _shape = createShape(plyFile, _mesh, _coloring, _grouping);
                    return [3 /*break*/, 3];
                case 2:
                    if (newColor) {
                        _coloring = getColoring(vertex, material, props);
                        _shape = createShape(plyFile, _mesh, _coloring, _grouping);
                    }
                    _a.label = 3;
                case 3:
                    _plyFile = plyFile;
                    _props = Object(object["b" /* deepClone */])(props);
                    return [2 /*return*/, _shape];
            }
        });
    }); };
    return getShape;
}
function shapeFromPly(source, params) {
    var _this = this;
    return mol_task["b" /* Task */].create('Shape Provider', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, {
                    label: 'Mesh',
                    data: source,
                    params: createPlyShapeParams(source),
                    getShape: makeShapeGetter(),
                    geometryUtils: mesh_mesh["a" /* Mesh */].Utils
                }];
        });
    }); });
}
//# sourceMappingURL=ply.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/schema.js
var basic_schema = __webpack_require__(93);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/common/entity.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var entity_EntityBuilder = /** @class */ (function () {
    function EntityBuilder() {
        this.count = 0;
        this.ids = [];
        this.types = [];
        this.descriptions = [];
        this.compoundsMap = new Map();
        this.namesMap = new Map();
        this.heteroMap = new Map();
        this.chainMap = new Map();
    }
    EntityBuilder.prototype.set = function (type, description) {
        this.count += 1;
        this.ids.push("" + this.count);
        this.types.push(type);
        this.descriptions.push([description]);
    };
    EntityBuilder.prototype.getEntityId = function (compId, moleculeType, chainId) {
        if (moleculeType === 2 /* Water */) {
            if (this.waterId === undefined) {
                this.set('water', 'Water');
                this.waterId = "" + this.count;
            }
            return this.waterId;
        }
        else if (Object(types["isPolymer"])(moleculeType)) {
            if (this.compoundsMap.has(chainId)) {
                return this.compoundsMap.get(chainId);
            }
            else {
                if (!this.chainMap.has(chainId)) {
                    this.set('polymer', "Polymer " + (this.chainMap.size + 1));
                    this.chainMap.set(chainId, "" + this.count);
                }
                return this.chainMap.get(chainId);
            }
        }
        else {
            if (!this.heteroMap.has(compId)) {
                this.set('non-polymer', this.namesMap.get(compId) || compId);
                this.heteroMap.set(compId, "" + this.count);
            }
            return this.heteroMap.get(compId);
        }
    };
    EntityBuilder.prototype.getEntityTable = function () {
        return mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].entity, {
            id: mol_data_db["Column"].ofStringArray(this.ids),
            type: mol_data_db["Column"].ofStringAliasArray(this.types),
            pdbx_description: mol_data_db["Column"].ofStringListArray(this.descriptions),
        }, this.count);
    };
    EntityBuilder.prototype.setCompounds = function (compounds) {
        for (var i = 0, il = compounds.length; i < il; ++i) {
            var _a = compounds[i], chains = _a.chains, description = _a.description;
            this.set('polymer', description);
            for (var j = 0, jl = chains.length; j < jl; ++j) {
                this.compoundsMap.set(chains[j], "" + this.count);
            }
        }
    };
    EntityBuilder.prototype.setNames = function (names) {
        var _this = this;
        names.forEach(function (n) { return _this.namesMap.set(n[0], n[1]); });
    };
    return EntityBuilder;
}());

//# sourceMappingURL=entity.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/parser.js + 13 modules
var parser = __webpack_require__(154);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/3dg.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







function getBasic(table) {
    var entityIds = new Array(table._rowCount);
    var entityBuilder = new entity_EntityBuilder();
    var seqIdStarts = table.position.toArray({ array: Uint32Array });
    var seqIdEnds = new Uint32Array(table._rowCount);
    var stride = seqIdStarts[1] - seqIdStarts[0];
    var objectRadius = stride / 3500;
    for (var i = 0, il = table._rowCount; i < il; ++i) {
        var chr = table.chromosome.value(i);
        var entityId = entityBuilder.getEntityId(chr, 7 /* DNA */, chr);
        entityIds[i] = entityId;
        seqIdEnds[i] = seqIdStarts[i] + stride - 1;
    }
    var ihm_sphere_obj_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].ihm_sphere_obj_site, {
        id: mol_data_db["Column"].ofIntArray(Object(array["fillSerial"])(new Uint32Array(table._rowCount))),
        entity_id: mol_data_db["Column"].ofStringArray(entityIds),
        seq_id_begin: mol_data_db["Column"].ofIntArray(seqIdStarts),
        seq_id_end: mol_data_db["Column"].ofIntArray(seqIdEnds),
        asym_id: table.chromosome,
        Cartn_x: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(table.x, function (x) { return x * 10; }, Float32Array)),
        Cartn_y: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(table.y, function (y) { return y * 10; }, Float32Array)),
        Cartn_z: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(table.z, function (z) { return z * 10; }, Float32Array)),
        object_radius: mol_data_db["Column"].ofConst(objectRadius, table._rowCount, mol_data_db["Column"].Schema.float),
        rmsf: mol_data_db["Column"].ofConst(0, table._rowCount, mol_data_db["Column"].Schema.float),
        model_id: mol_data_db["Column"].ofConst(1, table._rowCount, mol_data_db["Column"].Schema.int),
    }, table._rowCount);
    return Object(basic_schema["b" /* createBasic */])({
        entity: entityBuilder.getEntityTable(),
        ihm_model_list: mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].ihm_model_list, {
            model_id: mol_data_db["Column"].ofIntArray([1]),
            model_name: mol_data_db["Column"].ofStringArray(['3DG Model']),
        }, 1),
        ihm_sphere_obj_site: ihm_sphere_obj_site
    });
}
//

var Format3dg;
(function (Format3dg) {
    function is(x) {
        return x.kind === '3dg';
    }
    Format3dg.is = is;
    function from3dg(file3dg) {
        return { kind: '3dg', name: '3DG', data: file3dg };
    }
    Format3dg.from3dg = from3dg;
})(Format3dg || (Format3dg = {}));
function trajectoryFrom3DG(file3dg) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse 3DG', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var format, basic;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            format = Format3dg.from3dg(file3dg);
            basic = getBasic(file3dg.table);
            return [2 /*return*/, Object(parser["a" /* createModels */])(basic, format, ctx)];
        });
    }); });
}
//# sourceMappingURL=3dg.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/coordinates.js + 1 modules
var structure_coordinates = __webpack_require__(165);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/dcd.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var charmmTimeUnitFactor = 20.45482949774598;
function coordinatesFromDcd(dcdFile) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse DCD', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var header, deltaTime, offsetTime, frames, i, il;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, ctx.update('Converting to coordinates')];
                case 1:
                    _a.sent();
                    header = dcdFile.header;
                    deltaTime = Object(structure_coordinates["b" /* Time */])(1, 'step');
                    if (header.DELTA) {
                        deltaTime = Object(structure_coordinates["b" /* Time */])(header.DELTA * charmmTimeUnitFactor, 'ps');
                    }
                    offsetTime = Object(structure_coordinates["b" /* Time */])(0, deltaTime.unit);
                    if (header.ISTART >= 1) {
                        offsetTime = Object(structure_coordinates["b" /* Time */])((header.ISTART - 1) * deltaTime.value, deltaTime.unit);
                    }
                    frames = [];
                    for (i = 0, il = dcdFile.frames.length; i < il; ++i) {
                        frames.push(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, dcdFile.frames[i]), { time: Object(structure_coordinates["b" /* Time */])(offsetTime.value + deltaTime.value * i, deltaTime.unit) }));
                    }
                    return [2 /*return*/, structure_coordinates["a" /* Coordinates */].create(frames, deltaTime, offsetTime)];
            }
        });
    }); });
}
//# sourceMappingURL=dcd.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/util.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

function guessElementSymbolTokens(tokens, str, start, end) {
    var s = start, e = end - 1;
    // trim spaces and numbers
    var c = str.charCodeAt(s);
    while ((c === 32 || (c >= 48 && c <= 57)) && s <= e)
        c = str.charCodeAt(++s);
    c = str.charCodeAt(e);
    while ((c === 32 || (c >= 48 && c <= 57)) && e >= s)
        c = str.charCodeAt(--e);
    ++e;
    if (s === e)
        return text_tokenizer["a" /* TokenBuilder */].add(tokens, s, e); // empty
    if (s + 1 === e)
        return text_tokenizer["a" /* TokenBuilder */].add(tokens, s, e); // one char
    c = str.charCodeAt(s);
    if (s + 2 === e) { // two chars
        var c2 = str.charCodeAt(s + 1);
        if (((c === 78 || c === 110) && (c2 === 65 || c2 === 97)) || // NA na Na nA
            ((c === 67 || c === 99) && (c2 === 76 || c2 === 108)) || // CL
            ((c === 70 || c === 102) && (c2 === 69 || c2 === 101)) || // FE
            ((c === 83 || c === 115) && (c2 === 73 || c2 === 105)) // SI
        )
            return text_tokenizer["a" /* TokenBuilder */].add(tokens, s, s + 2);
    }
    if (c === 67 || c === 99 || // C c
        c === 72 || c === 104 || // H h
        c === 78 || c === 110 || // N n
        c === 79 || c === 111 || // O o
        c === 80 || c === 112 || // P p
        c === 83 || c === 115 // S s
    )
        return text_tokenizer["a" /* TokenBuilder */].add(tokens, s, s + 1);
    text_tokenizer["a" /* TokenBuilder */].add(tokens, s, s); // no reasonable guess, add empty token
}
var reTrimSpacesAndNumbers = /^[\s\d]+|[\s\d]+$/g;
function guessElementSymbolString(str) {
    // trim spaces and numbers, convert to upper case
    str = str.replace(reTrimSpacesAndNumbers, '').toUpperCase();
    var l = str.length;
    if (l === 0)
        return str; // empty
    if (l === 1)
        return str; // one char
    if (l === 2) { // two chars
        if (str === 'NA' || str === 'CL' || str === 'FE' || str === 'SI')
            return str;
    }
    var c = str[0];
    if (c === 'C' || c === 'H' || c === 'N' || c === 'O' || c === 'P' || c === 'S')
        return c;
    return ''; // no reasonable guess, return empty string
}
//# sourceMappingURL=util.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var set = __webpack_require__(90);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/common/component.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var ProteinAtomIdsList = [
    new Set(['CA']),
    new Set(['C']),
    new Set(['N'])
];
var RnaAtomIdsList = [
    new Set(['P', 'O3\'', 'O3*']),
    new Set(['C4\'', 'C4*']),
    new Set(['O2\'', 'O2*', 'F2\'', 'F2*'])
];
var DnaAtomIdsList = [
    new Set(['P', 'O3\'', 'O3*']),
    new Set(['C3\'', 'C3*']),
    new Set(['O2\'', 'O2*', 'F2\'', 'F2*'])
];
var StandardComponents = (function () {
    var map = new Map();
    var components = [
        { id: 'HIS', name: 'HISTIDINE', type: 'L-peptide linking' },
        { id: 'ARG', name: 'ARGININE', type: 'L-peptide linking' },
        { id: 'LYS', name: 'LYSINE', type: 'L-peptide linking' },
        { id: 'ILE', name: 'ISOLEUCINE', type: 'L-peptide linking' },
        { id: 'PHE', name: 'PHENYLALANINE', type: 'L-peptide linking' },
        { id: 'LEU', name: 'LEUCINE', type: 'L-peptide linking' },
        { id: 'TRP', name: 'TRYPTOPHAN', type: 'L-peptide linking' },
        { id: 'ALA', name: 'ALANINE', type: 'L-peptide linking' },
        { id: 'MET', name: 'METHIONINE', type: 'L-peptide linking' },
        { id: 'CYS', name: 'CYSTEINE', type: 'L-peptide linking' },
        { id: 'ASN', name: 'ASPARAGINE', type: 'L-peptide linking' },
        { id: 'VAL', name: 'VALINE', type: 'L-peptide linking' },
        { id: 'GLY', name: 'GLYCINE', type: 'peptide linking' },
        { id: 'SER', name: 'SERINE', type: 'L-peptide linking' },
        { id: 'GLN', name: 'GLUTAMINE', type: 'L-peptide linking' },
        { id: 'TYR', name: 'TYROSINE', type: 'L-peptide linking' },
        { id: 'ASP', name: 'ASPARTIC ACID', type: 'L-peptide linking' },
        { id: 'GLU', name: 'GLUTAMIC ACID', type: 'L-peptide linking' },
        { id: 'THR', name: 'THREONINE', type: 'L-peptide linking' },
        { id: 'SEC', name: 'SELENOCYSTEINE', type: 'L-peptide linking' },
        { id: 'PYL', name: 'PYRROLYSINE', type: 'L-peptide linking' },
        { id: 'A', name: 'ADENOSINE-5\'-MONOPHOSPHATE', type: 'RNA linking' },
        { id: 'C', name: 'CYTIDINE-5\'-MONOPHOSPHATE', type: 'RNA linking' },
        { id: 'T', name: 'THYMIDINE-5\'-MONOPHOSPHATE', type: 'RNA linking' },
        { id: 'G', name: 'GUANOSINE-5\'-MONOPHOSPHATE', type: 'RNA linking' },
        { id: 'I', name: 'INOSINIC ACID', type: 'RNA linking' },
        { id: 'U', name: 'URIDINE-5\'-MONOPHOSPHATE', type: 'RNA linking' },
        { id: 'DA', name: '2\'-DEOXYADENOSINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
        { id: 'DC', name: '2\'-DEOXYCYTIDINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
        { id: 'DT', name: 'THYMIDINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
        { id: 'DG', name: '2\'-DEOXYGUANOSINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
        { id: 'DI', name: '2\'-DEOXYINOSINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
        { id: 'DU', name: '2\'-DEOXYURIDINE-5\'-MONOPHOSPHATE', type: 'DNA linking' },
    ];
    components.forEach(function (c) { return map.set(c.id, c); });
    return map;
})();
var CharmmIonComponents = (function () {
    var map = new Map();
    var components = [
        { id: 'ZN2', name: 'ZINC ION', type: 'Ion' },
        { id: 'SOD', name: 'SODIUM ION', type: 'Ion' },
        { id: 'CES', name: 'CESIUM ION', type: 'Ion' },
        { id: 'CLA', name: 'CHLORIDE ION', type: 'Ion' },
        { id: 'CAL', name: 'CALCIUM ION', type: 'Ion' },
        { id: 'POT', name: 'POTASSIUM ION', type: 'Ion' },
    ];
    components.forEach(function (c) { return map.set(c.id, c); });
    return map;
})();
var component_ComponentBuilder = /** @class */ (function () {
    function ComponentBuilder(seqId, atomId) {
        this.seqId = seqId;
        this.atomId = atomId;
        this.namesMap = new Map();
        this.comps = new Map();
        this.ids = [];
        this.names = [];
        this.types = [];
        this.mon_nstd_flags = [];
    }
    ComponentBuilder.prototype.set = function (c) {
        this.comps.set(c.id, c);
        this.ids.push(c.id);
        this.names.push(c.name);
        this.types.push(c.type);
        this.mon_nstd_flags.push(types["PolymerNames"].has(c.id) ? 'y' : 'n');
    };
    ComponentBuilder.prototype.getAtomIds = function (index) {
        var atomIds = new Set();
        var prevSeqId = this.seqId.value(index);
        while (index < this.seqId.rowCount) {
            var seqId = this.seqId.value(index);
            if (seqId !== prevSeqId)
                break;
            atomIds.add(this.atomId.value(index));
            prevSeqId - seqId;
            index += 1;
        }
        return atomIds;
    };
    ComponentBuilder.prototype.hasAtomIds = function (atomIds, atomIdsList) {
        for (var i = 0, il = atomIdsList.length; i < il; ++i) {
            if (!set["a" /* SetUtils */].areIntersecting(atomIds, atomIdsList[i])) {
                return false;
            }
        }
        return true;
    };
    ComponentBuilder.prototype.getType = function (atomIds) {
        if (this.hasAtomIds(atomIds, ProteinAtomIdsList)) {
            return 'peptide linking';
        }
        else if (this.hasAtomIds(atomIds, RnaAtomIdsList)) {
            return 'RNA linking';
        }
        else if (this.hasAtomIds(atomIds, DnaAtomIdsList)) {
            return 'DNA linking';
        }
        else {
            return 'other';
        }
    };
    ComponentBuilder.prototype.has = function (compId) { return this.comps.has(compId); };
    ComponentBuilder.prototype.get = function (compId) { return this.comps.get(compId); };
    ComponentBuilder.prototype.add = function (compId, index) {
        if (!this.has(compId)) {
            if (StandardComponents.has(compId)) {
                this.set(StandardComponents.get(compId));
            }
            else if (types["WaterNames"].has(compId)) {
                this.set({ id: compId, name: 'WATER', type: 'non-polymer' });
            }
            else {
                var atomIds = this.getAtomIds(index);
                if (CharmmIonComponents.has(compId) && atomIds.size === 1) {
                    this.set(CharmmIonComponents.get(compId));
                }
                else {
                    var type = this.getType(atomIds);
                    this.set({ id: compId, name: this.namesMap.get(compId) || compId, type: type });
                }
            }
        }
        return this.get(compId);
    };
    ComponentBuilder.prototype.getChemCompTable = function () {
        return mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].chem_comp, {
            id: mol_data_db["Column"].ofStringArray(this.ids),
            name: mol_data_db["Column"].ofStringArray(this.names),
            type: mol_data_db["Column"].ofStringAliasArray(this.types),
            mon_nstd_flag: mol_data_db["Column"].ofStringAliasArray(this.mon_nstd_flags),
        }, this.ids.length);
    };
    ComponentBuilder.prototype.setNames = function (names) {
        var _this = this;
        names.forEach(function (n) { return _this.namesMap.set(n[0], n[1]); });
    };
    return ComponentBuilder;
}());

//# sourceMappingURL=component.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/memoize.js
var memoize = __webpack_require__(155);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/common/util.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var ChainIdAlphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
function _getChainId(index) {
    var n = ChainIdAlphabet.length;
    var j = index;
    var k = 0;
    var chainId = ChainIdAlphabet[j % n];
    while (j >= n) {
        j = Math.floor(j / n);
        chainId += ChainIdAlphabet[j % n];
        k += 1;
    }
    if (k >= 5) {
        console.warn('getChainId overflow');
    }
    return chainId;
}
var getChainId = Object(memoize["a" /* memoize1 */])(_getChainId);
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/gro.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










function gro_getBasic(atoms, modelNum) {
    var auth_atom_id = atoms.atomName;
    var auth_comp_id = atoms.residueName;
    var entityIds = new Array(atoms.count);
    var asymIds = new Array(atoms.count);
    var seqIds = new Uint32Array(atoms.count);
    var ids = new Uint32Array(atoms.count);
    var entityBuilder = new entity_EntityBuilder();
    var componentBuilder = new component_ComponentBuilder(atoms.residueNumber, atoms.atomName);
    var currentEntityId = '';
    var currentAsymIndex = 0;
    var currentAsymId = '';
    var currentSeqId = 0;
    var prevMoleculeType = 0 /* Unknown */;
    var prevResidueNumber = -1;
    for (var i = 0, il = atoms.count; i < il; ++i) {
        var residueNumber = atoms.residueNumber.value(i);
        if (residueNumber !== prevResidueNumber) {
            var compId = atoms.residueName.value(i);
            var moleculeType = Object(types["getMoleculeType"])(componentBuilder.add(compId, i).type, compId);
            if (moleculeType !== prevMoleculeType || (residueNumber !== prevResidueNumber + 1 && !(
            // gro format allows only for 5 character residueNumbers, handle overflow here
            prevResidueNumber === 99999 && residueNumber === 0))) {
                currentAsymId = getChainId(currentAsymIndex);
                currentAsymIndex += 1;
                currentSeqId = 0;
            }
            currentEntityId = entityBuilder.getEntityId(compId, moleculeType, currentAsymId);
            currentSeqId += 1;
            prevResidueNumber = residueNumber;
            prevMoleculeType = moleculeType;
        }
        entityIds[i] = currentEntityId;
        asymIds[i] = currentAsymId;
        seqIds[i] = currentSeqId;
        ids[i] = i;
    }
    var auth_asym_id = mol_data_db["Column"].ofStringArray(asymIds);
    var atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
        auth_asym_id: auth_asym_id,
        auth_atom_id: auth_atom_id,
        auth_comp_id: auth_comp_id,
        auth_seq_id: atoms.residueNumber,
        Cartn_x: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(atoms.x, function (x) { return x * 10; }, Float32Array)),
        Cartn_y: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(atoms.y, function (y) { return y * 10; }, Float32Array)),
        Cartn_z: mol_data_db["Column"].ofFloatArray(mol_data_db["Column"].mapToArray(atoms.z, function (z) { return z * 10; }, Float32Array)),
        id: mol_data_db["Column"].ofIntArray(ids),
        label_asym_id: auth_asym_id,
        label_atom_id: auth_atom_id,
        label_comp_id: auth_comp_id,
        label_seq_id: mol_data_db["Column"].ofIntArray(seqIds),
        label_entity_id: mol_data_db["Column"].ofStringArray(entityIds),
        occupancy: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.float),
        type_symbol: mol_data_db["Column"].ofStringArray(mol_data_db["Column"].mapToArray(atoms.atomName, function (s) { return guessElementSymbolString(s); })),
        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(modelNum, atoms.count, mol_data_db["Column"].Schema.int),
    }, atoms.count);
    return Object(basic_schema["b" /* createBasic */])({
        entity: entityBuilder.getEntityTable(),
        chem_comp: componentBuilder.getChemCompTable(),
        atom_site: atom_site
    });
}
//

var GroFormat;
(function (GroFormat) {
    function is(x) {
        return x.kind === 'gro';
    }
    GroFormat.is = is;
    function fromGro(gro) {
        return { kind: 'gro', name: gro.structures[0].header.title, data: gro };
    }
    GroFormat.fromGro = fromGro;
})(GroFormat || (GroFormat = {}));
// TODO reuse static model parts when hierarchy is identical
//      need to pass all gro.structures as one table into createModels
function trajectoryFromGRO(gro) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse GRO', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var format, models, i, il, basic, m;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = GroFormat.fromGro(gro);
                    models = [];
                    i = 0, il = gro.structures.length;
                    _a.label = 1;
                case 1:
                    if (!(i < il)) return [3 /*break*/, 4];
                    basic = gro_getBasic(gro.structures[i].atoms, i + 1);
                    return [4 /*yield*/, Object(parser["a" /* createModels */])(basic, format, ctx)];
                case 2:
                    m = _a.sent();
                    if (m.length === 1)
                        models.push(m[0]);
                    _a.label = 3;
                case 3:
                    ++i;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/, models];
            }
        });
    }); });
}
//# sourceMappingURL=gro.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif.js + 8 modules
var reader_cif = __webpack_require__(31);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/assembly.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function parseCryst1(id, record) {
    // COLUMNS       DATA TYPE      CONTENTS
    // --------------------------------------------------------------------------------
    //  1 -  6       Record name    "CRYST1"
    //  7 - 15       Real(9.3)      a (Angstroms)
    // 16 - 24       Real(9.3)      b (Angstroms)
    // 25 - 33       Real(9.3)      c (Angstroms)
    // 34 - 40       Real(7.2)      alpha (degrees)
    // 41 - 47       Real(7.2)      beta (degrees)
    // 48 - 54       Real(7.2)      gamma (degrees)
    // 56 - 66       LString        Space group
    // 67 - 70       Integer        Z value
    var get = function (s, l) { return (record.substr(s, l) || '').trim(); };
    var cell = {
        entry_id: reader_cif["c" /* CifField */].ofString(id),
        length_a: reader_cif["c" /* CifField */].ofString(get(6, 9)),
        length_b: reader_cif["c" /* CifField */].ofString(get(15, 9)),
        length_c: reader_cif["c" /* CifField */].ofString(get(24, 9)),
        angle_alpha: reader_cif["c" /* CifField */].ofString(get(33, 7)),
        angle_beta: reader_cif["c" /* CifField */].ofString(get(40, 7)),
        angle_gamma: reader_cif["c" /* CifField */].ofString(get(47, 7)),
        Z_PDB: reader_cif["c" /* CifField */].ofString(get(66, 4)),
        pdbx_unique_axis: reader_cif["c" /* CifField */].ofString('?')
    };
    var symmetry = {
        entry_id: reader_cif["c" /* CifField */].ofString(id),
        'space_group_name_H-M': reader_cif["c" /* CifField */].ofString(get(55, 11)),
        Int_Tables_number: reader_cif["c" /* CifField */].ofString('?'),
        cell_setting: reader_cif["c" /* CifField */].ofString('?'),
        space_group_name_Hall: reader_cif["c" /* CifField */].ofString('?')
    };
    return [reader_cif["b" /* CifCategory */].ofFields('cell', cell), reader_cif["b" /* CifCategory */].ofFields('symmetry', symmetry)];
}
function PdbAssembly(id, details) {
    return { id: id, details: details, groups: [] };
}
function parseRemark350(lines, lineStart, lineEnd) {
    var assemblies = [];
    // Read the assemblies
    var current, group, matrix, operId = 1, asmId = 1;
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        if (line.substr(11, 12) === 'BIOMOLECULE:') {
            var id = line.substr(23).trim();
            var details = "Biomolecule " + id;
            line = getLine(i + 1);
            if (line.substr(11, 30) !== 'APPLY THE FOLLOWING TO CHAINS:') {
                i++;
                details = line.substr(11).trim();
            }
            current = PdbAssembly(id, details);
            assemblies.push(current);
        }
        else if (line.substr(13, 5) === 'BIOMT') {
            var biomt = line.split(/\s+/);
            var row = parseInt(line[18]) - 1;
            if (row === 0) {
                matrix = linear_algebra["Mat4"].identity();
                group.operators.push({ id: operId++, matrix: matrix });
            }
            linear_algebra["Mat4"].setValue(matrix, row, 0, parseFloat(biomt[4]));
            linear_algebra["Mat4"].setValue(matrix, row, 1, parseFloat(biomt[5]));
            linear_algebra["Mat4"].setValue(matrix, row, 2, parseFloat(biomt[6]));
            linear_algebra["Mat4"].setValue(matrix, row, 3, parseFloat(biomt[7]));
        }
        else if (line.substr(11, 30) === 'APPLY THE FOLLOWING TO CHAINS:' ||
            line.substr(11, 30) === '                   AND CHAINS:') {
            if (line.substr(11, 5) === 'APPLY') {
                group = { chains: [], operators: [] };
                current.groups.push(group);
            }
            var chainList = line.substr(41, 30).split(',');
            for (var j = 0, jl = chainList.length; j < jl; ++j) {
                var c = chainList[j].trim();
                if (c)
                    group.chains.push(c);
            }
        }
        else if (line.substr(11, 33) === 'APPLYING THE FOLLOWING TO CHAINS:') {
            // variant in older PDB format version
            current = PdbAssembly("" + asmId, "Biomolecule " + asmId);
            assemblies.push(current);
            asmId += 1;
            group = { chains: [], operators: [] };
            current.groups.push(group);
            i++;
            line = getLine(i);
            var chainList = line.substr(11, 69).split(',');
            for (var j = 0, jl = chainList.length; j < jl; ++j) {
                var c = chainList[j].trim();
                if (c)
                    group.chains.push(c);
            }
        }
    }
    if (assemblies.length === 0)
        return [];
    // Generate CIF
    // pdbx_struct_assembly
    var pdbx_struct_assembly = {
        id: reader_cif["c" /* CifField */].ofStrings(assemblies.map(function (a) { return a.id; })),
        details: reader_cif["c" /* CifField */].ofStrings(assemblies.map(function (a) { return a.details; }))
    };
    // pdbx_struct_assembly_gen
    var pdbx_struct_assembly_gen_rows = [];
    for (var _i = 0, assemblies_1 = assemblies; _i < assemblies_1.length; _i++) {
        var asm = assemblies_1[_i];
        for (var _a = 0, _b = asm.groups; _a < _b.length; _a++) {
            var group_1 = _b[_a];
            pdbx_struct_assembly_gen_rows.push({
                assembly_id: asm.id,
                oper_expression: group_1.operators.map(function (o) { return o.id; }).join(','),
                asym_id_list: group_1.chains.join(',')
            });
        }
    }
    var pdbx_struct_assembly_gen = {
        assembly_id: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_assembly_gen_rows.map(function (r) { return r.assembly_id; })),
        oper_expression: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_assembly_gen_rows.map(function (r) { return r.oper_expression; })),
        asym_id_list: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_assembly_gen_rows.map(function (r) { return r.asym_id_list; }))
    };
    // pdbx_struct_oper_list
    var pdbx_struct_oper_list_rows = [];
    for (var _c = 0, assemblies_2 = assemblies; _c < assemblies_2.length; _c++) {
        var asm = assemblies_2[_c];
        for (var _d = 0, _e = asm.groups; _d < _e.length; _d++) {
            var group_2 = _e[_d];
            for (var _f = 0, _g = group_2.operators; _f < _g.length; _f++) {
                var oper = _g[_f];
                var row = {
                    id: '' + oper.id,
                    type: '?',
                    name: '?',
                    symmetry_operation: '?'
                };
                for (var i = 0; i < 3; i++) {
                    for (var j = 0; j < 3; j++) {
                        row["matrix[" + (i + 1) + "][" + (j + 1) + "]"] = '' + linear_algebra["Mat4"].getValue(oper.matrix, i, j);
                    }
                    row["vector[" + (i + 1) + "]"] = '' + linear_algebra["Mat4"].getValue(oper.matrix, i, 3);
                }
                pdbx_struct_oper_list_rows.push(row);
            }
        }
    }
    var pdbx_struct_oper_list = {
        id: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r.id; })),
        type: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r.type; })),
        name: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r.name; })),
        symmetry_operation: reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r.symmetry_operation; }))
    };
    var _loop_1 = function (i) {
        var _loop_2 = function (j) {
            var k_1 = "matrix[" + (i + 1) + "][" + (j + 1) + "]";
            pdbx_struct_oper_list[k_1] = reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r[k_1]; }));
        };
        for (var j = 0; j < 3; j++) {
            _loop_2(j);
        }
        var k = "vector[" + (i + 1) + "]";
        pdbx_struct_oper_list[k] = reader_cif["c" /* CifField */].ofStrings(pdbx_struct_oper_list_rows.map(function (r) { return r[k]; }));
    };
    for (var i = 0; i < 3; i++) {
        _loop_1(i);
    }
    return [
        reader_cif["b" /* CifCategory */].ofFields('pdbx_struct_assembly', pdbx_struct_assembly),
        reader_cif["b" /* CifCategory */].ofFields('pdbx_struct_assembly_gen', pdbx_struct_assembly_gen),
        reader_cif["b" /* CifCategory */].ofFields('pdbx_struct_oper_list', pdbx_struct_oper_list)
    ];
}
function parseMtrix(lines, lineStart, lineEnd) {
    var matrices = [];
    var matrix;
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        var ncs = line.split(/\s+/);
        var row = parseInt(line[5]) - 1;
        if (row === 0) {
            matrix = linear_algebra["Mat4"].identity();
            matrices.push(matrix);
        }
        linear_algebra["Mat4"].setValue(matrix, row, 0, parseFloat(ncs[2]));
        linear_algebra["Mat4"].setValue(matrix, row, 1, parseFloat(ncs[3]));
        linear_algebra["Mat4"].setValue(matrix, row, 2, parseFloat(ncs[4]));
        linear_algebra["Mat4"].setValue(matrix, row, 3, parseFloat(ncs[5]));
    }
    if (matrices.length === 0)
        return [];
    var struct_ncs_oper_rows = [];
    var id = 1;
    for (var _i = 0, matrices_1 = matrices; _i < matrices_1.length; _i++) {
        var oper = matrices_1[_i];
        var row = {
            id: 'ncsop' + (id++),
            code: '.',
            details: '.'
        };
        for (var i = 0; i < 3; i++) {
            for (var j = 0; j < 3; j++) {
                row["matrix[" + (i + 1) + "][" + (j + 1) + "]"] = '' + linear_algebra["Mat4"].getValue(oper, i, j);
            }
            row["vector[" + (i + 1) + "]"] = '' + linear_algebra["Mat4"].getValue(oper, i, 3);
        }
        struct_ncs_oper_rows.push(row);
    }
    var struct_ncs_oper = {
        id: reader_cif["c" /* CifField */].ofStrings(struct_ncs_oper_rows.map(function (r) { return r.id; })),
        code: reader_cif["c" /* CifField */].ofStrings(struct_ncs_oper_rows.map(function (r) { return r.code; })),
        details: reader_cif["c" /* CifField */].ofStrings(struct_ncs_oper_rows.map(function (r) { return r.details; })),
    };
    var _loop_3 = function (i) {
        var _loop_4 = function (j) {
            var k_2 = "matrix[" + (i + 1) + "][" + (j + 1) + "]";
            struct_ncs_oper[k_2] = reader_cif["c" /* CifField */].ofStrings(struct_ncs_oper_rows.map(function (r) { return r[k_2]; }));
        };
        for (var j = 0; j < 3; j++) {
            _loop_4(j);
        }
        var k = "vector[" + (i + 1) + "]";
        struct_ncs_oper[k] = reader_cif["c" /* CifField */].ofStrings(struct_ncs_oper_rows.map(function (r) { return r[k]; }));
    };
    for (var i = 0; i < 3; i++) {
        _loop_3(i);
    }
    return [reader_cif["b" /* CifCategory */].ofFields('struct_ncs_oper', struct_ncs_oper)];
}
//# sourceMappingURL=assembly.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/secondary-structure.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var HelixTypes = {
    // CLASS NUMBER
    // TYPE OF  HELIX                     (COLUMNS 39 - 40)
    // --------------------------------------------------------------
    // Right-handed alpha (default)                1
    // Right-handed omega                          2
    // Right-handed pi                             3
    // Right-handed gamma                          4
    // Right-handed 3 - 10                         5
    // Left-handed alpha                           6
    // Left-handed omega                           7
    // Left-handed gamma                           8
    // 2 - 7 ribbon/helix                          9
    // Polyproline                                10
    1: 'HELX_RH_AL_P',
    2: 'HELX_RH_OM_P',
    3: 'HELX_RH_PI_P',
    4: 'HELX_RH_GA_P',
    5: 'HELX_RH_3T_P',
    6: 'HELX_LH_AL_P',
    7: 'HELX_LH_OM_P',
    8: 'HELX_LH_GA_P',
    9: 'HELX_RH_27_P',
    10: 'HELX_RH_PP_P',
};
function getStructConfTypeId(type) {
    return HelixTypes[type] || 'HELX_P';
}
function parseHelix(lines, lineStart, lineEnd) {
    var helices = [];
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        // COLUMNS        DATA  TYPE     FIELD         DEFINITION
        // -----------------------------------------------------------------------------------
        // 1 -  6        Record name    "HELIX "
        // 8 - 10        Integer        serNum        Serial number of the helix. This starts
        //                                             at 1  and increases incrementally.
        // 12 - 14        LString(3)     helixID       Helix  identifier. In addition to a serial
        //                                             number, each helix is given an
        //                                             alphanumeric character helix identifier.
        // 16 - 18        Residue name   initResName   Name of the initial residue.
        // 20             Character      initChainID   Chain identifier for the chain containing
        //                                             this  helix.
        // 22 - 25        Integer        initSeqNum    Sequence number of the initial residue.
        // 26             AChar          initICode     Insertion code of the initial residue.
        // 28 - 30        Residue  name  endResName    Name of the terminal residue of the helix.
        // 32             Character      endChainID    Chain identifier for the chain containing
        //                                             this  helix.
        // 34 - 37        Integer        endSeqNum     Sequence number of the terminal residue.
        // 38             AChar          endICode      Insertion code of the terminal residue.
        // 39 - 40        Integer        helixClass    Helix class (see below).
        // 41 - 70        String         comment       Comment about this helix.
        // 72 - 76        Integer        length        Length of this helix.
        helices.push({
            serNum: line.substr(7, 3).trim(),
            helixID: line.substr(11, 3).trim(),
            initResName: line.substr(15, 3).trim(),
            initChainID: line.substr(19, 1).trim(),
            initSeqNum: line.substr(21, 4).trim(),
            initICode: line.substr(25, 1).trim(),
            endResName: line.substr(27, 3).trim(),
            endChainID: line.substr(31, 3).trim(),
            endSeqNum: line.substr(33, 4).trim(),
            endICode: line.substr(37, 1).trim(),
            helixClass: line.substr(38, 2).trim(),
            comment: line.substr(40, 30).trim(),
            length: line.substr(71, 5).trim()
        });
    }
    var beg_auth_asym_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.initChainID; }));
    var beg_auth_comp_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.initResName; }));
    var beg_auth_seq_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.initSeqNum; }));
    var end_auth_asym_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.endChainID; }));
    var end_auth_comp_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.endResName; }));
    var end_auth_seq_id = reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.endSeqNum; }));
    var struct_conf = {
        beg_label_asym_id: beg_auth_asym_id,
        beg_label_comp_id: beg_auth_comp_id,
        beg_label_seq_id: beg_auth_seq_id,
        beg_auth_asym_id: beg_auth_asym_id,
        beg_auth_comp_id: beg_auth_comp_id,
        beg_auth_seq_id: beg_auth_seq_id,
        conf_type_id: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return getStructConfTypeId(h.helixClass); })),
        details: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.comment; })),
        end_label_asym_id: end_auth_asym_id,
        end_label_comp_id: end_auth_asym_id,
        end_label_seq_id: end_auth_seq_id,
        end_auth_asym_id: end_auth_asym_id,
        end_auth_comp_id: end_auth_comp_id,
        end_auth_seq_id: end_auth_seq_id,
        id: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.serNum; })),
        pdbx_beg_PDB_ins_code: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.initICode; })),
        pdbx_end_PDB_ins_code: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.endICode; })),
        pdbx_PDB_helix_class: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.helixClass; })),
        pdbx_PDB_helix_length: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.length; })),
        pdbx_PDB_helix_id: reader_cif["c" /* CifField */].ofStrings(helices.map(function (h) { return h.helixID; })),
    };
    return reader_cif["b" /* CifCategory */].ofFields('struct_conf', struct_conf);
}
function parseSheet(lines, lineStart, lineEnd) {
    var sheets = [];
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        // COLUMNS       DATA  TYPE     FIELD          DEFINITION
        // -------------------------------------------------------------------------------------
        // 1 -  6        Record name   "SHEET "
        // 8 - 10        Integer       strand         Strand  number which starts at 1 for each
        //                                             strand within a sheet and increases by one.
        // 12 - 14        LString(3)    sheetID        Sheet  identifier.
        // 15 - 16        Integer       numStrands     Number  of strands in sheet.
        // 18 - 20        Residue name  initResName    Residue  name of initial residue.
        // 22             Character     initChainID    Chain identifier of initial residue
        //                                             in strand.
        // 23 - 26        Integer       initSeqNum     Sequence number of initial residue
        //                                             in strand.
        // 27             AChar         initICode      Insertion code of initial residue
        //                                             in  strand.
        // 29 - 31        Residue name  endResName     Residue name of terminal residue.
        // 33             Character     endChainID     Chain identifier of terminal residue.
        // 34 - 37        Integer       endSeqNum      Sequence number of terminal residue.
        // 38             AChar         endICode       Insertion code of terminal residue.
        // 39 - 40        Integer       sense          Sense of strand with respect to previous
        //                                             strand in the sheet. 0 if first strand,
        //                                             1 if  parallel,and -1 if anti-parallel.
        // 42 - 45        Atom          curAtom        Registration.  Atom name in current strand.
        // 46 - 48        Residue name  curResName     Registration.  Residue name in current strand
        // 50             Character     curChainId     Registration. Chain identifier in
        //                                             current strand.
        // 51 - 54        Integer       curResSeq      Registration.  Residue sequence number
        //                                             in current strand.
        // 55             AChar         curICode       Registration. Insertion code in
        //                                             current strand.
        // 57 - 60        Atom          prevAtom       Registration.  Atom name in previous strand.
        // 61 - 63        Residue name  prevResName    Registration.  Residue name in
        //                                             previous strand.
        // 65             Character     prevChainId    Registration.  Chain identifier in
        //                                             previous  strand.
        // 66 - 69        Integer       prevResSeq     Registration. Residue sequence number
        //                                             in previous strand.
        // 70             AChar         prevICode      Registration.  Insertion code in
        //                                             previous strand.
        sheets.push({
            strand: line.substr(7, 3).trim(),
            sheetID: line.substr(11, 3).trim(),
            numStrands: line.substr(14, 2).trim(),
            initResName: line.substr(17, 3).trim(),
            initChainID: line.substr(21, 1).trim(),
            initSeqNum: line.substr(22, 4).trim(),
            initICode: line.substr(26, 1).trim(),
            endResName: line.substr(28, 3).trim(),
            endChainID: line.substr(32, 1).trim(),
            endSeqNum: line.substr(33, 4).trim(),
            endICode: line.substr(37, 1).trim(),
            sense: line.substr(38, 2).trim(),
            curAtom: line.substr(41, 4).trim(),
            curResName: line.substr(45, 3).trim(),
            curChainId: line.substr(49, 1).trim(),
            curResSeq: line.substr(50, 4).trim(),
            curICode: line.substr(54, 1).trim(),
            prevAtom: line.substr(56, 4).trim(),
            prevResName: line.substr(60, 3).trim(),
            prevChainId: line.substr(64, 1).trim(),
            prevResSeq: line.substr(65, 4).trim(),
            prevICode: line.substr(69, 1).trim(),
        });
    }
    var beg_auth_asym_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.initChainID; }));
    var beg_auth_comp_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.initResName; }));
    var beg_auth_seq_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.initSeqNum; }));
    var end_auth_asym_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.endChainID; }));
    var end_auth_comp_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.endResName; }));
    var end_auth_seq_id = reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.endSeqNum; }));
    var struct_sheet_range = {
        beg_label_asym_id: beg_auth_asym_id,
        beg_label_comp_id: beg_auth_comp_id,
        beg_label_seq_id: beg_auth_seq_id,
        beg_auth_asym_id: beg_auth_asym_id,
        beg_auth_comp_id: beg_auth_comp_id,
        beg_auth_seq_id: beg_auth_seq_id,
        end_label_asym_id: end_auth_asym_id,
        end_label_comp_id: end_auth_asym_id,
        end_label_seq_id: end_auth_seq_id,
        end_auth_asym_id: end_auth_asym_id,
        end_auth_comp_id: end_auth_comp_id,
        end_auth_seq_id: end_auth_seq_id,
        id: reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.strand; })),
        sheet_id: reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.sheetID; })),
        pdbx_beg_PDB_ins_code: reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.initICode; })),
        pdbx_end_PDB_ins_code: reader_cif["c" /* CifField */].ofStrings(sheets.map(function (s) { return s.endICode; })),
    };
    return reader_cif["b" /* CifCategory */].ofFields('struct_sheet_range', struct_sheet_range);
}
//# sourceMappingURL=secondary-structure.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/entity.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var Spec = {
    'MOL_ID': '',
    'MOLECULE': '',
    'CHAIN': '',
    'FRAGMENT': '',
    'SYNONYM': '',
    'EC': '',
    'ENGINEERED': '',
    'MUTATION': '',
    'OTHER_DETAILS': ''
};
function parseCmpnd(lines, lineStart, lineEnd) {
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    var currentSpec;
    var currentCompound = { chains: [], description: '' };
    var Compounds = [];
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        // COLUMNS       DATA TYPE       FIELD         DEFINITION
        // ----------------------------------------------------------------------------------
        //  1 -  6       Record name     "COMPND"
        //  8 - 10       Continuation    continuation  Allows concatenation of multiple records.
        // 11 - 80       Specification   compound      Description of the molecular components.
        //               list
        var cmpnd = line.substr(10, 70).trim();
        var cmpndSpecEnd = cmpnd.indexOf(':');
        var cmpndSpec = cmpnd.substring(0, cmpndSpecEnd);
        var value = void 0;
        if (cmpndSpec in Spec) {
            currentSpec = cmpndSpec;
            value = cmpnd.substring(cmpndSpecEnd + 2);
        }
        else {
            value = cmpnd;
        }
        value = value.replace(/;$/, '');
        if (currentSpec === 'MOL_ID') {
            currentCompound = {
                chains: [],
                description: ''
            };
            Compounds.push(currentCompound);
        }
        else if (currentSpec === 'MOLECULE') {
            if (currentCompound.description)
                currentCompound.description += ' ';
            currentCompound.description += value;
        }
        else if (currentSpec === 'CHAIN') {
            Array.prototype.push.apply(currentCompound.chains, value.split(/\s*,\s*/));
        }
    }
    return Compounds;
}
function parseHetnam(lines, lineStart, lineEnd) {
    var getLine = function (n) { return lines.data.substring(lines.indices[2 * n], lines.indices[2 * n + 1]); };
    var hetnams = new Map();
    for (var i = lineStart; i < lineEnd; i++) {
        var line = getLine(i);
        // COLUMNS       DATA  TYPE    FIELD           DEFINITION
        // ----------------------------------------------------------------------------
        //  1 -  6       Record name   "HETNAM"
        //  9 - 10       Continuation  continuation    Allows concatenation of multiple records.
        // 12 - 14       LString(3)    hetID           Het identifier, right-justified.
        // 16 - 70       String        text            Chemical name.
        var het = line.substr(11, 3).trim();
        var name_1 = line.substr(15).trim();
        if (hetnams.has(het)) {
            hetnams.set(het, hetnams.get(het) + " " + name_1);
        }
        else {
            hetnams.set(het, name_1);
        }
    }
    return hetnams;
}
//# sourceMappingURL=entity.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/atom-site.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



function getAtomSiteTemplate(data, count) {
    var str = function () { return []; };
    var ts = function () { return text_tokenizer["a" /* TokenBuilder */].create(data, 2 * count); };
    return {
        index: 0,
        count: count,
        group_PDB: ts(),
        id: str(),
        auth_atom_id: ts(),
        label_alt_id: ts(),
        auth_comp_id: ts(),
        auth_asym_id: ts(),
        auth_seq_id: ts(),
        pdbx_PDB_ins_code: ts(),
        Cartn_x: ts(),
        Cartn_y: ts(),
        Cartn_z: ts(),
        occupancy: ts(),
        B_iso_or_equiv: ts(),
        type_symbol: ts(),
        pdbx_PDB_model_num: str(),
        label_entity_id: str()
    };
}
function getAtomSite(sites) {
    var auth_asym_id = reader_cif["c" /* CifField */].ofTokens(sites.auth_asym_id);
    var auth_atom_id = reader_cif["c" /* CifField */].ofTokens(sites.auth_atom_id);
    var auth_comp_id = reader_cif["c" /* CifField */].ofTokens(sites.auth_comp_id);
    var auth_seq_id = reader_cif["c" /* CifField */].ofTokens(sites.auth_seq_id);
    return {
        auth_asym_id: auth_asym_id,
        auth_atom_id: auth_atom_id,
        auth_comp_id: auth_comp_id,
        auth_seq_id: auth_seq_id,
        B_iso_or_equiv: reader_cif["c" /* CifField */].ofTokens(sites.B_iso_or_equiv),
        Cartn_x: reader_cif["c" /* CifField */].ofTokens(sites.Cartn_x),
        Cartn_y: reader_cif["c" /* CifField */].ofTokens(sites.Cartn_y),
        Cartn_z: reader_cif["c" /* CifField */].ofTokens(sites.Cartn_z),
        group_PDB: reader_cif["c" /* CifField */].ofTokens(sites.group_PDB),
        id: reader_cif["c" /* CifField */].ofStrings(sites.id),
        label_alt_id: reader_cif["c" /* CifField */].ofTokens(sites.label_alt_id),
        label_asym_id: auth_asym_id,
        label_atom_id: auth_atom_id,
        label_comp_id: auth_comp_id,
        label_seq_id: auth_seq_id,
        label_entity_id: reader_cif["c" /* CifField */].ofStrings(sites.label_entity_id),
        occupancy: reader_cif["c" /* CifField */].ofTokens(sites.occupancy),
        type_symbol: reader_cif["c" /* CifField */].ofTokens(sites.type_symbol),
        pdbx_PDB_ins_code: reader_cif["c" /* CifField */].ofTokens(sites.pdbx_PDB_ins_code),
        pdbx_PDB_model_num: reader_cif["c" /* CifField */].ofStrings(sites.pdbx_PDB_model_num)
    };
}
function addAtom(sites, model, data, s, e) {
    var str = data.data;
    var length = e - s;
    // TODO: filter invalid atoms
    // COLUMNS        DATA TYPE       CONTENTS
    // --------------------------------------------------------------------------------
    // 1 -  6        Record name     "ATOM  "
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.group_PDB, text_tokenizer["b" /* Tokenizer */].trim(data, s, s + 6));
    // 7 - 11        Integer         Atom serial number.
    // TODO: support HEX
    text_tokenizer["b" /* Tokenizer */].trim(data, s + 6, s + 11);
    sites.id[sites.index] = data.data.substring(data.tokenStart, data.tokenEnd);
    // 13 - 16        Atom            Atom name.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.auth_atom_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 12, s + 16));
    // 17             Character       Alternate location indicator.
    if (str.charCodeAt(s + 16) === 32) { // ' '
        text_tokenizer["a" /* TokenBuilder */].add(sites.label_alt_id, 0, 0);
    }
    else {
        text_tokenizer["a" /* TokenBuilder */].add(sites.label_alt_id, s + 16, s + 17);
    }
    // 18 - 20        Residue name    Residue name.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.auth_comp_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 17, s + 20));
    // 22             Character       Chain identifier.
    text_tokenizer["a" /* TokenBuilder */].add(sites.auth_asym_id, s + 21, s + 22);
    // 23 - 26        Integer         Residue sequence number.
    // TODO: support HEX
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.auth_seq_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 22, s + 26));
    // 27             AChar           Code for insertion of residues.
    if (str.charCodeAt(s + 26) === 32) { // ' '
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_PDB_ins_code, 0, 0);
    }
    else {
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_PDB_ins_code, s + 26, s + 27);
    }
    // 31 - 38        Real(8.3)       Orthogonal coordinates for X in Angstroms.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.Cartn_x, text_tokenizer["b" /* Tokenizer */].trim(data, s + 30, s + 38));
    // 39 - 46        Real(8.3)       Orthogonal coordinates for Y in Angstroms.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.Cartn_y, text_tokenizer["b" /* Tokenizer */].trim(data, s + 38, s + 46));
    // 47 - 54        Real(8.3)       Orthogonal coordinates for Z in Angstroms.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.Cartn_z, text_tokenizer["b" /* Tokenizer */].trim(data, s + 46, s + 54));
    // 55 - 60        Real(6.2)       Occupancy.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.occupancy, text_tokenizer["b" /* Tokenizer */].trim(data, s + 54, s + 60));
    // 61 - 66        Real(6.2)       Temperature factor (Default = 0.0).
    if (length >= 66) {
        text_tokenizer["a" /* TokenBuilder */].addToken(sites.B_iso_or_equiv, text_tokenizer["b" /* Tokenizer */].trim(data, s + 60, s + 66));
    }
    else {
        text_tokenizer["a" /* TokenBuilder */].add(sites.B_iso_or_equiv, 0, 0);
    }
    // 73 - 76        LString(4)      Segment identifier, left-justified.
    // ignored
    // 77 - 78        LString(2)      Element symbol, right-justified.
    if (length >= 78) {
        text_tokenizer["b" /* Tokenizer */].trim(data, s + 76, s + 78);
        if (data.tokenStart < data.tokenEnd) {
            text_tokenizer["a" /* TokenBuilder */].addToken(sites.type_symbol, data);
        }
        else {
            guessElementSymbolTokens(sites.type_symbol, str, s + 12, s + 16);
        }
    }
    else {
        guessElementSymbolTokens(sites.type_symbol, str, s + 12, s + 16);
    }
    // 79 - 80        LString(2)    charge       Charge  on the atom.
    // TODO
    sites.pdbx_PDB_model_num[sites.index] = model;
    sites.index++;
}
//# sourceMappingURL=atom-site.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/anisotropic.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function getAnisotropicTemplate(data, count) {
    var str = function () { return []; };
    var float = function () { return new Float32Array(count); };
    var ts = function () { return text_tokenizer["a" /* TokenBuilder */].create(data, 2 * count); };
    return {
        index: 0,
        count: count,
        id: str(),
        type_symbol: ts(),
        pdbx_label_atom_id: ts(),
        pdbx_label_alt_id: ts(),
        pdbx_label_comp_id: ts(),
        pdbx_label_asym_id: ts(),
        pdbx_label_seq_id: ts(),
        pdbx_PDB_ins_code: ts(),
        'U[1][1]': float(),
        'U[2][2]': float(),
        'U[3][3]': float(),
        'U[1][2]': float(),
        'U[1][3]': float(),
        'U[2][3]': float(),
        pdbx_auth_seq_id: ts(),
        pdbx_auth_comp_id: ts(),
        pdbx_auth_asym_id: ts(),
        pdbx_auth_atom_id: ts(),
    };
}
function getAnisotropic(sites) {
    var pdbx_auth_seq_id = reader_cif["c" /* CifField */].ofTokens(sites.pdbx_auth_seq_id);
    var pdbx_auth_comp_id = reader_cif["c" /* CifField */].ofTokens(sites.pdbx_auth_comp_id);
    var pdbx_auth_asym_id = reader_cif["c" /* CifField */].ofTokens(sites.pdbx_auth_asym_id);
    var pdbx_auth_atom_id = reader_cif["c" /* CifField */].ofTokens(sites.pdbx_auth_atom_id);
    var fields = {
        id: reader_cif["c" /* CifField */].ofStrings(sites.id),
        type_symbol: reader_cif["c" /* CifField */].ofTokens(sites.type_symbol),
        pdbx_label_atom_id: pdbx_auth_atom_id,
        pdbx_label_alt_id: reader_cif["c" /* CifField */].ofTokens(sites.pdbx_label_alt_id),
        pdbx_label_comp_id: pdbx_auth_comp_id,
        pdbx_label_asym_id: pdbx_auth_asym_id,
        pdbx_label_seq_id: pdbx_auth_seq_id,
        pdbx_PDB_ins_code: reader_cif["c" /* CifField */].ofTokens(sites.pdbx_PDB_ins_code),
        pdbx_auth_seq_id: pdbx_auth_seq_id,
        pdbx_auth_comp_id: pdbx_auth_comp_id,
        pdbx_auth_asym_id: pdbx_auth_asym_id,
        pdbx_auth_atom_id: pdbx_auth_atom_id,
    };
    fields['U[1][1]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[1][1]']);
    fields['U[2][2]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[2][2]']);
    fields['U[3][3]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[3][3]']);
    fields['U[1][2]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[1][2]']);
    fields['U[1][3]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[1][3]']);
    fields['U[2][3]'] = reader_cif["c" /* CifField */].ofNumbers(sites['U[2][3]']);
    return fields;
}
function addAnisotropic(sites, model, data, s, e) {
    var str = data.data;
    var length = e - s;
    // COLUMNS       DATA  TYPE    FIELD          DEFINITION
    // -----------------------------------------------------------------
    // 1 - 6        Record name   "ANISOU"
    // 7 - 11       Integer       serial         Atom serial number.
    text_tokenizer["b" /* Tokenizer */].trim(data, s + 6, s + 11);
    sites.id[sites.index] = str.substring(data.tokenStart, data.tokenEnd);
    // 13 - 16       Atom          name           Atom name.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.pdbx_auth_atom_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 12, s + 16));
    // 17            Character     altLoc         Alternate location indicator
    if (str.charCodeAt(s + 16) === 32) { // ' '
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_label_alt_id, 0, 0);
    }
    else {
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_label_alt_id, s + 16, s + 17);
    }
    // 18 - 20       Residue name  resName        Residue name.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.pdbx_auth_comp_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 17, s + 20));
    // 22            Character     chainID        Chain identifier.
    text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_auth_asym_id, s + 21, s + 22);
    // 23 - 26       Integer       resSeq         Residue sequence number.
    text_tokenizer["a" /* TokenBuilder */].addToken(sites.pdbx_auth_seq_id, text_tokenizer["b" /* Tokenizer */].trim(data, s + 22, s + 26));
    // 27            AChar         iCode          Insertion code.
    if (str.charCodeAt(s + 26) === 32) { // ' '
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_PDB_ins_code, 0, 0);
    }
    else {
        text_tokenizer["a" /* TokenBuilder */].add(sites.pdbx_PDB_ins_code, s + 26, s + 27);
    }
    // 29 - 35       Integer       u[0][0]        U(1,1)
    sites['U[1][1]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 28, s + 35) / 10000;
    // 36 - 42       Integer       u[1][1]        U(2,2)
    sites['U[2][2]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 35, s + 42) / 10000;
    // 43 - 49       Integer       u[2][2]        U(3,3)
    sites['U[3][3]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 42, s + 49) / 10000;
    // 50 - 56       Integer       u[0][1]        U(1,2)
    sites['U[1][2]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 49, s + 56) / 10000;
    // 57 - 63       Integer       u[0][2]        U(1,3)
    sites['U[1][3]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 56, s + 63) / 10000;
    // 64 - 70       Integer       u[1][2]        U(2,3)
    sites['U[2][3]'][sites.index] = Object(number_parser["e" /* parseIntSkipLeadingWhitespace */])(str, s + 63, s + 70) / 10000;
    // 77 - 78       LString(2)    element        Element symbol, right-justified.
    if (length >= 78) {
        text_tokenizer["b" /* Tokenizer */].trim(data, s + 76, s + 78);
        if (data.tokenStart < data.tokenEnd) {
            text_tokenizer["a" /* TokenBuilder */].addToken(sites.type_symbol, data);
        }
        else {
            guessElementSymbolTokens(sites.type_symbol, str, s + 12, s + 16);
        }
    }
    else {
        guessElementSymbolTokens(sites.type_symbol, str, s + 12, s + 16);
    }
    // 79 - 80       LString(2)    charge         Charge on the atom.
    // TODO
    sites.index++;
}
//# sourceMappingURL=anisotropic.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb/to-cif.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













function pdbToMmCif(pdb) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var lines, data, indices, tokenizer, atomCount, anisotropicCount, i, _i, s, e, atomSite, anisotropic, entityBuilder, helperCategories, heteroNames, modelNum, modelStr, i, _i, s, e, j, j, j, j, j, j, seqIds, atomIds, compIds, asymIds, componentBuilder, i, il, compId, moleculeType, categories, _a, helperCategories_1, c;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            lines = pdb.lines;
            data = lines.data, indices = lines.indices;
            tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
            atomCount = 0;
            anisotropicCount = 0;
            for (i = 0, _i = lines.count; i < _i; i++) {
                s = indices[2 * i], e = indices[2 * i + 1];
                switch (data[s]) {
                    case 'A':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'ATOM  '))
                            atomCount++;
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'ANISOU'))
                            anisotropicCount++;
                        break;
                    case 'H':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'HETATM'))
                            atomCount++;
                        break;
                }
            }
            atomSite = getAtomSiteTemplate(data, atomCount);
            anisotropic = getAnisotropicTemplate(data, anisotropicCount);
            entityBuilder = new entity_EntityBuilder();
            helperCategories = [];
            heteroNames = [];
            modelNum = 0, modelStr = '';
            for (i = 0, _i = lines.count; i < _i; i++) {
                s = indices[2 * i], e = indices[2 * i + 1];
                switch (data[s]) {
                    case 'A':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'ATOM  ')) {
                            if (!modelNum) {
                                modelNum++;
                                modelStr = '' + modelNum;
                            }
                            addAtom(atomSite, modelStr, tokenizer, s, e);
                        }
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'ANISOU')) {
                            addAnisotropic(anisotropic, modelStr, tokenizer, s, e);
                        }
                        break;
                    case 'C':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'CRYST1')) {
                            helperCategories.push.apply(helperCategories, parseCryst1(pdb.id || '?', data.substring(s, e)));
                        }
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'CONNECT')) {
                            // TODO: CONNECT records => struct_conn
                        }
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'COMPND')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'COMPND'))
                                    break;
                                j++;
                            }
                            entityBuilder.setCompounds(parseCmpnd(lines, i, j));
                            i = j - 1;
                        }
                        break;
                    case 'H':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'HETATM')) {
                            if (!modelNum) {
                                modelNum++;
                                modelStr = '' + modelNum;
                            }
                            addAtom(atomSite, modelStr, tokenizer, s, e);
                        }
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'HELIX')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'HELIX'))
                                    break;
                                j++;
                            }
                            helperCategories.push(parseHelix(lines, i, j));
                            i = j - 1;
                        }
                        else if (Object(string["f" /* substringStartsWith */])(data, s, e, 'HETNAM')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'HETNAM'))
                                    break;
                                j++;
                            }
                            heteroNames.push.apply(heteroNames, Array.from(parseHetnam(lines, i, j).entries()));
                            i = j - 1;
                        }
                        break;
                    case 'M':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'MODEL ')) {
                            modelNum++;
                            modelStr = '' + modelNum;
                        }
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'MTRIX')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'MTRIX'))
                                    break;
                                j++;
                            }
                            helperCategories.push.apply(helperCategories, parseMtrix(lines, i, j));
                            i = j - 1;
                        }
                        // TODO: MODRES records => pdbx_struct_mod_residue
                        break;
                    case 'O':
                        // TODO: ORIGX record => cif.database_PDB_matrix.origx, cif.database_PDB_matrix.origx_vector
                        break;
                    case 'R':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'REMARK 350')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'REMARK 350'))
                                    break;
                                j++;
                            }
                            helperCategories.push.apply(helperCategories, parseRemark350(lines, i, j));
                            i = j - 1;
                        }
                        break;
                    case 'S':
                        if (Object(string["f" /* substringStartsWith */])(data, s, e, 'SHEET')) {
                            j = i + 1;
                            while (true) {
                                s = indices[2 * j];
                                e = indices[2 * j + 1];
                                if (!Object(string["f" /* substringStartsWith */])(data, s, e, 'SHEET'))
                                    break;
                                j++;
                            }
                            helperCategories.push(parseSheet(lines, i, j));
                            i = j - 1;
                        }
                        // TODO: SCALE record => cif.atom_sites.fract_transf_matrix, cif.atom_sites.fract_transf_vector
                        break;
                }
            }
            seqIds = mol_data_db["Column"].ofIntTokens(atomSite.auth_seq_id);
            atomIds = mol_data_db["Column"].ofStringTokens(atomSite.auth_atom_id);
            compIds = mol_data_db["Column"].ofStringTokens(atomSite.auth_comp_id);
            asymIds = mol_data_db["Column"].ofStringTokens(atomSite.auth_asym_id);
            componentBuilder = new component_ComponentBuilder(seqIds, atomIds);
            componentBuilder.setNames(heteroNames);
            entityBuilder.setNames(heteroNames);
            for (i = 0, il = compIds.rowCount; i < il; ++i) {
                compId = compIds.value(i);
                moleculeType = Object(types["getMoleculeType"])(componentBuilder.add(compId, i).type, compId);
                atomSite.label_entity_id[i] = entityBuilder.getEntityId(compId, moleculeType, asymIds.value(i));
            }
            categories = {
                entity: reader_cif["b" /* CifCategory */].ofTable('entity', entityBuilder.getEntityTable()),
                chem_comp: reader_cif["b" /* CifCategory */].ofTable('chem_comp', componentBuilder.getChemCompTable()),
                atom_site: reader_cif["b" /* CifCategory */].ofFields('atom_site', getAtomSite(atomSite)),
                atom_site_anisotrop: reader_cif["b" /* CifCategory */].ofFields('atom_site_anisotrop', getAnisotropic(anisotropic))
            };
            for (_a = 0, helperCategories_1 = helperCategories; _a < helperCategories_1.length; _a++) {
                c = helperCategories_1[_a];
                categories[c.name] = c;
            }
            return [2 /*return*/, {
                    header: pdb.id || 'PDB',
                    categoryNames: Object.keys(categories),
                    categories: categories
                }];
        });
    });
}
//# sourceMappingURL=to-cif.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/pdb.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function trajectoryFromPDB(pdb) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse PDB', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var cif, format;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, ctx.update('Converting to mmCIF')];
                case 1:
                    _a.sent();
                    return [4 /*yield*/, pdbToMmCif(pdb)];
                case 2:
                    cif = _a.sent();
                    format = mmcif["MmcifFormat"].fromFrame(cif);
                    return [2 /*return*/, Object(parser["a" /* createModels */])(format.data.db, format, ctx)];
            }
        });
    }); });
}
//# sourceMappingURL=pdb.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/topology/topology.js
var topology_topology = __webpack_require__(341);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/psf.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










function psf_getBasic(atoms) {
    var auth_atom_id = atoms.atomName;
    var auth_comp_id = atoms.residueName;
    var entityIds = new Array(atoms.count);
    var asymIds = new Array(atoms.count);
    var seqIds = new Uint32Array(atoms.count);
    var ids = new Uint32Array(atoms.count);
    var entityBuilder = new entity_EntityBuilder();
    var componentBuilder = new component_ComponentBuilder(atoms.residueId, atoms.atomName);
    var currentEntityId = '';
    var currentAsymIndex = 0;
    var currentAsymId = '';
    var currentSeqId = 0;
    var currentSegmentName = atoms.segmentName.value(0), segmentChanged = false;
    var prevMoleculeType = 0 /* Unknown */;
    var prevResidueNumber = -1;
    for (var i = 0, il = atoms.count; i < il; ++i) {
        var residueNumber = atoms.residueId.value(i);
        if (currentSegmentName !== atoms.segmentName.value(i)) {
            currentAsymId = getChainId(currentAsymIndex);
            currentAsymIndex += 1;
            currentSeqId = 0;
            segmentChanged = true;
            currentSegmentName = atoms.segmentName.value(i);
        }
        else {
            segmentChanged = false;
        }
        if (segmentChanged || residueNumber !== prevResidueNumber) {
            var compId = atoms.residueName.value(i);
            var moleculeType = Object(types["getMoleculeType"])(componentBuilder.add(compId, i).type, compId);
            if (!segmentChanged && (moleculeType !== prevMoleculeType || residueNumber !== prevResidueNumber + 1)) {
                currentAsymId = getChainId(currentAsymIndex);
                currentAsymIndex += 1;
                currentSeqId = 0;
            }
            currentEntityId = entityBuilder.getEntityId(compId, moleculeType, currentAsymId);
            currentSeqId += 1;
            prevResidueNumber = residueNumber;
            prevMoleculeType = moleculeType;
        }
        entityIds[i] = currentEntityId;
        asymIds[i] = currentAsymId;
        seqIds[i] = currentSeqId;
        ids[i] = i;
    }
    var auth_asym_id = mol_data_db["Column"].ofStringArray(asymIds);
    var atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
        auth_asym_id: auth_asym_id,
        auth_atom_id: auth_atom_id,
        auth_comp_id: auth_comp_id,
        auth_seq_id: atoms.residueId,
        id: mol_data_db["Column"].ofIntArray(ids),
        label_asym_id: auth_asym_id,
        label_atom_id: auth_atom_id,
        label_comp_id: auth_comp_id,
        label_seq_id: mol_data_db["Column"].ofIntArray(seqIds),
        label_entity_id: mol_data_db["Column"].ofStringArray(entityIds),
        occupancy: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.float),
        type_symbol: mol_data_db["Column"].ofStringArray(mol_data_db["Column"].mapToArray(atoms.atomName, function (s) { return guessElementSymbolString(s); })),
        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.int),
    }, atoms.count);
    return Object(basic_schema["b" /* createBasic */])({
        entity: entityBuilder.getEntityTable(),
        chem_comp: componentBuilder.getChemCompTable(),
        atom_site: atom_site
    });
}
//

var PsfFormat;
(function (PsfFormat) {
    function is(x) {
        return x.kind === 'psf';
    }
    PsfFormat.is = is;
    function fromPsf(psf) {
        return { kind: 'psf', name: psf.id, data: psf };
    }
    PsfFormat.fromPsf = fromPsf;
})(PsfFormat || (PsfFormat = {}));
function topologyFromPsf(psf) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse PSF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var format, basic, _a, atomIdA, atomIdB, bonds;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            format = PsfFormat.fromPsf(psf);
            basic = psf_getBasic(psf.atoms);
            _a = psf.bonds, atomIdA = _a.atomIdA, atomIdB = _a.atomIdB;
            bonds = {
                indexA: mol_data_db["Column"].ofLambda({
                    value: function (row) { return atomIdA.value(row) - 1; },
                    rowCount: atomIdA.rowCount,
                    schema: atomIdA.schema,
                }),
                indexB: mol_data_db["Column"].ofLambda({
                    value: function (row) { return atomIdB.value(row) - 1; },
                    rowCount: atomIdB.rowCount,
                    schema: atomIdB.schema,
                }),
                order: mol_data_db["Column"].ofConst(1, psf.bonds.count, mol_data_db["Column"].Schema.int)
            };
            return [2 /*return*/, topology_topology["a" /* Topology */].create(psf.id, basic, bonds, format)];
        });
    }); });
}
//# sourceMappingURL=psf.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/language/builder.js
var builder = __webpack_require__(10);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/script.js + 4 modules
var mol_script_script = __webpack_require__(120);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/root-structure.js
var root_structure = __webpack_require__(269);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-script/runtime/query/compiler.js + 2 modules
var compiler = __webpack_require__(163);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-query.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var structure_query_StructureQueryHelper;
(function (StructureQueryHelper) {
    function isUnchanged(entry, query, structure) {
        if (entry.currentStructure !== structure)
            return false;
        if (mol_script_script["Script"].is(query)) {
            return !!entry.script && mol_script_script["Script"].areEqual(entry.script, query);
        }
        return entry.expression === query;
    }
    StructureQueryHelper.isUnchanged = isUnchanged;
    function create(structure, query) {
        var script = mol_script_script["Script"].is(query) ? query : void 0;
        var expression = mol_script_script["Script"].is(query) ? mol_script_script["Script"].toExpression(query) : query;
        var compiled = Object(compiler["compile"])(expression);
        return { script: script, expression: expression, compiled: compiled, originalStructure: structure, currentStructure: structure };
    }
    StructureQueryHelper.create = create;
    function run(entry, structure) {
        return entry.compiled(new mol_model_structure["QueryContext"](structure));
    }
    StructureQueryHelper.run = run;
    function createAndRun(structure, query) {
        var entry = create(structure, query);
        return { entry: entry, selection: run(entry, structure) };
    }
    StructureQueryHelper.createAndRun = createAndRun;
    function updateStructure(entry, structure) {
        entry.currentStructure = structure;
        return entry.compiled(new mol_model_structure["QueryContext"](structure));
    }
    StructureQueryHelper.updateStructure = updateStructure;
    function updateStructureObject(obj, selection, label) {
        var s = mol_model_structure["StructureSelection"].unionStructure(selection);
        obj.label = "" + (label || 'Selection');
        obj.description = mol_model_structure["Structure"].elementDescription(s);
        obj.data = s;
    }
    StructureQueryHelper.updateStructureObject = updateStructureObject;
})(structure_query_StructureQueryHelper || (structure_query_StructureQueryHelper = {}));
//# sourceMappingURL=structure-query.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-selection-query.js
var structure_selection_query = __webpack_require__(80);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-component.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var StaticStructureComponentTypes = [
    'all',
    'polymer',
    'protein',
    'nucleic',
    'water',
    'ion',
    'lipid',
    'branched',
    'ligand',
    'non-standard',
    'coarse'
];
var StructureComponentParams = {
    type: param_definition["ParamDefinition"].MappedStatic('static', {
        static: param_definition["ParamDefinition"].Text('polymer'),
        expression: param_definition["ParamDefinition"].Value(builder["MolScriptBuilder"].struct.generator.all),
        bundle: param_definition["ParamDefinition"].Value(mol_model_structure["StructureElement"].Bundle.Empty),
        script: param_definition["ParamDefinition"].Script({ language: 'mol-script', expression: '(sel.atom.all)' }),
    }, { isHidden: true }),
    nullIfEmpty: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(true, { isHidden: true })),
    label: param_definition["ParamDefinition"].Text('', { isHidden: true })
};
function createStructureComponent(a, params, cache) {
    cache.source = a;
    var component = mol_model_structure["Structure"].Empty;
    var label = void 0;
    switch (params.type.name) {
        case 'static': {
            var query = void 0;
            switch (params.type.params) {
                case 'all':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].all.query;
                    label = 'All';
                    break;
                case 'polymer':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].polymer.query;
                    label = 'Polymer';
                    break;
                case 'protein':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].protein.query;
                    label = 'Protein';
                    break;
                case 'nucleic':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].nucleic.query;
                    label = 'Nucleic';
                    break;
                case 'water':
                    query = mol_model_structure["Queries"].internal.water();
                    label = 'Water';
                    break;
                case 'ion':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].ion.query;
                    label = 'Ion';
                    break;
                case 'lipid':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].lipid.query;
                    label = 'Lipid';
                    break;
                case 'branched':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].branchedPlusConnected.query;
                    label = 'Branched';
                    break;
                case 'ligand':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].ligandPlusConnected.query;
                    label = 'Ligand';
                    break;
                case 'non-standard':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].nonStandardPolymer.query;
                    label = 'Non-standard';
                    break;
                case 'coarse':
                    query = structure_selection_query["b" /* StructureSelectionQueries */].coarse.query;
                    label = 'Coarse';
                    break;
                default: throw new Error(params.type + " is a not valid complex element.");
            }
            var result = query(new mol_model_structure["QueryContext"](a));
            component = mol_model_structure["StructureSelection"].unionStructure(result);
            break;
        }
        case 'script':
        case 'expression': {
            var _a = structure_query_StructureQueryHelper.createAndRun(a, params.type.params), selection = _a.selection, entry = _a.entry;
            cache.entry = entry;
            component = mol_model_structure["StructureSelection"].unionStructure(selection);
            break;
        }
        case 'bundle': {
            if (params.type.params.hash !== a.hashCode)
                break;
            component = mol_model_structure["StructureElement"].Bundle.toStructure(params.type.params, a);
            break;
        }
    }
    if (params.nullIfEmpty && component.elementCount === 0)
        return mol_state["StateObject"].Null;
    var props = { label: "" + (params.label || label || 'Component'), description: mol_model_structure["Structure"].elementDescription(component) };
    return new objects["a" /* PluginStateObject */].Molecule.Structure(component, props);
}
function updateStructureComponent(a, b, oldParams, newParams, cache) {
    if (oldParams.type.name !== newParams.type.name)
        return mol_state["StateTransformer"].UpdateResult.Recreate;
    var updated = false;
    switch (newParams.type.name) {
        case 'static': {
            if (a !== cache.source || oldParams.type.params !== newParams.type.params) {
                return mol_state["StateTransformer"].UpdateResult.Recreate;
            }
            break;
        }
        case 'script':
            if (!mol_script_script["Script"].areEqual(oldParams.type.params, newParams.type.params)) {
                return mol_state["StateTransformer"].UpdateResult.Recreate;
            }
        case 'expression': {
            if (oldParams.type.params !== newParams.type.params) {
                return mol_state["StateTransformer"].UpdateResult.Recreate;
            }
            if (a === cache.source)
                break;
            var entry = cache.entry;
            var selection = structure_query_StructureQueryHelper.updateStructure(entry, a);
            cache.source = a;
            b.data = mol_model_structure["StructureSelection"].unionStructure(selection);
            structure_query_StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
            updated = true;
            break;
        }
        case 'bundle': {
            if (a === cache.source && mol_model_structure["StructureElement"].Bundle.areEqual(oldParams.type.params, newParams.type.params)) {
                break;
            }
            cache.source = a;
            if (newParams.type.params.hash !== a.hashCode) {
                updated = b.data.elementCount !== 0;
                b.data = b.data.elementCount === 0 ? b.data : mol_model_structure["Structure"].Empty;
            }
            else {
                updated = true;
                b.data = mol_model_structure["StructureElement"].Bundle.toStructure(newParams.type.params, a);
            }
            break;
        }
    }
    if (updated) {
        if (newParams.nullIfEmpty && b.data.elementCount === 0)
            return mol_state["StateTransformer"].UpdateResult.Null;
        b.description = mol_model_structure["Structure"].elementDescription(b.data);
    }
    if (oldParams.label !== newParams.label) {
        updated = true;
        b.label = "" + (newParams.label || b.label);
    }
    return updated ? mol_state["StateTransformer"].UpdateResult.Updated : mol_state["StateTransformer"].UpdateResult.Unchanged;
}
//# sourceMappingURL=structure-component.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/common/text/column/token.js
var token = __webpack_require__(73);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/mol/parser.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






function parser_handleAtoms(tokenizer, count) {
    var x = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    var y = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    var z = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    var type_symbol = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    for (var i = 0; i < count; ++i) {
        text_tokenizer["b" /* Tokenizer */].markLine(tokenizer);
        var s = tokenizer.tokenStart, position = tokenizer.position;
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s, s + 10);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(x, tokenizer.tokenStart, tokenizer.tokenEnd);
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s + 10, s + 20);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(y, tokenizer.tokenStart, tokenizer.tokenEnd);
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s + 20, s + 30);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(z, tokenizer.tokenStart, tokenizer.tokenEnd);
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s + 31, s + 34);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(type_symbol, tokenizer.tokenStart, tokenizer.tokenEnd);
        tokenizer.position = position;
    }
    return {
        count: count,
        x: Object(token["c" /* default */])(x)(mol_data_db["Column"].Schema.float),
        y: Object(token["c" /* default */])(y)(mol_data_db["Column"].Schema.float),
        z: Object(token["c" /* default */])(z)(mol_data_db["Column"].Schema.float),
        type_symbol: Object(token["c" /* default */])(type_symbol)(mol_data_db["Column"].Schema.str)
    };
}
function handleBonds(tokenizer, count) {
    var atomIdxA = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    var atomIdxB = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    var order = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, count * 2);
    for (var i = 0; i < count; ++i) {
        text_tokenizer["b" /* Tokenizer */].markLine(tokenizer);
        var s = tokenizer.tokenStart, position = tokenizer.position;
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s, s + 3);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomIdxA, tokenizer.tokenStart, tokenizer.tokenEnd);
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s + 3, s + 6);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(atomIdxB, tokenizer.tokenStart, tokenizer.tokenEnd);
        text_tokenizer["b" /* Tokenizer */].trim(tokenizer, s + 6, s + 9);
        text_tokenizer["a" /* TokenBuilder */].addUnchecked(order, tokenizer.tokenStart, tokenizer.tokenEnd);
        tokenizer.position = position;
    }
    return {
        count: count,
        atomIdxA: Object(token["c" /* default */])(atomIdxA)(mol_data_db["Column"].Schema.int),
        atomIdxB: Object(token["c" /* default */])(atomIdxB)(mol_data_db["Column"].Schema.int),
        order: Object(token["c" /* default */])(order)(mol_data_db["Column"].Schema.int)
    };
}
function mol_parser_parseInternal(data) {
    var tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
    var title = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim();
    var program = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim();
    var comment = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer).trim();
    var counts = text_tokenizer["b" /* Tokenizer */].readLine(tokenizer);
    var atomCount = +counts.substr(0, 3), bondCount = +counts.substr(3, 3);
    var atoms = parser_handleAtoms(tokenizer, atomCount);
    var bonds = handleBonds(tokenizer, bondCount);
    var result = {
        title: title,
        program: program,
        comment: comment,
        atoms: atoms,
        bonds: bonds
    };
    return reader_result["a" /* ReaderResult */].success(result);
}
function parseMol(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse Mol', function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, mol_parser_parseInternal(data)];
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/bonds/index-pair.js
var index_pair = __webpack_require__(173);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mol.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








function getModels(mol, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var atoms, bonds, MOL, A, type_symbol, seq_id, atom_site, entityBuilder, componentBuilder, basics, models, indexA, indexB, order, pairBonds;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    atoms = mol.atoms, bonds = mol.bonds;
                    MOL = mol_data_db["Column"].ofConst('MOL', mol.atoms.count, mol_data_db["Column"].Schema.str);
                    A = mol_data_db["Column"].ofConst('A', mol.atoms.count, mol_data_db["Column"].Schema.str);
                    type_symbol = mol_data_db["Column"].asArrayColumn(atoms.type_symbol);
                    seq_id = mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.int);
                    atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
                        auth_asym_id: A,
                        auth_atom_id: type_symbol,
                        auth_comp_id: MOL,
                        auth_seq_id: seq_id,
                        Cartn_x: mol_data_db["Column"].asArrayColumn(atoms.x, Float32Array),
                        Cartn_y: mol_data_db["Column"].asArrayColumn(atoms.y, Float32Array),
                        Cartn_z: mol_data_db["Column"].asArrayColumn(atoms.z, Float32Array),
                        id: mol_data_db["Column"].range(0, atoms.count - 1),
                        label_asym_id: A,
                        label_atom_id: type_symbol,
                        label_comp_id: MOL,
                        label_seq_id: seq_id,
                        label_entity_id: mol_data_db["Column"].ofConst('1', atoms.count, mol_data_db["Column"].Schema.str),
                        occupancy: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.float),
                        type_symbol: type_symbol,
                        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.int),
                    }, atoms.count);
                    entityBuilder = new entity_EntityBuilder();
                    entityBuilder.setNames([['MOL', 'Unknown Entity']]);
                    entityBuilder.getEntityId('MOL', 0 /* Unknown */, 'A');
                    componentBuilder = new component_ComponentBuilder(seq_id, type_symbol);
                    componentBuilder.setNames([['MOL', 'Unknown Molecule']]);
                    componentBuilder.add('MOL', 0);
                    basics = Object(basic_schema["b" /* createBasic */])({
                        entity: entityBuilder.getEntityTable(),
                        chem_comp: componentBuilder.getChemCompTable(),
                        atom_site: atom_site
                    });
                    return [4 /*yield*/, Object(parser["a" /* createModels */])(basics, MolFormat.create(mol), ctx)];
                case 1:
                    models = _a.sent();
                    if (models.length > 0) {
                        indexA = mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(bonds.atomIdxA, function (x) { return x - 1; }, Int32Array));
                        indexB = mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(bonds.atomIdxB, function (x) { return x - 1; }, Int32Array));
                        order = mol_data_db["Column"].asArrayColumn(bonds.order, Int32Array);
                        pairBonds = index_pair["a" /* IndexPairBonds */].fromData({ pairs: { indexA: indexA, indexB: indexB, order: order }, count: bonds.count });
                        index_pair["a" /* IndexPairBonds */].Provider.set(models[0], pairBonds);
                    }
                    return [2 /*return*/, models];
            }
        });
    });
}
//

var MolFormat;
(function (MolFormat) {
    function is(x) {
        return x.kind === 'mol';
    }
    MolFormat.is = is;
    function create(mol) {
        return { kind: 'mol', name: mol.title, data: mol };
    }
    MolFormat.create = create;
})(MolFormat || (MolFormat = {}));
function trajectoryFromMol(mol) {
    return mol_task["b" /* Task */].create('Parse MOL', function (ctx) { return getModels(mol, ctx); });
}
//# sourceMappingURL=mol.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js + 1 modules
var property_symmetry = __webpack_require__(113);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/anisotropic.js
var property_anisotropic = __webpack_require__(211);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/cif-core.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














function getSpacegroupNameOrNumber(space_group) {
    var groupNumber = space_group.IT_number.value(0);
    var groupName = space_group['name_H-M_full'].value(0);
    if (!space_group.IT_number.isDefined)
        return groupName;
    if (!space_group['name_H-M_full'].isDefined)
        return groupNumber;
    return groupNumber;
}
function getSymmetry(db) {
    var cell = db.cell, space_group = db.space_group;
    var nameOrNumber = getSpacegroupNameOrNumber(space_group);
    var spaceCell = geometry["f" /* SpacegroupCell */].create(nameOrNumber, linear_algebra["Vec3"].create(cell.length_a.value(0), cell.length_b.value(0), cell.length_c.value(0)), linear_algebra["Vec3"].scale(linear_algebra["Vec3"].zero(), linear_algebra["Vec3"].create(cell.angle_alpha.value(0), cell.angle_beta.value(0), cell.angle_gamma.value(0)), Math.PI / 180));
    return {
        spacegroup: geometry["e" /* Spacegroup */].create(spaceCell),
        assemblies: [],
        isNonStandardCrystalFrame: false,
        ncsOperators: []
    };
}
function cif_core_getModels(db, format, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var atomCount, MOL, A, seq_id, symmetry, m, _a, fract_x, fract_y, fract_z, x, y, z, v, i, _b, type_symbol, label, typeSymbol, formalCharge, element_symbol, formal_charge, i, ts, n, element_symbol, i, atom_site, name, entityBuilder, componentBuilder, basics, models, bondCount, labelIndexMap, label_1, i, il, indexA, indexB, order, symmetryA, symmetryB, _c, atom_site_label_1, atom_site_label_2, valence, site_symmetry_1, site_symmetry_2, i;
        return Object(tslib_es6["__generator"])(this, function (_d) {
            switch (_d.label) {
                case 0:
                    atomCount = db.atom_site._rowCount;
                    MOL = mol_data_db["Column"].ofConst('MOL', atomCount, mol_data_db["Column"].Schema.str);
                    A = mol_data_db["Column"].ofConst('A', atomCount, mol_data_db["Column"].Schema.str);
                    seq_id = mol_data_db["Column"].ofConst(1, atomCount, mol_data_db["Column"].Schema.int);
                    symmetry = getSymmetry(db);
                    m = symmetry.spacegroup.cell.fromFractional;
                    _a = db.atom_site, fract_x = _a.fract_x, fract_y = _a.fract_y, fract_z = _a.fract_z;
                    x = new Float32Array(atomCount);
                    y = new Float32Array(atomCount);
                    z = new Float32Array(atomCount);
                    v = Object(linear_algebra["Vec3"])();
                    for (i = 0; i < atomCount; ++i) {
                        linear_algebra["Vec3"].set(v, fract_x.value(i), fract_y.value(i), fract_z.value(i));
                        linear_algebra["Vec3"].transformMat4(v, v, m);
                        x[i] = v[0], y[i] = v[1], z[i] = v[2];
                    }
                    _b = db.atom_site, type_symbol = _b.type_symbol, label = _b.label;
                    if (type_symbol.isDefined) {
                        element_symbol = new Array(atomCount);
                        formal_charge = new Int8Array(atomCount);
                        for (i = 0; i < atomCount; ++i) {
                            ts = type_symbol.value(i);
                            n = ts.length;
                            if (ts[n - 1] === '+') {
                                element_symbol[i] = ts.substring(0, n - 2);
                                formal_charge[i] = parseInt(ts[n - 2]);
                            }
                            else if (ts[n - 2] === '+') {
                                element_symbol[i] = ts.substring(0, n - 2);
                                formal_charge[i] = parseInt(ts[n - 1]);
                            }
                            else if (ts[n - 1] === '-') {
                                element_symbol[i] = ts.substring(0, n - 2);
                                formal_charge[i] = -parseInt(ts[n - 2]);
                            }
                            else if (ts[n - 2] === '-') {
                                element_symbol[i] = ts.substring(0, n - 2);
                                formal_charge[i] = -parseInt(ts[n - 1]);
                            }
                            else {
                                element_symbol[i] = ts;
                                formal_charge[i] = 0;
                            }
                        }
                        typeSymbol = mol_data_db["Column"].ofStringArray(element_symbol);
                        formalCharge = mol_data_db["Column"].ofIntArray(formal_charge);
                    }
                    else {
                        element_symbol = new Array(atomCount);
                        for (i = 0; i < atomCount; ++i) {
                            // TODO can take as is if type_symbol not given?
                            element_symbol[i] = guessElementSymbolString(label.value(i));
                        }
                        typeSymbol = mol_data_db["Column"].ofStringArray(element_symbol);
                        formalCharge = mol_data_db["Column"].Undefined(atomCount, mol_data_db["Column"].Schema.int);
                    }
                    atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
                        auth_asym_id: A,
                        auth_atom_id: label,
                        auth_comp_id: MOL,
                        auth_seq_id: seq_id,
                        Cartn_x: mol_data_db["Column"].ofFloatArray(x),
                        Cartn_y: mol_data_db["Column"].ofFloatArray(y),
                        Cartn_z: mol_data_db["Column"].ofFloatArray(z),
                        id: mol_data_db["Column"].range(0, atomCount - 1),
                        label_asym_id: A,
                        label_atom_id: label,
                        label_comp_id: MOL,
                        label_seq_id: seq_id,
                        label_entity_id: mol_data_db["Column"].ofConst('1', atomCount, mol_data_db["Column"].Schema.str),
                        occupancy: db.atom_site.occupancy.isDefined
                            ? db.atom_site.occupancy
                            : mol_data_db["Column"].ofConst(1, atomCount, mol_data_db["Column"].Schema.float),
                        type_symbol: typeSymbol,
                        pdbx_formal_charge: formalCharge,
                        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(1, atomCount, mol_data_db["Column"].Schema.int),
                        B_iso_or_equiv: db.atom_site.U_iso_or_equiv,
                    }, atomCount);
                    name = (db.chemical.name_common.value(0) ||
                        db.chemical.name_systematic.value(0) ||
                        db.chemical_formula.sum.value(0));
                    entityBuilder = new entity_EntityBuilder();
                    entityBuilder.setNames([['MOL', name || 'Unknown Entity']]);
                    entityBuilder.getEntityId('MOL', 0 /* Unknown */, 'A');
                    componentBuilder = new component_ComponentBuilder(seq_id, db.atom_site.type_symbol);
                    componentBuilder.setNames([['MOL', name || 'Unknown Molecule']]);
                    componentBuilder.add('MOL', 0);
                    basics = Object(basic_schema["b" /* createBasic */])({
                        entity: entityBuilder.getEntityTable(),
                        chem_comp: componentBuilder.getChemCompTable(),
                        atom_site: atom_site
                    });
                    return [4 /*yield*/, Object(parser["a" /* createModels */])(basics, format, ctx)];
                case 1:
                    models = _d.sent();
                    if (models.length > 0) {
                        property_symmetry["a" /* ModelSymmetry */].Provider.set(models[0], symmetry);
                        bondCount = db.geom_bond._rowCount;
                        if (bondCount > 0) {
                            labelIndexMap = {};
                            label_1 = db.atom_site.label;
                            for (i = 0, il = label_1.rowCount; i < il; ++i) {
                                labelIndexMap[label_1.value(i)] = i;
                            }
                            indexA = [];
                            indexB = [];
                            order = [];
                            symmetryA = [];
                            symmetryB = [];
                            _c = db.geom_bond, atom_site_label_1 = _c.atom_site_label_1, atom_site_label_2 = _c.atom_site_label_2, valence = _c.valence, site_symmetry_1 = _c.site_symmetry_1, site_symmetry_2 = _c.site_symmetry_2;
                            for (i = 0; i < bondCount; ++i) {
                                indexA[i] = labelIndexMap[atom_site_label_1.value(i)];
                                indexB[i] = labelIndexMap[atom_site_label_2.value(i)];
                                // TODO derive order from bond length if undefined
                                order[i] = valence.isDefined ? valence.value(i) : 1;
                                symmetryA[i] = site_symmetry_1.value(i) || '1_555';
                                symmetryB[i] = site_symmetry_2.value(i) || '1_555';
                            }
                            index_pair["a" /* IndexPairBonds */].Provider.set(models[0], index_pair["a" /* IndexPairBonds */].fromData({ pairs: {
                                    indexA: mol_data_db["Column"].ofIntArray(indexA),
                                    indexB: mol_data_db["Column"].ofIntArray(indexB),
                                    order: mol_data_db["Column"].ofIntArray(order),
                                    symmetryA: mol_data_db["Column"].ofStringArray(symmetryA),
                                    symmetryB: mol_data_db["Column"].ofStringArray(symmetryB)
                                }, count: indexA.length }));
                        }
                    }
                    return [2 /*return*/, models];
            }
        });
    });
}
function atomSiteAnisotropFromCifCore(model) {
    if (!cif_core_CifCoreFormat.is(model.sourceData))
        return;
    var _a = model.sourceData.data.db, atom_site = _a.atom_site, atom_site_aniso = _a.atom_site_aniso;
    var data = mol_data_db["Table"].ofPartialColumns(property_anisotropic["a" /* AtomSiteAnisotrop */].Schema, {
        U: atom_site_aniso.U,
        U_esd: atom_site_aniso.U_su
    }, atom_site_aniso._rowCount);
    var elementToAnsiotrop = property_anisotropic["a" /* AtomSiteAnisotrop */].getElementToAnsiotropFromLabel(atom_site.label, atom_site_aniso.label);
    return { data: data, elementToAnsiotrop: elementToAnsiotrop };
}
function atomSiteAnisotropApplicableCifCore(model) {
    if (!cif_core_CifCoreFormat.is(model.sourceData))
        return false;
    return model.sourceData.data.db.atom_site_aniso.U.isDefined;
}
property_anisotropic["a" /* AtomSiteAnisotrop */].Provider.formatRegistry.add('cifCore', atomSiteAnisotropFromCifCore, atomSiteAnisotropApplicableCifCore);
//

var cif_core_CifCoreFormat;
(function (CifCoreFormat) {
    function is(x) {
        return x.kind === 'cifCore';
    }
    CifCoreFormat.is = is;
    function fromFrame(frame, db) {
        if (!db)
            db = reader_cif["a" /* CIF */].schema.cifCore(frame);
        var name = (db.database_code.depnum_ccdc_archive.value(0) ||
            db.database_code.depnum_ccdc_fiz.value(0) ||
            db.database_code.ICSD.value(0) ||
            db.database_code.MDF.value(0) ||
            db.database_code.NBS.value(0) ||
            db.database_code.CSD.value(0) ||
            db.database_code.COD.value(0) ||
            db._name);
        return { kind: 'cifCore', name: name, data: { db: db, frame: frame } };
    }
    CifCoreFormat.fromFrame = fromFrame;
})(cif_core_CifCoreFormat || (cif_core_CifCoreFormat = {}));
function trajectoryFromCifCore(frame) {
    var format = cif_core_CifCoreFormat.fromFrame(frame);
    return mol_task["b" /* Task */].create('Parse CIF Core', function (ctx) { return cif_core_getModels(format.data.db, format, ctx); });
}
//# sourceMappingURL=cif-core.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/cube.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */








function cube_getModels(cube, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var atoms, MOL, A, type_symbol, seq_id, atom_site, entityBuilder, componentBuilder, basics;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    atoms = cube.atoms;
                    MOL = mol_data_db["Column"].ofConst('MOL', cube.atoms.count, mol_data_db["Column"].Schema.str);
                    A = mol_data_db["Column"].ofConst('A', cube.atoms.count, mol_data_db["Column"].Schema.str);
                    type_symbol = mol_data_db["Column"].ofArray({ array: mol_data_db["Column"].mapToArray(atoms.number, function (n) { return Object(types["getElementFromAtomicNumber"])(n); }), schema: mol_data_db["Column"].Schema.Aliased(mol_data_db["Column"].Schema.str) });
                    seq_id = mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.int);
                    atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
                        auth_asym_id: A,
                        auth_atom_id: type_symbol,
                        auth_comp_id: MOL,
                        auth_seq_id: seq_id,
                        Cartn_x: mol_data_db["Column"].asArrayColumn(atoms.x, Float32Array),
                        Cartn_y: mol_data_db["Column"].asArrayColumn(atoms.y, Float32Array),
                        Cartn_z: mol_data_db["Column"].asArrayColumn(atoms.z, Float32Array),
                        id: mol_data_db["Column"].range(0, atoms.count - 1),
                        label_asym_id: A,
                        label_atom_id: type_symbol,
                        label_comp_id: MOL,
                        label_seq_id: seq_id,
                        label_entity_id: mol_data_db["Column"].ofConst('1', atoms.count, mol_data_db["Column"].Schema.str),
                        occupancy: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.float),
                        type_symbol: type_symbol,
                        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.int),
                    }, atoms.count);
                    entityBuilder = new entity_EntityBuilder();
                    entityBuilder.setNames([['MOL', 'Unknown Entity']]);
                    entityBuilder.getEntityId('MOL', 0 /* Unknown */, 'A');
                    componentBuilder = new component_ComponentBuilder(seq_id, type_symbol);
                    componentBuilder.setNames([['MOL', 'Unknown Molecule']]);
                    componentBuilder.add('MOL', 0);
                    basics = Object(basic_schema["b" /* createBasic */])({
                        entity: entityBuilder.getEntityTable(),
                        chem_comp: componentBuilder.getChemCompTable(),
                        atom_site: atom_site
                    });
                    return [4 /*yield*/, Object(parser["a" /* createModels */])(basics, cube_MolFormat.create(cube), ctx)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
var cube_MolFormat;
(function (MolFormat) {
    function is(x) {
        return x.kind === 'cube';
    }
    MolFormat.is = is;
    function create(cube) {
        return { kind: 'cube', name: cube.header.comment1, data: cube };
    }
    MolFormat.create = create;
})(cube_MolFormat || (cube_MolFormat = {}));
function trajectoryFromCube(cube) {
    return mol_task["b" /* Task */].create('Parse Cube', function (ctx) { return cube_getModels(cube, ctx); });
}
//# sourceMappingURL=cube.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/mol2/parser.js
/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Zepei Xu <xuzepei19950617@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

//               NOTES
// When want to created undefined string column, must use
// undefStr = UndefinedColumn(molecule.num_atoms, ColumnType.str)
// but not
// const undefPooledStr = UndefinedColumn(molecule.num_atoms, ColumnType.pooledStr);
// because latter actuall return a column of zeros





var parser_skipWhitespace = text_tokenizer["b" /* Tokenizer */].skipWhitespace, parser_eatValue = text_tokenizer["b" /* Tokenizer */].eatValue, markLine = text_tokenizer["b" /* Tokenizer */].markLine, getTokenString = text_tokenizer["b" /* Tokenizer */].getTokenString, readLine = text_tokenizer["b" /* Tokenizer */].readLine;
function createEmptyMolecule() {
    return {
        mol_name: '',
        num_atoms: 0,
        num_bonds: 0,
        num_subst: 0,
        num_feat: 0,
        num_sets: 0,
        mol_type: '',
        charge_type: '',
        status_bits: '',
        mol_comment: ''
    };
}
function mol2_parser_State(tokenizer, runtimeCtx) {
    return {
        tokenizer: tokenizer,
        molecule: createEmptyMolecule(),
        runtimeCtx: runtimeCtx
    };
}
var reWhitespace = /\s+/g;
function handleMolecule(state) {
    var tokenizer = state.tokenizer, molecule = state.molecule;
    while (getTokenString(tokenizer) !== '@<TRIPOS>MOLECULE' && tokenizer.position < tokenizer.data.length) {
        markLine(tokenizer);
    }
    markLine(tokenizer);
    molecule.mol_name = getTokenString(tokenizer);
    markLine(tokenizer);
    var values = getTokenString(tokenizer).trim().split(reWhitespace);
    molecule.num_atoms = parseInt(values[0]);
    molecule.num_bonds = parseInt(values[1]);
    molecule.num_subst = parseInt(values[2]);
    molecule.num_feat = parseInt(values[3]);
    molecule.num_sets = parseInt(values[4]);
    markLine(tokenizer);
    molecule.mol_type = getTokenString(tokenizer);
    markLine(tokenizer);
    molecule.charge_type = getTokenString(tokenizer);
    markLine(tokenizer);
    if (getTokenString(tokenizer) === '')
        return;
    molecule.status_bits = getTokenString(tokenizer);
    markLine(tokenizer);
    if (getTokenString(tokenizer) === '')
        return;
    molecule.mol_comment = getTokenString(tokenizer);
}
function isStatus_bit(aString) {
    if (aString.includes('DSPMOD') || aString.includes('TYPECOL') || aString.includes('CAP')
        || aString.includes('BACKBONE') || aString.includes('DICT') || aString.includes('ESSENTIAL')
        || aString.includes('WATER') || aString.includes('DIRECT')) {
        return true;
    }
    return false;
}
function mol2_parser_handleAtoms(state) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, molecule, hasSubst_id, hasSubst_name, hasCharge, hasStatus_bit, initialTokenizerPosition, initialTokenizerLineNumber, firstLine, firstLineArray, firstLineLength, i, atom_idTokens, atom_nameTokens, xTokens, yTokens, zTokens, atom_typeTokens, atom_idTokenColumn, atom_nameTokenColumn, xTokenColumn, yTokenColumn, zTokenColumn, atom_typeColumn, subst_idTokens, subst_nameTokens, chargeTokens, status_bitTokens, subst_idTokenColumn, subst_nameTokenColumn, chargeTokenColumn, status_bitTokenColumn, undefFloat, undefInt, undefStr, numOfColumn, length, linesAlreadyRead, ret;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = state.tokenizer, molecule = state.molecule;
                    hasSubst_id = false;
                    hasSubst_name = false;
                    hasCharge = false;
                    hasStatus_bit = false;
                    // skip empty lines and '@<TRIPOS>ATOM'
                    while (getTokenString(tokenizer) !== '@<TRIPOS>ATOM' && tokenizer.position < tokenizer.data.length) {
                        markLine(tokenizer);
                    }
                    initialTokenizerPosition = tokenizer.position;
                    initialTokenizerLineNumber = tokenizer.lineNumber;
                    firstLine = readLine(tokenizer);
                    firstLineArray = firstLine.trim().split(/\s+/g);
                    firstLineLength = firstLineArray.length;
                    // optional columns are in order "integer string float string".
                    // Use this to find out which column is missing or empty
                    for (i = 6; i < firstLineLength; i++) {
                        if (!isNaN(Number(firstLineArray[i]))) {
                            if (firstLineArray[i].indexOf('.') === -1) {
                                hasSubst_id = true;
                            }
                            else {
                                hasCharge = true;
                            }
                        }
                        else if (isNaN(Number(firstLineArray[i]))) {
                            if (!isStatus_bit(firstLineArray[i])) {
                                hasSubst_name = true;
                            }
                            else {
                                hasStatus_bit = true;
                            }
                        }
                    }
                    atom_idTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    atom_nameTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    xTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    yTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    zTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    atom_typeTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    atom_idTokenColumn = Object(token["c" /* default */])(atom_idTokens);
                    atom_nameTokenColumn = Object(token["c" /* default */])(atom_nameTokens);
                    xTokenColumn = Object(token["c" /* default */])(xTokens);
                    yTokenColumn = Object(token["c" /* default */])(yTokens);
                    zTokenColumn = Object(token["c" /* default */])(zTokens);
                    atom_typeColumn = Object(token["c" /* default */])(atom_typeTokens);
                    subst_idTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    subst_nameTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    chargeTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    status_bitTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_atoms * 2);
                    subst_idTokenColumn = Object(token["c" /* default */])(subst_idTokens);
                    subst_nameTokenColumn = Object(token["c" /* default */])(subst_nameTokens);
                    chargeTokenColumn = Object(token["c" /* default */])(chargeTokens);
                    status_bitTokenColumn = Object(token["c" /* default */])(status_bitTokens);
                    undefFloat = mol_data_db["Column"].Undefined(molecule.num_atoms, mol_data_db["Column"].Schema.float);
                    undefInt = mol_data_db["Column"].Undefined(molecule.num_atoms, mol_data_db["Column"].Schema.int);
                    undefStr = mol_data_db["Column"].Undefined(molecule.num_atoms, mol_data_db["Column"].Schema.str);
                    numOfColumn = 6;
                    if (hasSubst_id) {
                        numOfColumn++;
                    }
                    if (hasSubst_name) {
                        numOfColumn++;
                    }
                    if (hasCharge) {
                        numOfColumn++;
                    }
                    if (hasStatus_bit) {
                        numOfColumn++;
                    }
                    tokenizer.position = initialTokenizerPosition;
                    tokenizer.lineNumber = initialTokenizerLineNumber;
                    length = tokenizer.length;
                    linesAlreadyRead = 0;
                    return [4 /*yield*/, Object(mol_task["c" /* chunkedSubtask */])(state.runtimeCtx, 100000, void 0, function (chunkSize) {
                            var linesToRead = Math.min(molecule.num_atoms - linesAlreadyRead, chunkSize);
                            for (var i = 0; i < linesToRead; i++) {
                                var subst_idWritten = false;
                                var subst_nameWritten = false;
                                var chargeWritten = false;
                                var status_bitWritten = false;
                                for (var j = 0; j < numOfColumn; j++) {
                                    parser_skipWhitespace(tokenizer);
                                    tokenizer.tokenStart = tokenizer.position;
                                    parser_eatValue(tokenizer);
                                    switch (j) {
                                        case 0:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atom_idTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 1:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atom_nameTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 2:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(xTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 3:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(yTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 4:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(zTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 5:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(atom_typeTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        default:
                                            if (hasSubst_id === true && subst_idWritten === false) {
                                                text_tokenizer["a" /* TokenBuilder */].addUnchecked(subst_idTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                                subst_idWritten = true;
                                            }
                                            else if (hasSubst_name === true && subst_nameWritten === false) {
                                                text_tokenizer["a" /* TokenBuilder */].addUnchecked(subst_nameTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                                subst_nameWritten = true;
                                            }
                                            else if (hasCharge === true && chargeWritten === false) {
                                                text_tokenizer["a" /* TokenBuilder */].addUnchecked(chargeTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                                chargeWritten = true;
                                            }
                                            else if (hasStatus_bit === true && status_bitWritten === false) {
                                                text_tokenizer["a" /* TokenBuilder */].addUnchecked(status_bitTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                                status_bitWritten = true;
                                            }
                                    }
                                }
                            }
                            linesAlreadyRead += linesToRead;
                            return linesToRead;
                        }, function (ctx) { return ctx.update({ message: 'Parsing...', current: tokenizer.position, max: length }); })];
                case 1:
                    _a.sent();
                    ret = {
                        count: molecule.num_atoms,
                        atom_id: atom_idTokenColumn(mol_data_db["Column"].Schema.int),
                        atom_name: atom_nameTokenColumn(mol_data_db["Column"].Schema.str),
                        x: xTokenColumn(mol_data_db["Column"].Schema.float),
                        y: yTokenColumn(mol_data_db["Column"].Schema.float),
                        z: zTokenColumn(mol_data_db["Column"].Schema.float),
                        atom_type: atom_typeColumn(mol_data_db["Column"].Schema.str),
                        // optional columns
                        subst_id: hasSubst_id ? subst_idTokenColumn(mol_data_db["Column"].Schema.int) : undefInt,
                        subst_name: hasSubst_name ? subst_nameTokenColumn(mol_data_db["Column"].Schema.str) : undefStr,
                        charge: hasCharge ? chargeTokenColumn(mol_data_db["Column"].Schema.float) : undefFloat,
                        status_bit: hasStatus_bit ? status_bitTokenColumn(mol_data_db["Column"].Schema.str) : undefStr,
                    };
                    return [2 /*return*/, ret];
            }
        });
    });
}
function parser_handleBonds(state) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, molecule, hasStatus_bit, initialTokenizerPosition, initialTokenizerLineNumber, firstLine, firstLineArray, firstLineLength, bond_idTokens, origin_bond_idTokens, target_bond_idTokens, bondTypeTokens, bond_idTokenColumn, origin_bond_idTokenColumn, target_bond_idTokenColumn, bondTypeTokenColumn, status_bitTokens, status_bitTokenColumn, undefStr, numberOfColumn, length, linesAlreadyRead, ret;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = state.tokenizer, molecule = state.molecule;
                    hasStatus_bit = false;
                    while (getTokenString(tokenizer) !== '@<TRIPOS>BOND' && tokenizer.position < tokenizer.data.length) {
                        markLine(tokenizer);
                    }
                    initialTokenizerPosition = tokenizer.position;
                    initialTokenizerLineNumber = tokenizer.lineNumber;
                    firstLine = readLine(tokenizer);
                    firstLineArray = firstLine.trim().split(/\s+/g);
                    firstLineLength = firstLineArray.length;
                    if (firstLineLength === 5) {
                        hasStatus_bit = true;
                    }
                    bond_idTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_bonds * 2);
                    origin_bond_idTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_bonds * 2);
                    target_bond_idTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_bonds * 2);
                    bondTypeTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_bonds * 2);
                    bond_idTokenColumn = Object(token["c" /* default */])(bond_idTokens);
                    origin_bond_idTokenColumn = Object(token["c" /* default */])(origin_bond_idTokens);
                    target_bond_idTokenColumn = Object(token["c" /* default */])(target_bond_idTokens);
                    bondTypeTokenColumn = Object(token["c" /* default */])(bondTypeTokens);
                    status_bitTokens = text_tokenizer["a" /* TokenBuilder */].create(tokenizer.data, molecule.num_bonds * 2);
                    status_bitTokenColumn = Object(token["c" /* default */])(status_bitTokens);
                    undefStr = mol_data_db["Column"].Undefined(molecule.num_bonds, mol_data_db["Column"].Schema.str);
                    numberOfColumn = 4;
                    if (hasStatus_bit) {
                        numberOfColumn++;
                    }
                    tokenizer.position = initialTokenizerPosition;
                    tokenizer.lineNumber = initialTokenizerLineNumber;
                    length = tokenizer.length;
                    linesAlreadyRead = 0;
                    return [4 /*yield*/, Object(mol_task["c" /* chunkedSubtask */])(state.runtimeCtx, 100000, void 0, function (chunkSize) {
                            var linesToRead = Math.min(molecule.num_bonds - linesAlreadyRead, chunkSize);
                            for (var i = 0; i < linesToRead; i++) {
                                for (var j = 0; j < numberOfColumn; j++) {
                                    parser_skipWhitespace(tokenizer);
                                    tokenizer.tokenStart = tokenizer.position;
                                    parser_eatValue(tokenizer);
                                    switch (j) {
                                        case 0:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(bond_idTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 1:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(origin_bond_idTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 2:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(target_bond_idTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        case 3:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(bondTypeTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                        default:
                                            text_tokenizer["a" /* TokenBuilder */].addUnchecked(status_bitTokens, tokenizer.tokenStart, tokenizer.tokenEnd);
                                            break;
                                    }
                                }
                            }
                            linesAlreadyRead += linesToRead;
                            return linesToRead;
                        }, function (ctx) { return ctx.update({ message: 'Parsing...', current: tokenizer.position, max: length }); })];
                case 1:
                    _a.sent();
                    ret = {
                        count: molecule.num_bonds,
                        bond_id: bond_idTokenColumn(mol_data_db["Column"].Schema.int),
                        origin_atom_id: origin_bond_idTokenColumn(mol_data_db["Column"].Schema.int),
                        target_atom_id: target_bond_idTokenColumn(mol_data_db["Column"].Schema.int),
                        bond_type: bondTypeTokenColumn(mol_data_db["Column"].Schema.str),
                        // optional columns
                        status_bits: hasStatus_bit ? status_bitTokenColumn(mol_data_db["Column"].Schema.str) : undefStr,
                    };
                    return [2 /*return*/, ret];
            }
        });
    });
}
function mol2_parser_parseInternal(ctx, data, name) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var tokenizer, structures, state, atoms, bonds, result;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tokenizer = Object(text_tokenizer["b" /* Tokenizer */])(data);
                    ctx.update({ message: 'Parsing...', current: 0, max: data.length });
                    structures = [];
                    _a.label = 1;
                case 1:
                    if (!(tokenizer.position < data.length)) return [3 /*break*/, 4];
                    state = mol2_parser_State(tokenizer, ctx);
                    handleMolecule(state);
                    return [4 /*yield*/, mol2_parser_handleAtoms(state)];
                case 2:
                    atoms = _a.sent();
                    return [4 /*yield*/, parser_handleBonds(state)];
                case 3:
                    bonds = _a.sent();
                    structures.push({ molecule: state.molecule, atoms: atoms, bonds: bonds });
                    parser_skipWhitespace(tokenizer);
                    return [3 /*break*/, 1];
                case 4:
                    result = { name: name, structures: structures };
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success(result)];
            }
        });
    });
}
function parseMol2(data, name) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse MOL2', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, mol2_parser_parseInternal(ctx, data, name)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mol2.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








function mol2_getModels(mol2, ctx) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var models, i, il, _a, atoms, bonds, A, atom_site, entityBuilder, componentBuilder, i_1, il_1, basics, _models, indexA, indexB, order, pairBonds;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    models = [];
                    i = 0, il = mol2.structures.length;
                    _b.label = 1;
                case 1:
                    if (!(i < il)) return [3 /*break*/, 4];
                    _a = mol2.structures[i], atoms = _a.atoms, bonds = _a.bonds;
                    A = mol_data_db["Column"].ofConst('A', atoms.count, mol_data_db["Column"].Schema.str);
                    atom_site = mol_data_db["Table"].ofPartialColumns(basic_schema["a" /* BasicSchema */].atom_site, {
                        auth_asym_id: A,
                        auth_atom_id: mol_data_db["Column"].asArrayColumn(atoms.atom_type),
                        auth_comp_id: atoms.subst_name,
                        auth_seq_id: atoms.subst_id,
                        Cartn_x: mol_data_db["Column"].asArrayColumn(atoms.x, Float32Array),
                        Cartn_y: mol_data_db["Column"].asArrayColumn(atoms.y, Float32Array),
                        Cartn_z: mol_data_db["Column"].asArrayColumn(atoms.z, Float32Array),
                        id: mol_data_db["Column"].asArrayColumn(atoms.atom_id),
                        label_asym_id: A,
                        label_atom_id: mol_data_db["Column"].asArrayColumn(atoms.atom_type),
                        label_comp_id: atoms.subst_name,
                        label_seq_id: atoms.subst_id,
                        label_entity_id: mol_data_db["Column"].ofConst('1', atoms.count, mol_data_db["Column"].Schema.str),
                        occupancy: mol_data_db["Column"].ofConst(1, atoms.count, mol_data_db["Column"].Schema.float),
                        type_symbol: mol_data_db["Column"].asArrayColumn(atoms.atom_name),
                        pdbx_PDB_model_num: mol_data_db["Column"].ofConst(i, atoms.count, mol_data_db["Column"].Schema.int),
                    }, atoms.count);
                    entityBuilder = new entity_EntityBuilder();
                    entityBuilder.setNames([['MOL', 'Unknown Entity']]);
                    entityBuilder.getEntityId('MOL', 0 /* Unknown */, 'A');
                    componentBuilder = new component_ComponentBuilder(atoms.subst_id, atoms.atom_name);
                    for (i_1 = 0, il_1 = atoms.subst_name.rowCount; i_1 < il_1; ++i_1) {
                        componentBuilder.add(atoms.subst_name.value(i_1), i_1);
                    }
                    basics = Object(basic_schema["b" /* createBasic */])({
                        entity: entityBuilder.getEntityTable(),
                        chem_comp: componentBuilder.getChemCompTable(),
                        atom_site: atom_site
                    });
                    return [4 /*yield*/, Object(parser["a" /* createModels */])(basics, Mol2Format.create(mol2), ctx)];
                case 2:
                    _models = _b.sent();
                    if (_models.length > 0) {
                        indexA = mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(bonds.origin_atom_id, function (x) { return x - 1; }, Int32Array));
                        indexB = mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(bonds.target_atom_id, function (x) { return x - 1; }, Int32Array));
                        order = mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(bonds.bond_type, function (x) { return x === 'ar' ? 1 : parseInt(x); }, Int8Array));
                        pairBonds = index_pair["a" /* IndexPairBonds */].fromData({ pairs: { indexA: indexA, indexB: indexB, order: order }, count: bonds.count });
                        index_pair["a" /* IndexPairBonds */].Provider.set(_models[0], pairBonds);
                        models.push(_models[0]);
                    }
                    _b.label = 3;
                case 3:
                    ++i;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/, models];
            }
        });
    });
}
//

var Mol2Format;
(function (Mol2Format) {
    function is(x) {
        return x.kind === 'mol2';
    }
    Mol2Format.is = is;
    function create(mol2) {
        return { kind: 'mol2', name: mol2.name, data: mol2 };
    }
    Mol2Format.create = create;
})(Mol2Format || (Mol2Format = {}));
function trajectoryFromMol2(mol2) {
    return mol_task["b" /* Task */].create('Parse MOL2', function (ctx) { return mol2_getModels(mol2, ctx); });
}
//# sourceMappingURL=mol2.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-io/reader/xtc/parser.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from NGL.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var MagicInts = new Uint32Array([
    0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 10, 12, 16, 20, 25, 32, 40, 50, 64,
    80, 101, 128, 161, 203, 256, 322, 406, 512, 645, 812, 1024, 1290,
    1625, 2048, 2580, 3250, 4096, 5060, 6501, 8192, 10321, 13003,
    16384, 20642, 26007, 32768, 41285, 52015, 65536, 82570, 104031,
    131072, 165140, 208063, 262144, 330280, 416127, 524287, 660561,
    832255, 1048576, 1321122, 1664510, 2097152, 2642245, 3329021,
    4194304, 5284491, 6658042, 8388607, 10568983, 13316085, 16777216
]);
var FirstIdx = 9;
// const LastIdx = MagicInts.length
var Decoder;
(function (Decoder) {
    function sizeOfInt(size) {
        var num = 1;
        var numOfBits = 0;
        while (size >= num && numOfBits < 32) {
            numOfBits++;
            num <<= 1;
        }
        return numOfBits;
    }
    Decoder.sizeOfInt = sizeOfInt;
    var _tmpBytes = new Uint8Array(32);
    function sizeOfInts(numOfInts, sizes) {
        var numOfBytes = 1;
        var numOfBits = 0;
        _tmpBytes[0] = 1;
        for (var i = 0; i < numOfInts; i++) {
            var bytecnt = void 0;
            var tmp = 0;
            for (bytecnt = 0; bytecnt < numOfBytes; bytecnt++) {
                tmp += _tmpBytes[bytecnt] * sizes[i];
                _tmpBytes[bytecnt] = tmp & 0xff;
                tmp >>= 8;
            }
            while (tmp !== 0) {
                _tmpBytes[bytecnt++] = tmp & 0xff;
                tmp >>= 8;
            }
            numOfBytes = bytecnt;
        }
        var num = 1;
        numOfBytes--;
        while (_tmpBytes[numOfBytes] >= num) {
            numOfBits++;
            num *= 2;
        }
        return numOfBits + numOfBytes * 8;
    }
    Decoder.sizeOfInts = sizeOfInts;
    var _buffer = new ArrayBuffer(8 * 3);
    Decoder.buf = new Int32Array(_buffer);
    var uint32view = new Uint32Array(_buffer);
    function decodeBits(cbuf, offset, numOfBits1) {
        var numOfBits = numOfBits1;
        var mask = (1 << numOfBits) - 1;
        var lastBB0 = uint32view[1];
        var lastBB1 = uint32view[2];
        var cnt = Decoder.buf[0];
        var num = 0;
        while (numOfBits >= 8) {
            lastBB1 = (lastBB1 << 8) | cbuf[offset + cnt++];
            num |= (lastBB1 >> lastBB0) << (numOfBits - 8);
            numOfBits -= 8;
        }
        if (numOfBits > 0) {
            if (lastBB0 < numOfBits) {
                lastBB0 += 8;
                lastBB1 = (lastBB1 << 8) | cbuf[offset + cnt++];
            }
            lastBB0 -= numOfBits;
            num |= (lastBB1 >> lastBB0) & ((1 << numOfBits) - 1);
        }
        num &= mask;
        Decoder.buf[0] = cnt;
        Decoder.buf[1] = lastBB0;
        Decoder.buf[2] = lastBB1;
        return num;
    }
    Decoder.decodeBits = decodeBits;
    function decodeByte(cbuf, offset) {
        // special version of decodeBits with numOfBits = 8
        // const mask = 0xff; // (1 << 8) - 1;
        // let lastBB0 = uint32view[1];
        var lastBB1 = uint32view[2];
        var cnt = Decoder.buf[0];
        lastBB1 = (lastBB1 << 8) | cbuf[offset + cnt];
        Decoder.buf[0] = cnt + 1;
        // buf[1] = lastBB0;
        Decoder.buf[2] = lastBB1;
        return (lastBB1 >> uint32view[1]) & 0xff;
    }
    var intBytes = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    // new Int32Array(32);
    function decodeInts(cbuf, offset, numOfBits1, sizes, nums) {
        var numOfBits = numOfBits1;
        var numOfBytes = 0;
        intBytes[0] = 0;
        intBytes[1] = 0;
        intBytes[2] = 0;
        intBytes[3] = 0;
        while (numOfBits > 8) {
            // this is inversed??? why??? because of the endiannness???
            intBytes[numOfBytes++] = decodeByte(cbuf, offset);
            numOfBits -= 8;
        }
        if (numOfBits > 0) {
            intBytes[numOfBytes++] = decodeBits(cbuf, offset, numOfBits);
        }
        for (var i = 2; i > 0; i--) {
            var num = 0;
            var s = sizes[i];
            for (var j = numOfBytes - 1; j >= 0; j--) {
                num = (num << 8) | intBytes[j];
                var t = (num / s) | 0;
                intBytes[j] = t;
                num = num - t * s;
            }
            nums[i] = num;
        }
        nums[0] = intBytes[0] | (intBytes[1] << 8) | (intBytes[2] << 16) | (intBytes[3] << 24);
    }
    Decoder.decodeInts = decodeInts;
})(Decoder || (Decoder = {}));
function undefinedError() {
    throw new Error('(xdrfile error) Undefined error.');
}
function xtc_parser_parseInternal(ctx, data) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var dv, f, coordinates, boxes, times, minMaxInt, sizeint, bitsizeint, sizesmall, thiscoord, prevcoord, offset, buf, frameCoords, natoms, box, i, i, lfp, lsize, precision, bitsize, smallidx, tmpIdx, smaller, smallnum, adz, invPrecision, run, i, flag, isSmaller, k, tmpSwap, c;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    dv = new DataView(data.buffer, data.byteOffset);
                    f = {
                        frames: [],
                        boxes: [],
                        times: [],
                        timeOffset: 0,
                        deltaTime: 0
                    };
                    coordinates = f.frames;
                    boxes = f.boxes;
                    times = f.times;
                    minMaxInt = [0, 0, 0, 0, 0, 0];
                    sizeint = [0, 0, 0];
                    bitsizeint = [0, 0, 0];
                    sizesmall = [0, 0, 0];
                    thiscoord = [0.1, 0.1, 0.1];
                    prevcoord = [0.1, 0.1, 0.1];
                    offset = 0;
                    buf = Decoder.buf;
                    _a.label = 1;
                case 1:
                    if (false) {}
                    frameCoords = void 0;
                    natoms = dv.getInt32(offset + 4);
                    // const step = dv.getInt32(offset + 8)
                    offset += 12;
                    times.push(dv.getFloat32(offset));
                    offset += 4;
                    box = new Float32Array(9);
                    for (i = 0; i < 9; ++i) {
                        box[i] = dv.getFloat32(offset) * 10;
                        offset += 4;
                    }
                    boxes.push(box);
                    if (natoms <= 9) { // no compression
                        frameCoords = { count: natoms / 3, x: new Float32Array(natoms / 3), y: new Float32Array(natoms / 3), z: new Float32Array(natoms / 3) };
                        for (i = 0; i < natoms / 3; ++i) {
                            frameCoords.x[i] = dv.getFloat32(offset);
                            frameCoords.y[i] = dv.getFloat32(offset);
                            frameCoords.z[i] = dv.getFloat32(offset);
                            offset += 4;
                        }
                    }
                    else {
                        buf[0] = buf[1] = buf[2] = 0;
                        sizeint[0] = sizeint[1] = sizeint[2] = 0;
                        sizesmall[0] = sizesmall[1] = sizesmall[2] = 0;
                        bitsizeint[0] = bitsizeint[1] = bitsizeint[2] = 0;
                        thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                        prevcoord[0] = prevcoord[1] = prevcoord[2] = 0;
                        frameCoords = { count: natoms, x: new Float32Array(natoms), y: new Float32Array(natoms), z: new Float32Array(natoms) };
                        lfp = 0;
                        lsize = dv.getInt32(offset);
                        offset += 4;
                        precision = dv.getFloat32(offset);
                        offset += 4;
                        minMaxInt[0] = dv.getInt32(offset);
                        minMaxInt[1] = dv.getInt32(offset + 4);
                        minMaxInt[2] = dv.getInt32(offset + 8);
                        minMaxInt[3] = dv.getInt32(offset + 12);
                        minMaxInt[4] = dv.getInt32(offset + 16);
                        minMaxInt[5] = dv.getInt32(offset + 20);
                        sizeint[0] = minMaxInt[3] - minMaxInt[0] + 1;
                        sizeint[1] = minMaxInt[4] - minMaxInt[1] + 1;
                        sizeint[2] = minMaxInt[5] - minMaxInt[2] + 1;
                        offset += 24;
                        bitsize = void 0;
                        if ((sizeint[0] | sizeint[1] | sizeint[2]) > 0xffffff) {
                            bitsizeint[0] = Decoder.sizeOfInt(sizeint[0]);
                            bitsizeint[1] = Decoder.sizeOfInt(sizeint[1]);
                            bitsizeint[2] = Decoder.sizeOfInt(sizeint[2]);
                            bitsize = 0; // flag the use of large sizes
                        }
                        else {
                            bitsize = Decoder.sizeOfInts(3, sizeint);
                        }
                        smallidx = dv.getInt32(offset);
                        offset += 4;
                        tmpIdx = smallidx - 1;
                        tmpIdx = (FirstIdx > tmpIdx) ? FirstIdx : tmpIdx;
                        smaller = (MagicInts[tmpIdx] / 2) | 0;
                        smallnum = (MagicInts[smallidx] / 2) | 0;
                        sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx];
                        adz = Math.ceil(dv.getInt32(offset) / 4) * 4;
                        offset += 4;
                        invPrecision = 1.0 / precision;
                        run = 0;
                        i = 0;
                        // const buf8 = new Uint8Array(data.buffer, data.byteOffset + offset, 32 * 4); // 229...
                        thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                        while (i < lsize) {
                            if (bitsize === 0) {
                                thiscoord[0] = Decoder.decodeBits(data, offset, bitsizeint[0]);
                                thiscoord[1] = Decoder.decodeBits(data, offset, bitsizeint[1]);
                                thiscoord[2] = Decoder.decodeBits(data, offset, bitsizeint[2]);
                            }
                            else {
                                Decoder.decodeInts(data, offset, bitsize, sizeint, thiscoord);
                            }
                            i++;
                            thiscoord[0] += minMaxInt[0];
                            thiscoord[1] += minMaxInt[1];
                            thiscoord[2] += minMaxInt[2];
                            prevcoord[0] = thiscoord[0];
                            prevcoord[1] = thiscoord[1];
                            prevcoord[2] = thiscoord[2];
                            flag = Decoder.decodeBits(data, offset, 1);
                            isSmaller = 0;
                            if (flag === 1) {
                                run = Decoder.decodeBits(data, offset, 5);
                                isSmaller = run % 3;
                                run -= isSmaller;
                                isSmaller--;
                            }
                            // if ((lfp-ptrstart)+run > size3){
                            //   fprintf(stderr, "(xdrfile error) Buffer overrun during decompression.\n");
                            //   return 0;
                            // }
                            if (run > 0) {
                                thiscoord[0] = thiscoord[1] = thiscoord[2] = 0;
                                for (k = 0; k < run; k += 3) {
                                    Decoder.decodeInts(data, offset, smallidx, sizesmall, thiscoord);
                                    i++;
                                    thiscoord[0] += prevcoord[0] - smallnum;
                                    thiscoord[1] += prevcoord[1] - smallnum;
                                    thiscoord[2] += prevcoord[2] - smallnum;
                                    if (k === 0) {
                                        tmpSwap = thiscoord[0];
                                        thiscoord[0] = prevcoord[0];
                                        prevcoord[0] = tmpSwap;
                                        tmpSwap = thiscoord[1];
                                        thiscoord[1] = prevcoord[1];
                                        prevcoord[1] = tmpSwap;
                                        tmpSwap = thiscoord[2];
                                        thiscoord[2] = prevcoord[2];
                                        prevcoord[2] = tmpSwap;
                                        frameCoords.x[lfp] = prevcoord[0] * invPrecision;
                                        frameCoords.y[lfp] = prevcoord[1] * invPrecision;
                                        frameCoords.z[lfp] = prevcoord[2] * invPrecision;
                                        lfp++;
                                    }
                                    else {
                                        prevcoord[0] = thiscoord[0];
                                        prevcoord[1] = thiscoord[1];
                                        prevcoord[2] = thiscoord[2];
                                    }
                                    frameCoords.x[lfp] = thiscoord[0] * invPrecision;
                                    frameCoords.y[lfp] = thiscoord[1] * invPrecision;
                                    frameCoords.z[lfp] = thiscoord[2] * invPrecision;
                                    lfp++;
                                }
                            }
                            else {
                                frameCoords.x[lfp] = thiscoord[0] * invPrecision;
                                frameCoords.y[lfp] = thiscoord[1] * invPrecision;
                                frameCoords.z[lfp] = thiscoord[2] * invPrecision;
                                lfp++;
                            }
                            smallidx += isSmaller;
                            if (isSmaller < 0) {
                                smallnum = smaller;
                                if (smallidx > FirstIdx) {
                                    smaller = (MagicInts[smallidx - 1] / 2) | 0;
                                }
                                else {
                                    smaller = 0;
                                }
                            }
                            else if (isSmaller > 0) {
                                smaller = smallnum;
                                smallnum = (MagicInts[smallidx] / 2) | 0;
                            }
                            sizesmall[0] = sizesmall[1] = sizesmall[2] = MagicInts[smallidx];
                            if (sizesmall[0] === 0 || sizesmall[1] === 0 || sizesmall[2] === 0) {
                                undefinedError();
                            }
                        }
                        offset += adz;
                    }
                    for (c = 0; c < natoms; c++) {
                        frameCoords.x[c] *= 10;
                        frameCoords.y[c] *= 10;
                        frameCoords.z[c] *= 10;
                    }
                    coordinates.push(frameCoords);
                    if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                    return [4 /*yield*/, ctx.update({ current: offset, max: data.length })];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    if (offset >= data.length)
                        return [3 /*break*/, 4];
                    return [3 /*break*/, 1];
                case 4:
                    if (times.length >= 1) {
                        f.timeOffset = times[0];
                    }
                    if (times.length >= 2) {
                        f.deltaTime = times[1] - times[0];
                    }
                    return [2 /*return*/, f];
            }
        });
    });
}
function parseXtc(data) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse XTC', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var file, e_1;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 2, , 3]);
                    ctx.update({ canAbort: true, message: 'Parsing trajectory...' });
                    return [4 /*yield*/, xtc_parser_parseInternal(ctx, data)];
                case 1:
                    file = _a.sent();
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].success(file)];
                case 2:
                    e_1 = _a.sent();
                    return [2 /*return*/, reader_result["a" /* ReaderResult */].error('' + e_1)];
                case 3: return [2 /*return*/];
            }
        });
    }); });
}
//# sourceMappingURL=parser.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/xtc.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




function coordinatesFromXtc(file) {
    var _this = this;
    return mol_task["b" /* Task */].create('Parse XTC', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        var deltaTime, offsetTime, frames, i, il;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, ctx.update('Converting to coordinates')];
                case 1:
                    _a.sent();
                    deltaTime = Object(structure_coordinates["b" /* Time */])(file.deltaTime, 'step');
                    offsetTime = Object(structure_coordinates["b" /* Time */])(file.timeOffset, deltaTime.unit);
                    frames = [];
                    for (i = 0, il = file.frames.length; i < il; ++i) {
                        frames.push({
                            elementCount: file.frames[i].count,
                            // TODO:
                            cell: cell_Cell.empty(),
                            x: file.frames[i].x,
                            y: file.frames[i].y,
                            z: file.frames[i].z,
                            time: Object(structure_coordinates["b" /* Time */])(offsetTime.value + deltaTime.value * i, deltaTime.unit)
                        });
                    }
                    return [2 /*return*/, structure_coordinates["a" /* Coordinates */].create(frames, deltaTime, offsetTime)];
            }
        });
    }); });
}
//# sourceMappingURL=xtc.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/model.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



























































var CoordinatesFromDcd = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'coordinates-from-dcd',
    display: { name: 'Parse DCD', description: 'Parse DCD binary data.' },
    from: [objects["a" /* PluginStateObject */].Data.Binary],
    to: objects["a" /* PluginStateObject */].Molecule.Coordinates
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse DCD', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, coordinates;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseDcd(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, coordinatesFromDcd(parsed.result).runInContext(ctx)];
                    case 2:
                        coordinates = _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' })];
                }
            });
        }); });
    }
});
var CoordinatesFromXtc = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'coordinates-from-xtc',
    display: { name: 'Parse XTC', description: 'Parse XTC binary data.' },
    from: [objects["a" /* PluginStateObject */].Data.Binary],
    to: objects["a" /* PluginStateObject */].Molecule.Coordinates
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse XTC', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, coordinates;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseXtc(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, coordinatesFromXtc(parsed.result).runInContext(ctx)];
                    case 2:
                        coordinates = _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Coordinates(coordinates, { label: a.label, description: 'Coordinates' })];
                }
            });
        }); });
    }
});
var TopologyFromPsf = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'topology-from-psf',
    display: { name: 'PSF Topology', description: 'Parse PSF string data.' },
    from: [objects["a" /* PluginStateObject */].Format.Psf],
    to: objects["a" /* PluginStateObject */].Molecule.Topology
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Create Topology', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var topology;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, topologyFromPsf(a.data).runInContext(ctx)];
                    case 1:
                        topology = _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Topology(topology, { label: topology.label || a.label, description: 'Topology' })];
                }
            });
        }); });
    }
});
function getTrajectory(ctx, obj, coordinates) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var topology, model;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!(obj.type === objects["a" /* PluginStateObject */].Molecule.Topology.type)) return [3 /*break*/, 2];
                    topology = obj.data;
                    return [4 /*yield*/, mol_model_structure["Model"].trajectoryFromTopologyAndCoordinates(topology, coordinates).runInContext(ctx)];
                case 1: return [2 /*return*/, _a.sent()];
                case 2:
                    if (obj.type === objects["a" /* PluginStateObject */].Molecule.Model.type) {
                        model = obj.data;
                        return [2 /*return*/, mol_model_structure["Model"].trajectoryFromModelAndCoordinates(model, coordinates)];
                    }
                    _a.label = 3;
                case 3: throw new Error('no model/topology found');
            }
        });
    });
}
var TrajectoryFromModelAndCoordinates = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-model-and-coordinates',
    display: { name: 'Trajectory from Topology & Coordinates', description: 'Create a trajectory from existing model/topology and coordinates.' },
    from: objects["a" /* PluginStateObject */].Root,
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory,
    params: {
        modelRef: param_definition["ParamDefinition"].Text('', { isHidden: true }),
        coordinatesRef: param_definition["ParamDefinition"].Text('', { isHidden: true }),
    }
})({
    apply: function (_a) {
        var _this = this;
        var params = _a.params, dependencies = _a.dependencies;
        return mol_task["b" /* Task */].create('Create trajectory from model/topology and coordinates', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var coordinates, trajectory, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        coordinates = dependencies[params.coordinatesRef].data;
                        return [4 /*yield*/, getTrajectory(ctx, dependencies[params.modelRef], coordinates)];
                    case 1:
                        trajectory = _a.sent();
                        props = { label: 'Trajectory', description: trajectory.length + " model" + (trajectory.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(trajectory, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromBlob = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-blob',
    display: { name: 'Parse Blob', description: 'Parse format blob into a single trajectory.' },
    from: objects["a" /* PluginStateObject */].Format.Blob,
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse Format Blob', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var models, _i, _a, e, block, xs, _b, xs_1, x, props;
            return Object(tslib_es6["__generator"])(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        models = [];
                        _i = 0, _a = a.data;
                        _c.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        e = _a[_i];
                        if (e.kind !== 'cif')
                            return [3 /*break*/, 3];
                        block = e.data.blocks[0];
                        return [4 /*yield*/, Object(mmcif["trajectoryFromMmCIF"])(block).runInContext(ctx)];
                    case 2:
                        xs = _c.sent();
                        if (xs.length === 0)
                            throw new Error('No models found.');
                        for (_b = 0, xs_1 = xs; _b < xs_1.length; _b++) {
                            x = xs_1[_b];
                            models.push(x);
                        }
                        _c.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4:
                        props = { label: 'Trajectory', description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromMmCif = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-mmcif',
    display: { name: 'Trajectory from mmCIF', description: 'Identify and create all separate models in the specified CIF data block' },
    from: objects["a" /* PluginStateObject */].Format.Cif,
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory,
    params: function (a) {
        if (!a) {
            return {
                blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.' }))
            };
        }
        var blocks = a.data.blocks;
        return {
            blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Select(blocks[0] && blocks[0].header, blocks.map(function (b) { return [b.header, b.header]; }), { description: 'Header of the block to parse' }))
        };
    }
})({
    isApplicable: function (a) { return a.data.blocks.length > 0; },
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Parse mmCIF', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var header, block, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        header = params.blockHeader || a.data.blocks[0].header;
                        block = a.data.blocks.find(function (b) { return b.header === header; });
                        if (!block)
                            throw new Error("Data block '" + [header] + "' not found.");
                        return [4 /*yield*/, Object(mmcif["trajectoryFromMmCIF"])(block).runInContext(ctx)];
                    case 1:
                        models = _a.sent();
                        if (models.length === 0)
                            throw new Error('No models found.');
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromPDB = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-pdb',
    display: { name: 'Parse PDB', description: 'Parse PDB string and create trajectory.' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse PDB', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parsePDB(a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, trajectoryFromPDB(parsed.result).runInContext(ctx)];
                    case 2:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromGRO = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-gro',
    display: { name: 'Parse GRO', description: 'Parse GRO string and create trajectory.' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse GRO', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseGRO(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, trajectoryFromGRO(parsed.result).runInContext(ctx)];
                    case 2:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromMOL = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-mol',
    display: { name: 'Parse MOL', description: 'Parse MOL string and create trajectory.' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse MOL', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseMol(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, trajectoryFromMol(parsed.result).runInContext(ctx)];
                    case 2:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromMOL2 = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-mol2',
    display: { name: 'Parse MOL2', description: 'Parse MOL2 string and create trajectory.' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse MOL2', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parseMol2(a.data, a.label).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, trajectoryFromMol2(parsed.result).runInContext(ctx)];
                    case 2:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromCube = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-cube',
    display: { name: 'Parse Cube', description: 'Parse Cube file to create a trajectory.' },
    from: objects["a" /* PluginStateObject */].Format.Cube,
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse MOL', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, trajectoryFromCube(a.data).runInContext(ctx)];
                    case 1:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFromCifCore = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-cif-core',
    display: { name: 'Parse CIF Core', description: 'Identify and create all separate models in the specified CIF data block' },
    from: objects["a" /* PluginStateObject */].Format.Cif,
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory,
    params: function (a) {
        if (!a) {
            return {
                blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(void 0, { description: 'Header of the block to parse. If none is specifed, the 1st data block in the file is used.' }))
            };
        }
        var blocks = a.data.blocks;
        return {
            blockHeader: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Select(blocks[0] && blocks[0].header, blocks.map(function (b) { return [b.header, b.header]; }), { description: 'Header of the block to parse' }))
        };
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Parse CIF Core', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var header, block, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        header = params.blockHeader || a.data.blocks[0].header;
                        block = a.data.blocks.find(function (b) { return b.header === header; });
                        if (!block)
                            throw new Error("Data block '" + [header] + "' not found.");
                        return [4 /*yield*/, trajectoryFromCifCore(block).runInContext(ctx)];
                    case 1:
                        models = _a.sent();
                        if (models.length === 0)
                            throw new Error('No models found.');
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var TrajectoryFrom3DG = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'trajectory-from-3dg',
    display: { name: 'Parse 3DG', description: 'Parse 3DG string and create trajectory.' },
    from: [objects["a" /* PluginStateObject */].Data.String],
    to: objects["a" /* PluginStateObject */].Molecule.Trajectory
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Parse 3DG', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var parsed, models, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, parse3DG(a.data).runInContext(ctx)];
                    case 1:
                        parsed = _a.sent();
                        if (parsed.isError)
                            throw new Error(parsed.message);
                        return [4 /*yield*/, trajectoryFrom3DG(parsed.result).runInContext(ctx)];
                    case 2:
                        models = _a.sent();
                        props = { label: "" + models[0].entry, description: models.length + " model" + (models.length === 1 ? '' : 's') };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Trajectory(models, props)];
                }
            });
        }); });
    }
});
var plus1 = function (v) { return v + 1; }, minus1 = function (v) { return v - 1; };
var ModelFromTrajectory = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'model-from-trajectory',
    display: { name: 'Molecular Model', description: 'Create a molecular model from specified index in a trajectory.' },
    from: objects["a" /* PluginStateObject */].Molecule.Trajectory,
    to: objects["a" /* PluginStateObject */].Molecule.Model,
    params: function (a) {
        if (!a) {
            return { modelIndex: param_definition["ParamDefinition"].Numeric(0, {}, { description: 'Zero-based index of the model' }) };
        }
        return { modelIndex: param_definition["ParamDefinition"].Converted(plus1, minus1, param_definition["ParamDefinition"].Numeric(1, { min: 1, max: a.data.length, step: 1 }, { description: 'Model Index' })) };
    }
})({
    isApplicable: function (a) { return a.data.length > 0; },
    apply: function (_a) {
        var a = _a.a, params = _a.params;
        var modelIndex = params.modelIndex % a.data.length;
        if (modelIndex < 0)
            modelIndex += a.data.length;
        var model = a.data[params.modelIndex];
        var label = "Model " + model.modelNum;
        var description = a.data.length === 1 ? undefined : "of " + a.data.length;
        return new objects["a" /* PluginStateObject */].Molecule.Model(model, { label: label, description: description });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customProperties.dispose();
    }
});
var StructureFromTrajectory = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-from-trajectory',
    display: { name: 'Structure from Trajectory', description: 'Create a molecular structure from a trajectory.' },
    from: objects["a" /* PluginStateObject */].Molecule.Trajectory,
    to: objects["a" /* PluginStateObject */].Molecule.Structure
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a;
        return mol_task["b" /* Task */].create('Build Structure', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var s, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                s = mol_model_structure["Structure"].ofTrajectory(a.data);
                props = { label: 'Ensemble', description: mol_model_structure["Structure"].elementDescription(s) };
                return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Structure(s, props)];
            });
        }); });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var StructureFromModel = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-from-model',
    display: { name: 'Structure', description: 'Create a molecular structure (model, assembly, or symmetry) from the specified model.' },
    from: objects["a" /* PluginStateObject */].Molecule.Model,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: function (a) { return root_structure["a" /* RootStructureDefinition */].getParams(a && a.data); }
})({
    canAutoUpdate: function (_a) {
        var oldParams = _a.oldParams, newParams = _a.newParams;
        return root_structure["a" /* RootStructureDefinition */].canAutoUpdate(oldParams.type, newParams.type);
    },
    apply: function (_a, plugin) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Build Structure', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                return [2 /*return*/, root_structure["a" /* RootStructureDefinition */].create(plugin, ctx, a.data, params && params.type)];
            });
        }); });
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        if (!b.data.models.includes(a.data))
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        if (!Object(mol_util["h" /* deepEqual */])(oldParams, newParams))
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        return mol_state["StateTransformer"].UpdateResult.Unchanged;
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var _translation = Object(linear_algebra["Vec3"])(), _m = Object(linear_algebra["Mat4"])(), _n = Object(linear_algebra["Mat4"])();
var TransformStructureConformation = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'transform-structure-conformation',
    display: { name: 'Transform Conformation' },
    isDecorator: true,
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: {
        transform: param_definition["ParamDefinition"].MappedStatic('components', {
            components: param_definition["ParamDefinition"].Group({
                axis: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(1, 0, 0)),
                angle: param_definition["ParamDefinition"].Numeric(0, { min: -180, max: 180, step: 0.1 }),
                translation: param_definition["ParamDefinition"].Vec3(linear_algebra["Vec3"].create(0, 0, 0)),
            }, { isFlat: true }),
            matrix: param_definition["ParamDefinition"].Group({
                data: param_definition["ParamDefinition"].Mat4(linear_algebra["Mat4"].identity()),
                transpose: param_definition["ParamDefinition"].Boolean(false)
            }, { isFlat: true })
        }, { label: 'Kind' })
    }
})({
    canAutoUpdate: function (_a) {
        var newParams = _a.newParams;
        return newParams.transform.name !== 'matrix';
    },
    apply: function (_a) {
        // TODO: optimze
        // TODO: think of ways how to fast-track changes to this for animations
        var a = _a.a, params = _a.params;
        var transform = Object(linear_algebra["Mat4"])();
        if (params.transform.name === 'components') {
            var _b = params.transform.params, axis = _b.axis, angle = _b.angle, translation = _b.translation;
            var center = a.data.boundary.sphere.center;
            linear_algebra["Mat4"].fromTranslation(_m, linear_algebra["Vec3"].negate(_translation, center));
            linear_algebra["Mat4"].fromTranslation(_n, linear_algebra["Vec3"].add(_translation, center, translation));
            var rot = linear_algebra["Mat4"].fromRotation(Object(linear_algebra["Mat4"])(), Math.PI / 180 * angle, linear_algebra["Vec3"].normalize(Object(linear_algebra["Vec3"])(), axis));
            linear_algebra["Mat4"].mul3(transform, _n, rot, _m);
        }
        else if (params.transform.name === 'matrix') {
            linear_algebra["Mat4"].copy(transform, params.transform.params.data);
            if (params.transform.params.transpose)
                linear_algebra["Mat4"].transpose(transform, transform);
        }
        var s = mol_model_structure["Structure"].transform(a.data, transform);
        return new objects["a" /* PluginStateObject */].Molecule.Structure(s, { label: a.label, description: a.description + " [Transformed]" });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
    // interpolate(src, tar, t) {
    //     // TODO: optimize
    //     const u = Mat4.fromRotation(Mat4(), Math.PI / 180 * src.angle, Vec3.normalize(Vec3(), src.axis));
    //     Mat4.setTranslation(u, src.translation);
    //     const v = Mat4.fromRotation(Mat4(), Math.PI / 180 * tar.angle, Vec3.normalize(Vec3(), tar.axis));
    //     Mat4.setTranslation(v, tar.translation);
    //     const m = SymmetryOperator.slerp(Mat4(), u, v, t);
    //     const rot = Mat4.getRotation(Quat.zero(), m);
    //     const axis = Vec3();
    //     const angle = Quat.getAxisAngle(axis, rot);
    //     const translation = Mat4.getTranslation(Vec3(), m);
    //     return { axis, angle, translation };
    // }
});
var StructureSelectionFromExpression = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selection-from-expression',
    display: { name: 'Selection', description: 'Create a molecular structure from the specified expression.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: {
        expression: param_definition["ParamDefinition"].Value(builder["MolScriptBuilder"].struct.generator.all, { isHidden: true }),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('', { isHidden: true }))
    }
})({
    apply: function (_a) {
        var a = _a.a, params = _a.params, cache = _a.cache;
        var _b = structure_query_StructureQueryHelper.createAndRun(a.data, params.expression), selection = _b.selection, entry = _b.entry;
        cache.entry = entry;
        if (mol_model_structure["StructureSelection"].isEmpty(selection))
            return mol_state["StateObject"].Null;
        var s = mol_model_structure["StructureSelection"].unionStructure(selection);
        var props = { label: "" + (params.label || 'Selection'), description: mol_model_structure["Structure"].elementDescription(s) };
        return new objects["a" /* PluginStateObject */].Molecule.Structure(s, props);
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache;
        if (oldParams.expression !== newParams.expression)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var entry = cache.entry;
        if (entry.currentStructure === a.data) {
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        }
        var selection = structure_query_StructureQueryHelper.updateStructure(entry, a.data);
        if (mol_model_structure["StructureSelection"].isEmpty(selection))
            return mol_state["StateTransformer"].UpdateResult.Null;
        structure_query_StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
        return mol_state["StateTransformer"].UpdateResult.Updated;
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var MultiStructureSelectionFromExpression = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-multi-selection-from-expression',
    display: { name: 'Multi-structure Measurement Selection', description: 'Create selection object from multiple structures.' },
    from: objects["a" /* PluginStateObject */].Root,
    to: objects["a" /* PluginStateObject */].Molecule.Structure.Selections,
    params: {
        selections: param_definition["ParamDefinition"].ObjectList({
            key: param_definition["ParamDefinition"].Text(void 0, { description: 'A unique key.' }),
            ref: param_definition["ParamDefinition"].Text(),
            groupId: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text()),
            expression: param_definition["ParamDefinition"].Value(builder["MolScriptBuilder"].struct.generator.empty)
        }, function (e) { return e.ref; }, { isHidden: true }),
        isTransitive: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false, { isHidden: true, description: 'Remap the selections from the original structure if structurally equivalent.' })),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('', { isHidden: true }))
    }
})({
    apply: function (_a) {
        var params = _a.params, cache = _a.cache, dependencies = _a.dependencies;
        var entries = new Map();
        var selections = [];
        var totalSize = 0;
        for (var _i = 0, _b = params.selections; _i < _b.length; _i++) {
            var sel = _b[_i];
            var _c = structure_query_StructureQueryHelper.createAndRun(dependencies[sel.ref].data, sel.expression), selection = _c.selection, entry = _c.entry;
            entries.set(sel.key, entry);
            var loci = mol_model_structure["StructureSelection"].toLociWithSourceUnits(selection);
            selections.push({ key: sel.key, loci: loci, groupId: sel.groupId });
            totalSize += mol_model_structure["StructureElement"].Loci.size(loci);
        }
        cache.entries = entries;
        var props = { label: "" + (params.label || 'Multi-selection'), description: params.selections.length + " source(s), " + totalSize + " element(s) total" };
        return new objects["a" /* PluginStateObject */].Molecule.Structure.Selections(selections, props);
    },
    update: function (_a) {
        var b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache, dependencies = _a.dependencies;
        if (!!oldParams.isTransitive !== !!newParams.isTransitive)
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        var cacheEntries = cache.entries;
        var entries = new Map();
        var current = new Map();
        for (var _i = 0, _b = b.data; _i < _b.length; _i++) {
            var e = _b[_i];
            current.set(e.key, e);
        }
        var changed = false;
        var totalSize = 0;
        var selections = [];
        for (var _c = 0, _d = newParams.selections; _c < _d.length; _c++) {
            var sel = _d[_c];
            var structure = dependencies[sel.ref].data;
            var recreate = false;
            if (cacheEntries.has(sel.key)) {
                var entry = cacheEntries.get(sel.key);
                if (structure_query_StructureQueryHelper.isUnchanged(entry, sel.expression, structure) && current.has(sel.key)) {
                    var loci = current.get(sel.key);
                    if (loci.groupId !== sel.groupId) {
                        loci.groupId = sel.groupId;
                        changed = true;
                    }
                    entries.set(sel.key, entry);
                    selections.push(loci);
                    totalSize += mol_model_structure["StructureElement"].Loci.size(loci.loci);
                    continue;
                }
                if (entry.expression !== sel.expression) {
                    recreate = true;
                }
                else {
                    // TODO: properly support "transitive" queries. For that Structure.areUnitAndIndicesEqual needs to be fixed;
                    var update = false;
                    if (!!newParams.isTransitive) {
                        if (mol_model_structure["Structure"].areUnitAndIndicesEqual(entry.originalStructure, structure)) {
                            var selection = structure_query_StructureQueryHelper.run(entry, entry.originalStructure);
                            entry.currentStructure = structure;
                            entries.set(sel.key, entry);
                            var loci = mol_model_structure["StructureElement"].Loci.remap(mol_model_structure["StructureSelection"].toLociWithSourceUnits(selection), structure);
                            selections.push({ key: sel.key, loci: loci, groupId: sel.groupId });
                            totalSize += mol_model_structure["StructureElement"].Loci.size(loci);
                            changed = true;
                        }
                        else {
                            update = true;
                        }
                    }
                    else {
                        update = true;
                    }
                    if (update) {
                        changed = true;
                        var selection = structure_query_StructureQueryHelper.updateStructure(entry, structure);
                        entries.set(sel.key, entry);
                        var loci = mol_model_structure["StructureSelection"].toLociWithSourceUnits(selection);
                        selections.push({ key: sel.key, loci: loci, groupId: sel.groupId });
                        totalSize += mol_model_structure["StructureElement"].Loci.size(loci);
                    }
                }
            }
            else {
                recreate = true;
            }
            if (recreate) {
                changed = true;
                // create new selection
                var _e = structure_query_StructureQueryHelper.createAndRun(structure, sel.expression), selection = _e.selection, entry = _e.entry;
                entries.set(sel.key, entry);
                var loci = mol_model_structure["StructureSelection"].toLociWithSourceUnits(selection);
                selections.push({ key: sel.key, loci: loci });
                totalSize += mol_model_structure["StructureElement"].Loci.size(loci);
            }
        }
        if (!changed)
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        cache.entries = entries;
        b.data = selections;
        b.label = "" + (newParams.label || 'Multi-selection');
        b.description = selections.length + " source(s), " + totalSize + " element(s) total";
        return mol_state["StateTransformer"].UpdateResult.Updated;
    }
});
var StructureSelectionFromScript = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selection-from-script',
    display: { name: 'Selection', description: 'Create a molecular structure from the specified script.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: {
        script: param_definition["ParamDefinition"].Script({ language: 'mol-script', expression: '(sel.atom.atom-groups :residue-test (= atom.resname ALA))' }),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text(''))
    }
})({
    apply: function (_a) {
        var a = _a.a, params = _a.params, cache = _a.cache;
        var _b = structure_query_StructureQueryHelper.createAndRun(a.data, params.script), selection = _b.selection, entry = _b.entry;
        cache.entry = entry;
        var s = mol_model_structure["StructureSelection"].unionStructure(selection);
        var props = { label: "" + (params.label || 'Selection'), description: mol_model_structure["Structure"].elementDescription(s) };
        return new objects["a" /* PluginStateObject */].Molecule.Structure(s, props);
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache;
        if (!mol_script_script["Script"].areEqual(oldParams.script, newParams.script)) {
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        }
        var entry = cache.entry;
        if (entry.currentStructure === a.data) {
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        }
        var selection = structure_query_StructureQueryHelper.updateStructure(entry, a.data);
        structure_query_StructureQueryHelper.updateStructureObject(b, selection, newParams.label);
        return mol_state["StateTransformer"].UpdateResult.Updated;
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var StructureSelectionFromBundle = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-selection-from-bundle',
    display: { name: 'Selection', description: 'Create a molecular structure from the specified structure-element bundle.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: {
        bundle: param_definition["ParamDefinition"].Value(mol_model_structure["StructureElement"].Bundle.Empty, { isHidden: true }),
        label: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('', { isHidden: true }))
    }
})({
    apply: function (_a) {
        var a = _a.a, params = _a.params, cache = _a.cache;
        if (params.bundle.hash !== a.data.hashCode) {
            return mol_state["StateObject"].Null;
        }
        cache.source = a.data;
        var s = mol_model_structure["StructureElement"].Bundle.toStructure(params.bundle, a.data);
        if (s.elementCount === 0)
            return mol_state["StateObject"].Null;
        var props = { label: "" + (params.label || 'Selection'), description: mol_model_structure["Structure"].elementDescription(s) };
        return new objects["a" /* PluginStateObject */].Molecule.Structure(s, props);
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache;
        if (!mol_model_structure["StructureElement"].Bundle.areEqual(oldParams.bundle, newParams.bundle)) {
            return mol_state["StateTransformer"].UpdateResult.Recreate;
        }
        if (newParams.bundle.hash !== a.data.hashCode) {
            return mol_state["StateTransformer"].UpdateResult.Null;
        }
        if (cache.source === a.data) {
            return mol_state["StateTransformer"].UpdateResult.Unchanged;
        }
        cache.source = a.data;
        var s = mol_model_structure["StructureElement"].Bundle.toStructure(newParams.bundle, a.data);
        if (s.elementCount === 0)
            return mol_state["StateTransformer"].UpdateResult.Null;
        b.label = "" + (newParams.label || 'Selection');
        b.description = mol_model_structure["Structure"].elementDescription(s);
        b.data = s;
        return mol_state["StateTransformer"].UpdateResult.Updated;
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var StructureComplexElementTypes = {
    'polymer': 'polymer',
    'protein': 'protein',
    'nucleic': 'nucleic',
    'water': 'water',
    'branched': 'branched',
    'ligand': 'ligand',
    'non-standard': 'non-standard',
    'coarse': 'coarse',
    // Legacy
    'atomic-sequence': 'atomic-sequence',
    'atomic-het': 'atomic-het',
    'spheres': 'spheres'
};
var StructureComplexElementTypeTuples = param_definition["ParamDefinition"].objectToOptions(StructureComplexElementTypes);
var StructureComplexElement = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-complex-element',
    display: { name: 'Complex Element', description: 'Create a molecular structure from the specified model.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: { type: param_definition["ParamDefinition"].Select('atomic-sequence', StructureComplexElementTypeTuples, { isHidden: true }) }
})({
    apply: function (_a) {
        // TODO: update function.
        var a = _a.a, params = _a.params;
        var query, label;
        switch (params.type) {
            case 'polymer':
                query = structure_selection_query["b" /* StructureSelectionQueries */].polymer.query;
                label = 'Polymer';
                break;
            case 'protein':
                query = structure_selection_query["b" /* StructureSelectionQueries */].protein.query;
                label = 'Protein';
                break;
            case 'nucleic':
                query = structure_selection_query["b" /* StructureSelectionQueries */].nucleic.query;
                label = 'Nucleic';
                break;
            case 'water':
                query = mol_model_structure["Queries"].internal.water();
                label = 'Water';
                break;
            case 'branched':
                query = structure_selection_query["b" /* StructureSelectionQueries */].branchedPlusConnected.query;
                label = 'Branched';
                break;
            case 'ligand':
                query = structure_selection_query["b" /* StructureSelectionQueries */].ligandPlusConnected.query;
                label = 'Ligand';
                break;
            case 'non-standard':
                query = structure_selection_query["b" /* StructureSelectionQueries */].nonStandardPolymer.query;
                label = 'Non-standard';
                break;
            case 'coarse':
                query = structure_selection_query["b" /* StructureSelectionQueries */].coarse.query;
                label = 'Coarse';
                break;
            case 'atomic-sequence':
                query = mol_model_structure["Queries"].internal.atomicSequence();
                label = 'Sequence';
                break;
            case 'atomic-het':
                query = mol_model_structure["Queries"].internal.atomicHet();
                label = 'HET Groups/Ligands';
                break;
            case 'spheres':
                query = mol_model_structure["Queries"].internal.spheres();
                label = 'Coarse Spheres';
                break;
            default: throw new Error(params.type + " is a not valid complex element.");
        }
        var result = query(new mol_model_structure["QueryContext"](a.data));
        var s = mol_model_structure["StructureSelection"].unionStructure(result);
        if (s.elementCount === 0)
            return mol_state["StateObject"].Null;
        return new objects["a" /* PluginStateObject */].Molecule.Structure(s, { label: label, description: mol_model_structure["Structure"].elementDescription(s) });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var StructureComponent = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'structure-component',
    display: { name: 'Component', description: 'A molecular structure component.' },
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: StructureComponentParams
})({
    apply: function (_a) {
        var a = _a.a, params = _a.params, cache = _a.cache;
        return createStructureComponent(a.data, params, cache);
    },
    update: function (_a) {
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams, cache = _a.cache;
        return updateStructureComponent(a.data, b, oldParams, newParams, cache);
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
var CustomModelProperties = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'custom-model-properties',
    display: { name: 'Custom Model Properties' },
    isDecorator: true,
    from: objects["a" /* PluginStateObject */].Molecule.Model,
    to: objects["a" /* PluginStateObject */].Molecule.Model,
    params: function (a, ctx) {
        return ctx.customModelProperties.getParams(a === null || a === void 0 ? void 0 : a.data);
    }
})({
    apply: function (_a, ctx) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Custom Props', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, attachModelProps(a.data, ctx, taskCtx, params)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Model(a.data, { label: a.label, description: a.description })];
                }
            });
        }); });
    },
    update: function (_a, ctx) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Custom Props', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, _a, name_1, property;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        b.data = a.data;
                        b.label = a.label;
                        b.description = a.description;
                        for (_i = 0, _a = oldParams.autoAttach; _i < _a.length; _i++) {
                            name_1 = _a[_i];
                            property = ctx.customModelProperties.get(name_1);
                            if (!property)
                                continue;
                            a.data.customProperties.reference(property.descriptor, false);
                        }
                        return [4 /*yield*/, attachModelProps(a.data, ctx, taskCtx, newParams)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customProperties.dispose();
    }
});
function attachModelProps(model, ctx, taskCtx, params) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var propertyCtx, autoAttach, properties, _i, _a, name_2, property, props, e_1;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
                    autoAttach = params.autoAttach, properties = params.properties;
                    _i = 0, _a = Object.keys(properties);
                    _b.label = 1;
                case 1:
                    if (!(_i < _a.length)) return [3 /*break*/, 8];
                    name_2 = _a[_i];
                    property = ctx.customModelProperties.get(name_2);
                    props = properties[name_2];
                    if (!(autoAttach.includes(name_2) || property.isHidden)) return [3 /*break*/, 6];
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, 4, , 5]);
                    return [4 /*yield*/, property.attach(propertyCtx, model, props, true)];
                case 3:
                    _b.sent();
                    return [3 /*break*/, 5];
                case 4:
                    e_1 = _b.sent();
                    ctx.log.warn("Error attaching model prop '" + name_2 + "': " + e_1);
                    return [3 /*break*/, 5];
                case 5: return [3 /*break*/, 7];
                case 6:
                    property.set(model, props);
                    _b.label = 7;
                case 7:
                    _i++;
                    return [3 /*break*/, 1];
                case 8: return [2 /*return*/];
            }
        });
    });
}
var CustomStructureProperties = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'custom-structure-properties',
    display: { name: 'Custom Structure Properties' },
    isDecorator: true,
    from: objects["a" /* PluginStateObject */].Molecule.Structure,
    to: objects["a" /* PluginStateObject */].Molecule.Structure,
    params: function (a, ctx) {
        return ctx.customStructureProperties.getParams(a === null || a === void 0 ? void 0 : a.data.root);
    }
})({
    apply: function (_a, ctx) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Custom Props', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, attachStructureProps(a.data.root, ctx, taskCtx, params)];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Molecule.Structure(a.data, { label: a.label, description: a.description })];
                }
            });
        }); });
    },
    update: function (_a, ctx) {
        var _this = this;
        var a = _a.a, b = _a.b, oldParams = _a.oldParams, newParams = _a.newParams;
        return mol_task["b" /* Task */].create('Custom Props', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, _a, name_3, property;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        b.data = a.data;
                        b.label = a.label;
                        b.description = a.description;
                        for (_i = 0, _a = oldParams.autoAttach; _i < _a.length; _i++) {
                            name_3 = _a[_i];
                            property = ctx.customStructureProperties.get(name_3);
                            if (!property)
                                continue;
                            a.data.customPropertyDescriptors.reference(property.descriptor, false);
                        }
                        return [4 /*yield*/, attachStructureProps(a.data.root, ctx, taskCtx, newParams)];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, mol_state["StateTransformer"].UpdateResult.Updated];
                }
            });
        }); });
    },
    dispose: function (_a) {
        var b = _a.b;
        b === null || b === void 0 ? void 0 : b.data.customPropertyDescriptors.dispose();
    }
});
function attachStructureProps(structure, ctx, taskCtx, params) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var propertyCtx, autoAttach, properties, _i, _a, name_4, property, props, e_2;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    propertyCtx = { runtime: taskCtx, assetManager: ctx.managers.asset };
                    autoAttach = params.autoAttach, properties = params.properties;
                    _i = 0, _a = Object.keys(properties);
                    _b.label = 1;
                case 1:
                    if (!(_i < _a.length)) return [3 /*break*/, 8];
                    name_4 = _a[_i];
                    property = ctx.customStructureProperties.get(name_4);
                    props = properties[name_4];
                    if (!(autoAttach.includes(name_4) || property.isHidden)) return [3 /*break*/, 6];
                    _b.label = 2;
                case 2:
                    _b.trys.push([2, 4, , 5]);
                    return [4 /*yield*/, property.attach(propertyCtx, structure, props, true)];
                case 3:
                    _b.sent();
                    return [3 /*break*/, 5];
                case 4:
                    e_2 = _b.sent();
                    ctx.log.warn("Error attaching structure prop '" + name_4 + "': " + e_2);
                    return [3 /*break*/, 5];
                case 5: return [3 /*break*/, 7];
                case 6:
                    property.set(structure, props);
                    _b.label = 7;
                case 7:
                    _i++;
                    return [3 /*break*/, 1];
                case 8: return [2 /*return*/];
            }
        });
    });
}
var ShapeFromPly = objects["b" /* PluginStateTransform */].BuiltIn({
    name: 'shape-from-ply',
    display: { name: 'Shape from PLY', description: 'Create Shape from PLY data' },
    from: objects["a" /* PluginStateObject */].Format.Ply,
    to: objects["a" /* PluginStateObject */].Shape.Provider,
    params: function (a) {
        return {};
    }
})({
    apply: function (_a) {
        var _this = this;
        var a = _a.a, params = _a.params;
        return mol_task["b" /* Task */].create('Create shape from PLY', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var shape, props;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, shapeFromPly(a.data, params).runInContext(ctx)];
                    case 1:
                        shape = _a.sent();
                        props = { label: 'Shape' };
                        return [2 /*return*/, new objects["a" /* PluginStateObject */].Shape.Provider(shape, props)];
                }
            });
        }); });
    }
});
//# sourceMappingURL=model.js.map

/***/ }),
/* 317 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ unzip; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ ungzip; });
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ zip; });

// UNUSED EXPORTS: inflateRaw, inflate, deflate

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/bin.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */
function toUint32(x) {
    return x >>> 0;
}
function toInt32(x) {
    return x >> 0;
}
function readUshort(buff, p) {
    return (buff[p]) | (buff[p + 1] << 8);
}
function writeUshort(buff, p, n) {
    buff[p] = (n) & 255;
    buff[p + 1] = (n >> 8) & 255;
}
function readUint(buff, p) {
    return (buff[p + 3] * (256 * 256 * 256)) + ((buff[p + 2] << 16) | (buff[p + 1] << 8) | buff[p]);
}
function writeUint(buff, p, n) {
    buff[p] = n & 255;
    buff[p + 1] = (n >> 8) & 255;
    buff[p + 2] = (n >> 16) & 255;
    buff[p + 3] = (n >> 24) & 255;
}
function readASCII(buff, p, l) {
    var s = '';
    for (var i = 0; i < l; i++)
        s += String.fromCharCode(buff[p + i]);
    return s;
}
// function writeASCII(data: Uint8Array, p: number, s: string){
//     for(let i=0; i<s.length; i++) data[p+i] = s.charCodeAt(i);
// }
function pad(n) {
    return n.length < 2 ? '0' + n : n;
}
function readUTF8(buff, p, l) {
    var s = '', ns;
    for (var i = 0; i < l; i++)
        s += '%' + pad(buff[p + i].toString(16));
    try {
        ns = decodeURIComponent(s);
    }
    catch (e) {
        return readASCII(buff, p, l);
    }
    return ns;
}
function writeUTF8(buff, p, str) {
    var strl = str.length;
    var i = 0;
    for (var ci = 0; ci < strl; ci++) {
        var code = str.charCodeAt(ci);
        if ((code & (0xffffffff - (1 << 7) + 1)) === 0) {
            buff[p + i] = (code);
            i++;
        }
        else if ((code & (0xffffffff - (1 << 11) + 1)) === 0) {
            buff[p + i] = (192 | (code >> 6));
            buff[p + i + 1] = (128 | ((code >> 0) & 63));
            i += 2;
        }
        else if ((code & (0xffffffff - (1 << 16) + 1)) === 0) {
            buff[p + i] = (224 | (code >> 12));
            buff[p + i + 1] = (128 | ((code >> 6) & 63));
            buff[p + i + 2] = (128 | ((code >> 0) & 63));
            i += 3;
        }
        else if ((code & (0xffffffff - (1 << 21) + 1)) === 0) {
            buff[p + i] = (240 | (code >> 18));
            buff[p + i + 1] = (128 | ((code >> 12) & 63));
            buff[p + i + 2] = (128 | ((code >> 6) & 63));
            buff[p + i + 3] = (128 | ((code >> 0) & 63));
            i += 4;
        }
        else
            throw 'e';
    }
    return i;
}
function sizeUTF8(str) {
    var strl = str.length;
    var i = 0;
    for (var ci = 0; ci < strl; ci++) {
        var code = str.charCodeAt(ci);
        if ((code & (0xffffffff - (1 << 7) + 1)) === 0) {
            i++;
        }
        else if ((code & (0xffffffff - (1 << 11) + 1)) === 0) {
            i += 2;
        }
        else if ((code & (0xffffffff - (1 << 16) + 1)) === 0) {
            i += 3;
        }
        else if ((code & (0xffffffff - (1 << 21) + 1)) === 0) {
            i += 4;
        }
        else {
            throw 'e';
        }
    }
    return i;
}
//# sourceMappingURL=bin.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/checksum.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */
var CrcTable = (function () {
    var tab = new Uint32Array(256);
    for (var n = 0; n < 256; n++) {
        var c = n;
        for (var k = 0; k < 8; k++) {
            if (c & 1)
                c = 0xedb88320 ^ (c >>> 1);
            else
                c = c >>> 1;
        }
        tab[n] = c;
    }
    return tab;
})();
function _crc(c, buf, off, len) {
    for (var i = 0; i < len; i++) {
        c = CrcTable[(c ^ buf[off + i]) & 0xff] ^ (c >>> 8);
    }
    return c;
}
function crc(b, o, l) {
    return _crc(0xffffffff, b, o, l) ^ 0xffffffff;
}
function adler(data, o, len) {
    var a = 1, b = 0;
    var off = o;
    var end = o + len;
    while (off < end) {
        var eend = Math.min(off + 5552, end);
        while (off < eend) {
            a += data[off++];
            b += a;
        }
        a = a % 65521;
        b = b % 65521;
    }
    return (b << 16) | a;
}
//# sourceMappingURL=checksum.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/util.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */
var U = (function () {
    var u16 = Uint16Array, u32 = Uint32Array;
    return {
        next_code: new u16(16),
        bl_count: new u16(16),
        ordr: [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15],
        of0: [3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 999, 999, 999],
        exb: [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0, 0],
        ldef: new u16(32),
        df0: [1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 65535, 65535],
        dxb: [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 0, 0],
        ddef: new u32(32),
        flmap: new u16(512),
        fltree: [],
        fdmap: new u16(32),
        fdtree: [],
        lmap: new u16(32768),
        ltree: [], ttree: [],
        dmap: new u16(32768),
        dtree: [],
        imap: new u16(512),
        itree: [],
        // rev9 : new u16(  512)
        rev15: new u16(1 << 15),
        lhst: new u32(286), dhst: new u32(30), ihst: new u32(19),
        lits: new u32(15000),
        strt: new u16(1 << 16),
        prev: new u16(1 << 15)
    };
})();
(function () {
    var len = 1 << 15;
    for (var i = 0; i < len; i++) {
        var x = i;
        x = (((x & 0xaaaaaaaa) >>> 1) | ((x & 0x55555555) << 1));
        x = (((x & 0xcccccccc) >>> 2) | ((x & 0x33333333) << 2));
        x = (((x & 0xf0f0f0f0) >>> 4) | ((x & 0x0f0f0f0f) << 4));
        x = (((x & 0xff00ff00) >>> 8) | ((x & 0x00ff00ff) << 8));
        U.rev15[i] = (((x >>> 16) | (x << 16))) >>> 17;
    }
    function pushV(tgt, n, sv) {
        while (n-- !== 0)
            tgt.push(0, sv);
    }
    for (var i = 0; i < 32; i++) {
        U.ldef[i] = (U.of0[i] << 3) | U.exb[i];
        U.ddef[i] = (U.df0[i] << 4) | U.dxb[i];
    }
    pushV(U.fltree, 144, 8);
    pushV(U.fltree, 255 - 143, 9);
    pushV(U.fltree, 279 - 255, 7);
    pushV(U.fltree, 287 - 279, 8);
    /*
    var i = 0;
    for(; i<=143; i++) U.fltree.push(0,8);
    for(; i<=255; i++) U.fltree.push(0,9);
    for(; i<=279; i++) U.fltree.push(0,7);
    for(; i<=287; i++) U.fltree.push(0,8);
    */
    makeCodes(U.fltree, 9);
    codes2map(U.fltree, 9, U.flmap);
    revCodes(U.fltree, 9);
    pushV(U.fdtree, 32, 5);
    // for(i=0;i<32; i++) U.fdtree.push(0,5);
    makeCodes(U.fdtree, 5);
    codes2map(U.fdtree, 5, U.fdmap);
    revCodes(U.fdtree, 5);
    pushV(U.itree, 19, 0);
    pushV(U.ltree, 286, 0);
    pushV(U.dtree, 30, 0);
    pushV(U.ttree, 320, 0);
    /*
    for(var i=0; i< 19; i++) U.itree.push(0,0);
    for(var i=0; i<286; i++) U.ltree.push(0,0);
    for(var i=0; i< 30; i++) U.dtree.push(0,0);
    for(var i=0; i<320; i++) U.ttree.push(0,0);
    */
})();
function codes2map(tree, MAX_BITS, map) {
    var max_code = tree.length;
    var r15 = U.rev15;
    for (var i = 0; i < max_code; i += 2) {
        if (tree[i + 1] !== 0) {
            var lit = i >> 1;
            var cl = tree[i + 1], val = (lit << 4) | cl; // :  (0x8000 | (U.of0[lit-257]<<7) | (U.exb[lit-257]<<4) | cl);
            var rest = (MAX_BITS - cl);
            var i0 = tree[i] << rest;
            var i1 = i0 + (1 << rest);
            // tree[i]=r15[i0]>>>(15-MAX_BITS);
            while (i0 !== i1) {
                var p0 = r15[i0] >>> (15 - MAX_BITS);
                map[p0] = val;
                i0++;
            }
        }
    }
}
function makeCodes(tree, MAX_BITS) {
    var max_code = tree.length;
    var bl_count = U.bl_count;
    for (var i = 0; i <= MAX_BITS; i++)
        bl_count[i] = 0;
    for (var i = 1; i < max_code; i += 2)
        bl_count[tree[i]]++;
    var next_code = U.next_code; // smallest code for each length
    var code = 0;
    bl_count[0] = 0;
    for (var bits = 1; bits <= MAX_BITS; bits++) {
        code = (code + bl_count[bits - 1]) << 1;
        next_code[bits] = code;
    }
    for (var n = 0; n < max_code; n += 2) {
        var len = tree[n + 1];
        if (len !== 0) {
            tree[n] = next_code[len];
            next_code[len]++;
        }
    }
}
function revCodes(tree, MAX_BITS) {
    var r15 = U.rev15, imb = 15 - MAX_BITS;
    for (var i = 0; i < tree.length; i += 2) {
        var i0 = (tree[i] << (MAX_BITS - tree[i + 1]));
        tree[i] = r15[i0] >>> imb;
    }
}
//# sourceMappingURL=util.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/inflate.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */


function InflateContext(data, buf) {
    var noBuf = buf === undefined;
    if (buf === undefined)
        buf = new Uint8Array((data.length >>> 2) << 3);
    return {
        data: data,
        buf: buf,
        noBuf: noBuf,
        BFINAL: 0,
        off: 0,
        pos: 0
    };
}
function inflateBlocks(ctx, count) {
    var data = ctx.data, noBuf = ctx.noBuf;
    var buf = ctx.buf, BFINAL = ctx.BFINAL, off = ctx.off, pos = ctx.pos;
    var iBlock = 0;
    while (BFINAL === 0 && iBlock < count) {
        var lmap = void 0, dmap = void 0;
        var ML = 0, MD = 0;
        BFINAL = _bitsF(data, pos, 1);
        iBlock += 1;
        var BTYPE = _bitsF(data, pos + 1, 2);
        pos += 3;
        if (BTYPE === 0) {
            // uncompressed block
            if ((pos & 7) !== 0)
                pos += 8 - (pos & 7);
            var p8 = (pos >>> 3) + 4;
            var len = data[p8 - 4] | (data[p8 - 3] << 8);
            if (noBuf)
                buf = _check(buf, off + len);
            buf.set(new Uint8Array(data.buffer, data.byteOffset + p8, len), off);
            pos = ((p8 + len) << 3);
            off += len;
            continue;
        }
        // grow output buffer if not provided
        if (noBuf)
            buf = _check(buf, off + (1 << 17));
        if (BTYPE === 1) {
            // block compressed with fixed Huffman codes
            lmap = U.flmap;
            dmap = U.fdmap;
            ML = (1 << 9) - 1;
            MD = (1 << 5) - 1;
        }
        else if (BTYPE === 2) {
            // block compressed with dynamic Huffman codes
            var HLIT = _bitsE(data, pos, 5) + 257;
            var HDIST = _bitsE(data, pos + 5, 5) + 1;
            var HCLEN = _bitsE(data, pos + 10, 4) + 4;
            pos += 14;
            for (var i = 0; i < 38; i += 2) {
                U.itree[i] = 0;
                U.itree[i + 1] = 0;
            }
            var tl = 1;
            for (var i = 0; i < HCLEN; i++) {
                var l = _bitsE(data, pos + i * 3, 3);
                U.itree[(U.ordr[i] << 1) + 1] = l;
                if (l > tl)
                    tl = l;
            }
            pos += 3 * HCLEN;
            makeCodes(U.itree, tl);
            codes2map(U.itree, tl, U.imap);
            lmap = U.lmap;
            dmap = U.dmap;
            pos = _decodeTiny(U.imap, (1 << tl) - 1, HLIT + HDIST, data, pos, U.ttree);
            var mx0 = _copyOut(U.ttree, 0, HLIT, U.ltree);
            ML = (1 << mx0) - 1;
            var mx1 = _copyOut(U.ttree, HLIT, HDIST, U.dtree);
            MD = (1 << mx1) - 1;
            makeCodes(U.ltree, mx0);
            codes2map(U.ltree, mx0, lmap);
            makeCodes(U.dtree, mx1);
            codes2map(U.dtree, mx1, dmap);
        }
        else {
            throw new Error("unknown BTYPE " + BTYPE);
        }
        while (true) {
            var code = lmap[_get17(data, pos) & ML];
            pos += code & 15;
            var lit = code >>> 4;
            if ((lit >>> 8) === 0) {
                buf[off++] = lit;
            }
            else if (lit === 256) {
                break;
            }
            else {
                var end = off + lit - 254;
                if (lit > 264) {
                    var ebs = U.ldef[lit - 257];
                    end = off + (ebs >>> 3) + _bitsE(data, pos, ebs & 7);
                    pos += ebs & 7;
                }
                var dcode = dmap[_get17(data, pos) & MD];
                pos += dcode & 15;
                var dlit = dcode >>> 4;
                var dbs = U.ddef[dlit];
                var dst = (dbs >>> 4) + _bitsF(data, pos, dbs & 15);
                pos += dbs & 15;
                if (noBuf)
                    buf = _check(buf, off + (1 << 17));
                while (off < end) {
                    buf[off] = buf[off++ - dst];
                    buf[off] = buf[off++ - dst];
                    buf[off] = buf[off++ - dst];
                    buf[off] = buf[off++ - dst];
                }
                off = end;
            }
        }
    }
    ctx.buf = buf;
    ctx.BFINAL = BFINAL;
    ctx.off = off;
    ctx.pos = pos;
}
// https://tools.ietf.org/html/rfc1951
function _inflate(runtime, data, buf) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var ctx;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (data[0] === 3 && data[1] === 0)
                        return [2 /*return*/, (buf ? buf : new Uint8Array(0))];
                    ctx = InflateContext(data, buf);
                    _a.label = 1;
                case 1:
                    if (!(ctx.BFINAL === 0)) return [3 /*break*/, 4];
                    if (!runtime.shouldUpdate) return [3 /*break*/, 3];
                    return [4 /*yield*/, runtime.update({ message: 'Inflating blocks...', current: ctx.pos, max: data.length })];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    inflateBlocks(ctx, 100);
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/, ctx.buf.length === ctx.off ? ctx.buf : ctx.buf.slice(0, ctx.off)];
            }
        });
    });
}
function _check(buf, len) {
    var bl = buf.length;
    if (len <= bl)
        return buf;
    var nbuf = new Uint8Array(Math.max(bl << 1, len));
    nbuf.set(buf, 0);
    return nbuf;
}
function _decodeTiny(lmap, LL, len, data, pos, tree) {
    var i = 0;
    while (i < len) {
        var code = lmap[_get17(data, pos) & LL];
        pos += code & 15;
        var lit = code >>> 4;
        if (lit <= 15) {
            tree[i] = lit;
            i++;
        }
        else {
            var ll = 0, n = 0;
            if (lit === 16) {
                n = (3 + _bitsE(data, pos, 2));
                pos += 2;
                ll = tree[i - 1];
            }
            else if (lit === 17) {
                n = (3 + _bitsE(data, pos, 3));
                pos += 3;
            }
            else if (lit === 18) {
                n = (11 + _bitsE(data, pos, 7));
                pos += 7;
            }
            var ni = i + n;
            while (i < ni) {
                tree[i] = ll;
                i++;
            }
        }
    }
    return pos;
}
function _copyOut(src, off, len, tree) {
    var mx = 0, i = 0;
    var tl = tree.length >>> 1;
    while (i < len) {
        var v = src[i + off];
        tree[(i << 1)] = 0;
        tree[(i << 1) + 1] = v;
        if (v > mx)
            mx = v;
        i++;
    }
    while (i < tl) {
        tree[(i << 1)] = 0;
        tree[(i << 1) + 1] = 0;
        i++;
    }
    return mx;
}
function _bitsE(dt, pos, length) {
    return ((dt[pos >>> 3] | (dt[(pos >>> 3) + 1] << 8)) >>> (pos & 7)) & ((1 << length) - 1);
}
function _bitsF(dt, pos, length) {
    return ((dt[pos >>> 3] | (dt[(pos >>> 3) + 1] << 8) | (dt[(pos >>> 3) + 2] << 16)) >>> (pos & 7)) & ((1 << length) - 1);
}
function _get17(dt, pos) {
    return (dt[pos >>> 3] | (dt[(pos >>> 3) + 1] << 8) | (dt[(pos >>> 3) + 2] << 16)) >>> (pos & 7);
}
//# sourceMappingURL=inflate.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/huffman.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */
function _hufTree(hst, tree, MAXL) {
    var list = [];
    var hl = hst.length, tl = tree.length;
    for (var i = 0; i < tl; i += 2) {
        tree[i] = 0;
        tree[i + 1] = 0;
    }
    for (var i = 0; i < hl; i++)
        if (hst[i] !== 0)
            list.push({ lit: i, f: hst[i], d: undefined });
    var end = list.length, l2 = list.slice(0);
    if (end === 0)
        return 0; // empty histogram (usually for dist)
    if (end === 1) {
        var lit = list[0].lit, l2_1 = lit === 0 ? 1 : 0;
        tree[(lit << 1) + 1] = 1;
        tree[(l2_1 << 1) + 1] = 1;
        return 1;
    }
    list.sort(function (a, b) { return a.f - b.f; });
    var a = list[0], b = list[1], i0 = 0, i1 = 1, i2 = 2;
    list[0] = {
        lit: -1,
        f: a.f + b.f,
        l: a,
        r: b,
        d: 0
    };
    while (i1 !== end - 1) {
        if (i0 !== i1 && (i2 === end || list[i0].f < list[i2].f)) {
            a = list[i0++];
        }
        else {
            a = list[i2++];
        }
        if (i0 !== i1 && (i2 === end || list[i0].f < list[i2].f)) {
            b = list[i0++];
        }
        else {
            b = list[i2++];
        }
        list[i1++] = {
            lit: -1,
            f: a.f + b.f,
            l: a,
            r: b,
            d: undefined
        };
    }
    var maxl = setDepth(list[i1 - 1], 0);
    if (maxl > MAXL) {
        restrictDepth(l2, MAXL, maxl);
        maxl = MAXL;
    }
    for (var i = 0; i < end; i++)
        tree[(l2[i].lit << 1) + 1] = l2[i].d;
    return maxl;
}
function setDepth(t, d) {
    if (t.lit !== -1) {
        t.d = d;
        return d;
    }
    return Math.max(setDepth(t.l, d + 1), setDepth(t.r, d + 1));
}
function restrictDepth(dps, MD, maxl) {
    var i = 0, bCost = 1 << (maxl - MD), dbt = 0;
    dps.sort(function (a, b) { return b.d === a.d ? a.f - b.f : b.d - a.d; });
    for (i = 0; i < dps.length; i++) {
        if (dps[i].d > MD) {
            var od = dps[i].d;
            dps[i].d = MD;
            dbt += bCost - (1 << (maxl - od));
        }
        else {
            break;
        }
    }
    dbt = dbt >>> (maxl - MD);
    while (dbt > 0) {
        var od = dps[i].d;
        if (od < MD) {
            dps[i].d++;
            dbt -= (1 << (MD - od - 1));
        }
        else {
            i++;
        }
    }
    for (; i >= 0; i--) {
        if (dps[i].d === MD && dbt < 0) {
            dps[i].d--;
            dbt++;
        }
    }
    if (dbt !== 0)
        console.log('debt left');
}
//# sourceMappingURL=huffman.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/deflate.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 */


function _deflateRaw(data, out, opos, lvl) {
    var opts = [
        /*
            ush good_length; /* reduce lazy search above this match length
            ush max_lazy;    /* do not perform lazy search above this match length
            ush nice_length; /* quit search above this match length
        */
        /*      good lazy nice chain */
        /* 0 */ [0, 0, 0, 0, 0],
        /* 1 */ [4, 4, 8, 4, 0],
        /* 2 */ [4, 5, 16, 8, 0],
        /* 3 */ [4, 6, 16, 16, 0],
        /* 4 */ [4, 10, 16, 32, 0],
        /* 5 */ [8, 16, 32, 32, 0],
        /* 6 */ [8, 16, 128, 128, 0],
        /* 7 */ [8, 32, 128, 256, 0],
        /* 8 */ [32, 128, 258, 1024, 1],
        /* 9 */ [32, 258, 258, 4096, 1] /* max compression */
    ];
    var opt = opts[lvl];
    var i = 0, pos = opos << 3, cvrd = 0;
    var dlen = data.length;
    if (lvl === 0) {
        while (i < dlen) {
            var len = Math.min(0xffff, dlen - i);
            _putsE(out, pos, (i + len === dlen ? 1 : 0));
            pos = _copyExact(data, i, len, out, pos + 8);
            i += len;
        }
        return pos >>> 3;
    }
    var lits = U.lits, strt = U.strt, prev = U.prev;
    var li = 0, lc = 0, bs = 0, ebits = 0, c = 0, nc = 0; // last_item, literal_count, block_start
    if (dlen > 2) {
        nc = _hash(data, 0);
        strt[nc] = 0;
    }
    // let nmch = 0
    // let nmci = 0
    for (i = 0; i < dlen; i++) {
        c = nc;
        //*
        if (i + 1 < dlen - 2) {
            nc = _hash(data, i + 1);
            var ii = ((i + 1) & 0x7fff);
            prev[ii] = strt[nc];
            strt[nc] = ii;
        } // */
        if (cvrd <= i) {
            if ((li > 14000 || lc > 26697) && (dlen - i) > 100) {
                if (cvrd < i) {
                    lits[li] = i - cvrd;
                    li += 2;
                    cvrd = i;
                }
                pos = _writeBlock(((i === dlen - 1) || (cvrd === dlen)) ? 1 : 0, lits, li, ebits, data, bs, i - bs, out, pos);
                li = lc = ebits = 0;
                bs = i;
            }
            var mch = 0;
            // if(nmci==i) mch= nmch;  else
            if (i < dlen - 2) {
                mch = _bestMatch(data, i, prev, c, Math.min(opt[2], dlen - i), opt[3]);
            }
            /*
            if(mch!=0 && opt[4]==1 && (mch>>>16)<opt[1] && i+1<dlen-2) {
                nmch = UZIP.F._bestMatch(data, i+1, prev, nc, opt[2], opt[3]);  nmci=i+1;
                //var mch2 = UZIP.F._bestMatch(data, i+2, prev, nnc);  //nmci=i+1;
                if((nmch>>>16)>(mch>>>16)) mch=0;
            }//*/
            // const len = mch>>>16, dst = mch & 0xffff;  // if(i-dst<0) throw "e";
            if (mch !== 0) {
                var len = mch >>> 16, dst = mch & 0xffff; // if(i-dst<0) throw "e";
                var lgi = _goodIndex(len, U.of0);
                U.lhst[257 + lgi]++;
                var dgi = _goodIndex(dst, U.df0);
                U.dhst[dgi]++;
                ebits += U.exb[lgi] + U.dxb[dgi];
                lits[li] = (len << 23) | (i - cvrd);
                lits[li + 1] = (dst << 16) | (lgi << 8) | dgi;
                li += 2;
                cvrd = i + len;
            }
            else {
                U.lhst[data[i]]++;
            }
            lc++;
        }
    }
    if (bs !== i || data.length === 0) {
        if (cvrd < i) {
            lits[li] = i - cvrd;
            li += 2;
            cvrd = i;
        }
        pos = _writeBlock(1, lits, li, ebits, data, bs, i - bs, out, pos);
        li = 0;
        lc = 0;
        li = lc = ebits = 0;
        bs = i;
    }
    while ((pos & 7) !== 0)
        pos++;
    return pos >>> 3;
}
function _bestMatch(data, i, prev, c, nice, chain) {
    var ci = (i & 0x7fff), pi = prev[ci];
    // console.log("----", i);
    var dif = ((ci - pi + (1 << 15)) & 0x7fff);
    if (pi === ci || c !== _hash(data, i - dif))
        return 0;
    var tl = 0, td = 0; // top length, top distance
    var dlim = Math.min(0x7fff, i);
    while (dif <= dlim && --chain !== 0 && pi !== ci /* && c==UZIP.F._hash(data,i-dif)*/) {
        if (tl === 0 || (data[i + tl] === data[i + tl - dif])) {
            var cl = _howLong(data, i, dif);
            if (cl > tl) {
                tl = cl;
                td = dif;
                if (tl >= nice)
                    break; //*
                if (dif + 2 < cl)
                    cl = dif + 2;
                var maxd = 0; // pi does not point to the start of the word
                for (var j = 0; j < cl - 2; j++) {
                    var ei = (i - dif + j + (1 << 15)) & 0x7fff;
                    var li = prev[ei];
                    var curd = (ei - li + (1 << 15)) & 0x7fff;
                    if (curd > maxd) {
                        maxd = curd;
                        pi = ei;
                    }
                }
            }
        }
        ci = pi;
        pi = prev[ci];
        dif += ((ci - pi + (1 << 15)) & 0x7fff);
    }
    return (tl << 16) | td;
}
function _howLong(data, i, dif) {
    if (data[i] !== data[i - dif] || data[i + 1] !== data[i + 1 - dif] || data[i + 2] !== data[i + 2 - dif])
        return 0;
    var oi = i, l = Math.min(data.length, i + 258);
    i += 3;
    // while(i+4<l && data[i]==data[i-dif] && data[i+1]==data[i+1-dif] && data[i+2]==data[i+2-dif] && data[i+3]==data[i+3-dif]) i+=4;
    while (i < l && data[i] === data[i - dif])
        i++;
    return i - oi;
}
function _hash(data, i) {
    return (((data[i] << 8) | data[i + 1]) + (data[i + 2] << 4)) & 0xffff;
    // var hash_shift = 0, hash_mask = 255;
    // var h = data[i+1] % 251;
    // h = (((h << 8) + data[i+2]) % 251);
    // h = (((h << 8) + data[i+2]) % 251);
    // h = ((h<<hash_shift) ^ (c) ) & hash_mask;
    // return h | (data[i]<<8);
    // return (data[i] | (data[i+1]<<8));
}
function _writeBlock(BFINAL, lits, li, ebits, data, o0, l0, out, pos) {
    U.lhst[256]++;
    var _a = getTrees(), ML = _a[0], MD = _a[1], MH = _a[2], numl = _a[3], numd = _a[4], numh = _a[5], lset = _a[6], dset = _a[7];
    var cstSize = (((pos + 3) & 7) === 0 ? 0 : 8 - ((pos + 3) & 7)) + 32 + (l0 << 3);
    var fxdSize = ebits + contSize(U.fltree, U.lhst) + contSize(U.fdtree, U.dhst);
    var dynSize = ebits + contSize(U.ltree, U.lhst) + contSize(U.dtree, U.dhst);
    dynSize += 14 + 3 * numh + contSize(U.itree, U.ihst) + (U.ihst[16] * 2 + U.ihst[17] * 3 + U.ihst[18] * 7);
    for (var j = 0; j < 286; j++)
        U.lhst[j] = 0;
    for (var j = 0; j < 30; j++)
        U.dhst[j] = 0;
    for (var j = 0; j < 19; j++)
        U.ihst[j] = 0;
    var BTYPE = (cstSize < fxdSize && cstSize < dynSize) ? 0 : (fxdSize < dynSize ? 1 : 2);
    _putsF(out, pos, BFINAL);
    _putsF(out, pos + 1, BTYPE);
    pos += 3;
    // let opos = pos;
    if (BTYPE === 0) {
        while ((pos & 7) !== 0)
            pos++;
        pos = _copyExact(data, o0, l0, out, pos);
    }
    else {
        var ltree = void 0, dtree = void 0;
        if (BTYPE === 1) {
            ltree = U.fltree;
            dtree = U.fdtree;
        }
        else if (BTYPE === 2) {
            makeCodes(U.ltree, ML);
            revCodes(U.ltree, ML);
            makeCodes(U.dtree, MD);
            revCodes(U.dtree, MD);
            makeCodes(U.itree, MH);
            revCodes(U.itree, MH);
            ltree = U.ltree;
            dtree = U.dtree;
            _putsE(out, pos, numl - 257);
            pos += 5; // 286
            _putsE(out, pos, numd - 1);
            pos += 5; // 30
            _putsE(out, pos, numh - 4);
            pos += 4; // 19
            for (var i = 0; i < numh; i++)
                _putsE(out, pos + i * 3, U.itree[(U.ordr[i] << 1) + 1]);
            pos += 3 * numh;
            pos = _codeTiny(lset, U.itree, out, pos);
            pos = _codeTiny(dset, U.itree, out, pos);
        }
        else {
            throw new Error("unknown BTYPE " + BTYPE);
        }
        var off = o0;
        for (var si = 0; si < li; si += 2) {
            var qb = lits[si], len = (qb >>> 23), end = off + (qb & ((1 << 23) - 1));
            while (off < end)
                pos = _writeLit(data[off++], ltree, out, pos);
            if (len !== 0) {
                var qc = lits[si + 1], dst = (qc >> 16), lgi = (qc >> 8) & 255, dgi = (qc & 255);
                pos = _writeLit(257 + lgi, ltree, out, pos);
                _putsE(out, pos, len - U.of0[lgi]);
                pos += U.exb[lgi];
                pos = _writeLit(dgi, dtree, out, pos);
                _putsF(out, pos, dst - U.df0[dgi]);
                pos += U.dxb[dgi];
                off += len;
            }
        }
        pos = _writeLit(256, ltree, out, pos);
    }
    // console.log(pos-opos, fxdSize, dynSize, cstSize);
    return pos;
}
function _copyExact(data, off, len, out, pos) {
    var p8 = (pos >>> 3);
    out[p8] = (len);
    out[p8 + 1] = (len >>> 8);
    out[p8 + 2] = 255 - out[p8];
    out[p8 + 3] = 255 - out[p8 + 1];
    p8 += 4;
    out.set(new Uint8Array(data.buffer, off, len), p8);
    // for(var i=0; i<len; i++) out[p8+i]=data[off+i];
    return pos + ((len + 4) << 3);
}
/*
    Interesting facts:
    - decompressed block can have bytes, which do not occur in a Huffman tree (copied from the previous block by reference)
*/
function getTrees() {
    var ML = _hufTree(U.lhst, U.ltree, 15);
    var MD = _hufTree(U.dhst, U.dtree, 15);
    var lset = [];
    var numl = _lenCodes(U.ltree, lset);
    var dset = [];
    var numd = _lenCodes(U.dtree, dset);
    for (var i = 0; i < lset.length; i += 2)
        U.ihst[lset[i]]++;
    for (var i = 0; i < dset.length; i += 2)
        U.ihst[dset[i]]++;
    var MH = _hufTree(U.ihst, U.itree, 7);
    var numh = 19;
    while (numh > 4 && U.itree[(U.ordr[numh - 1] << 1) + 1] === 0)
        numh--;
    return [ML, MD, MH, numl, numd, numh, lset, dset];
}
function contSize(tree, hst) {
    var s = 0;
    for (var i = 0; i < hst.length; i++)
        s += hst[i] * tree[(i << 1) + 1];
    return s;
}
function _codeTiny(set, tree, out, pos) {
    for (var i = 0; i < set.length; i += 2) {
        var l = set[i], rst = set[i + 1]; // console.log(l, pos, tree[(l<<1)+1]);
        pos = _writeLit(l, tree, out, pos);
        var rsl = l === 16 ? 2 : (l === 17 ? 3 : 7);
        if (l > 15) {
            _putsE(out, pos, rst);
            pos += rsl;
        }
    }
    return pos;
}
function _lenCodes(tree, set) {
    var len = tree.length;
    while (len !== 2 && tree[len - 1] === 0)
        len -= 2; // when no distances, keep one code with length 0
    for (var i = 0; i < len; i += 2) {
        var l = tree[i + 1], nxt = (i + 3 < len ? tree[i + 3] : -1), nnxt = (i + 5 < len ? tree[i + 5] : -1), prv = (i === 0 ? -1 : tree[i - 1]);
        if (l === 0 && nxt === l && nnxt === l) {
            var lz = i + 5;
            while (lz + 2 < len && tree[lz + 2] === l)
                lz += 2;
            var zc = Math.min((lz + 1 - i) >>> 1, 138);
            if (zc < 11)
                set.push(17, zc - 3);
            else
                set.push(18, zc - 11);
            i += zc * 2 - 2;
        }
        else if (l === prv && nxt === l && nnxt === l) {
            var lz = i + 5;
            while (lz + 2 < len && tree[lz + 2] === l)
                lz += 2;
            var zc = Math.min((lz + 1 - i) >>> 1, 6);
            set.push(16, zc - 3);
            i += zc * 2 - 2;
        }
        else {
            set.push(l, 0);
        }
    }
    return len >>> 1;
}
function _goodIndex(v, arr) {
    var i = 0;
    if (arr[i | 16] <= v)
        i |= 16;
    if (arr[i | 8] <= v)
        i |= 8;
    if (arr[i | 4] <= v)
        i |= 4;
    if (arr[i | 2] <= v)
        i |= 2;
    if (arr[i | 1] <= v)
        i |= 1;
    return i;
}
function _writeLit(ch, ltree, out, pos) {
    _putsF(out, pos, ltree[ch << 1]);
    return pos + ltree[(ch << 1) + 1];
}
function _putsE(dt, pos, val) {
    val = val << (pos & 7);
    var o = (pos >>> 3);
    dt[o] |= val;
    dt[o + 1] |= (val >>> 8);
}
function _putsF(dt, pos, val) {
    val = val << (pos & 7);
    var o = (pos >>> 3);
    dt[o] |= val;
    dt[o + 1] |= (val >>> 8);
    dt[o + 2] |= (val >>> 16);
}
//# sourceMappingURL=deflate.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/zip/zip.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from https://github.com/photopea/UZIP.js/blob/master/UZIP.js
 * MIT License, Copyright (c) 2018 Photopea
 *
 * - added `ungzip`
 */





function unzip(runtime, buf, onlyNames) {
    if (onlyNames === void 0) { onlyNames = false; }
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var out, data, eocd, o, cnu, coffs, i, csize, usize, nl, el, cl, roff;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    out = Object.create(null);
                    data = new Uint8Array(buf);
                    eocd = data.length - 4;
                    while (readUint(data, eocd) !== 0x06054b50)
                        eocd--;
                    o = eocd;
                    o += 4; // sign  = 0x06054b50
                    o += 4; // disks = 0;
                    cnu = readUshort(data, o);
                    o += 2;
                    // const cnt = readUshort(data, o);
                    o += 2;
                    // const csize = readUint(data, o);
                    o += 4;
                    coffs = readUint(data, o);
                    o += 4;
                    o = coffs;
                    i = 0;
                    _a.label = 1;
                case 1:
                    if (!(i < cnu)) return [3 /*break*/, 4];
                    // const sign = readUint(data, o);
                    o += 4;
                    o += 4; // versions;
                    o += 4; // flag + compr
                    o += 4; // time
                    // const crc32 = readUint(data, o);
                    o += 4;
                    csize = readUint(data, o);
                    o += 4;
                    usize = readUint(data, o);
                    o += 4;
                    nl = readUshort(data, o);
                    el = readUshort(data, o + 2);
                    cl = readUshort(data, o + 4);
                    o += 6; // name, extra, comment
                    o += 8; // disk, attribs
                    roff = readUint(data, o);
                    o += 4;
                    o += nl + el + cl;
                    return [4 /*yield*/, _readLocal(runtime, data, roff, out, csize, usize, onlyNames)];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    i++;
                    return [3 /*break*/, 1];
                case 4:
                // console.log(out);
                return [2 /*return*/, out];
            }
        });
    });
}
function _readLocal(runtime, data, o, out, csize, usize, onlyNames) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var cmpr, nlen, elen, name, file, buf;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    // const sign  = readUint(data, o);
                    o += 4;
                    // const ver   = readUshort(data, o);
                    o += 2;
                    // const gpflg = readUshort(data, o);
                    o += 2;
                    cmpr = readUshort(data, o);
                    o += 2;
                    // const time  = readUint(data, o);
                    o += 4;
                    // const crc32 = readUint(data, o);
                    o += 4;
                    // var csize = rUi(data, o);  o+=4;
                    // var usize = rUi(data, o);  o+=4;
                    o += 8;
                    nlen = readUshort(data, o);
                    o += 2;
                    elen = readUshort(data, o);
                    o += 2;
                    name = readUTF8(data, o, nlen);
                    o += nlen; // console.log(name);
                    o += elen;
                    if (onlyNames) {
                        out[name] = { size: usize, csize: csize };
                        return [2 /*return*/];
                    }
                    file = new Uint8Array(data.buffer, o);
                    if (!(cmpr === 0)) return [3 /*break*/, 1];
                    out[name] = new Uint8Array(file.buffer.slice(o, o + csize));
                    return [3 /*break*/, 4];
                case 1:
                    if (!(cmpr === 8)) return [3 /*break*/, 3];
                    buf = new Uint8Array(usize);
                    return [4 /*yield*/, inflateRaw(runtime, file, buf)];
                case 2:
                    _a.sent();
                    out[name] = buf;
                    return [3 /*break*/, 4];
                case 3: throw "unknown compression method: " + cmpr;
                case 4: return [2 /*return*/];
            }
        });
    });
}
function inflateRaw(runtime, file, buf) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, _inflate(runtime, file, buf)];
        });
    });
}
function inflate(runtime, file, buf) {
    // const CMF = file[0]
    // const FLG = file[1]
    // const CM = (CMF&15)
    // const CINFO = (CMF>>>4);
    // console.log(CM, CINFO,CMF,FLG);
    return inflateRaw(runtime, new Uint8Array(file.buffer, file.byteOffset + 2, file.length - 6), buf);
}
// https://tools.ietf.org/html/rfc1952
function ungzip(runtime, file, buf) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var flg, o, xlen, zero, zero, crc32, isize, blocks, inflated, crcValue;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    flg = file[3];
                    o = 10;
                    if (flg & 4) { // FEXTRA
                        xlen = readUshort(file, o);
                        // console.log('FEXTRA', xlen)
                        o += xlen;
                    }
                    if (flg & 8) { // FNAME
                        zero = o;
                        while (file[zero] !== 0)
                            ++zero;
                        // const name = readUTF8(file, o, zero - o)
                        // console.log('FNAME', name, zero - o)
                        o = zero + 1;
                    }
                    if (flg & 16) { // FCOMMENT
                        zero = o;
                        while (file[zero] !== 0)
                            ++zero;
                        // const comment = readUTF8(file, o, zero - o)
                        // console.log('FCOMMENT', comment)
                        o = zero + 1;
                    }
                    if (flg & 1) { // FHCRC
                        // const hcrc = readUshort(file, o)
                        // console.log('FHCRC', hcrc)
                        o += 2;
                    }
                    crc32 = toInt32(readUint(file, file.length - 8));
                    isize = readUint(file, file.length - 4);
                    if (buf === undefined)
                        buf = new Uint8Array(isize);
                    blocks = new Uint8Array(file.buffer, file.byteOffset + o, file.length - o - 8);
                    return [4 /*yield*/, inflateRaw(runtime, blocks, buf)];
                case 1:
                    inflated = _a.sent();
                    crcValue = crc(inflated, 0, inflated.length);
                    if (crc32 !== crcValue) {
                        console.error("ungzip: checksums don't match");
                    }
                    return [2 /*return*/, inflated];
            }
        });
    });
}
function deflate(data, opts /* , buf, off*/) {
    if (opts === undefined)
        opts = { level: 6 };
    var off = 0;
    var buf = new Uint8Array(50 + Math.floor(data.length * 1.1));
    buf[off] = 120;
    buf[off + 1] = 156;
    off += 2;
    off = _deflateRaw(data, buf, off, opts.level);
    var crcValue = adler(data, 0, data.length);
    buf[off + 0] = ((crcValue >>> 24) & 255);
    buf[off + 1] = ((crcValue >>> 16) & 255);
    buf[off + 2] = ((crcValue >>> 8) & 255);
    buf[off + 3] = ((crcValue >>> 0) & 255);
    return new Uint8Array(buf.buffer, 0, off + 4);
}
function deflateRaw(data, opts) {
    if (opts === undefined)
        opts = { level: 6 };
    var buf = new Uint8Array(50 + Math.floor(data.length * 1.1));
    var off = _deflateRaw(data, buf, 0, opts.level);
    return new Uint8Array(buf.buffer, 0, off);
}
function zip(obj, noCmpr) {
    if (noCmpr === void 0) { noCmpr = false; }
    var tot = 0;
    var zpd = {};
    for (var p in obj) {
        var cpr = !_noNeed(p) && !noCmpr, buf = obj[p];
        var crcValue = crc(buf, 0, buf.length);
        zpd[p] = {
            cpr: cpr,
            usize: buf.length,
            crc: crcValue,
            file: (cpr ? deflateRaw(buf) : buf)
        };
    }
    for (var p in zpd)
        tot += zpd[p].file.length + 30 + 46 + 2 * sizeUTF8(p);
    tot += 22;
    var data = new Uint8Array(tot);
    var o = 0;
    var fof = [];
    for (var p in zpd) {
        var file = zpd[p];
        fof.push(o);
        o = _writeHeader(data, o, p, file, 0);
    }
    var i = 0, ioff = o;
    for (var p in zpd) {
        var file = zpd[p];
        fof.push(o);
        o = _writeHeader(data, o, p, file, 1, fof[i++]);
    }
    var csize = o - ioff;
    writeUint(data, o, 0x06054b50);
    o += 4;
    o += 4; // disks
    writeUshort(data, o, i);
    o += 2;
    writeUshort(data, o, i);
    o += 2; // number of c d records
    writeUint(data, o, csize);
    o += 4;
    writeUint(data, o, ioff);
    o += 4;
    o += 2;
    return data.buffer;
}
// no need to compress .PNG, .ZIP, .JPEG ....
function _noNeed(fn) {
    var ext = fn.split('.').pop().toLowerCase();
    return 'png,jpg,jpeg,zip'.indexOf(ext) !== -1;
}
function _writeHeader(data, o, p, obj, t, roff) {
    if (roff === void 0) { roff = 0; }
    var file = obj.file;
    writeUint(data, o, t === 0 ? 0x04034b50 : 0x02014b50);
    o += 4; // sign
    if (t === 1)
        o += 2; // ver made by
    writeUshort(data, o, 20);
    o += 2; // ver
    writeUshort(data, o, 0);
    o += 2; // gflip
    writeUshort(data, o, obj.cpr ? 8 : 0);
    o += 2; // cmpr
    writeUint(data, o, 0);
    o += 4; // time
    writeUint(data, o, obj.crc);
    o += 4; // crc32
    writeUint(data, o, file.length);
    o += 4; // csize
    writeUint(data, o, obj.usize);
    o += 4; // usize
    writeUshort(data, o, sizeUTF8(p));
    o += 2; // nlen
    writeUshort(data, o, 0);
    o += 2; // elen
    if (t === 1) {
        o += 2; // comment length
        o += 2; // disk number
        o += 6; // attributes
        writeUint(data, o, roff);
        o += 4; // usize
    }
    var nlen = writeUTF8(data, o, p);
    o += nlen;
    if (t === 0) {
        data.set(file, o);
        o += file.length;
    }
    return o;
}
//# sourceMappingURL=zip.js.map

/***/ }),
/* 318 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ PostprocessingParams; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ postprocessing_PostprocessingPass; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/compute/util.js
var util = __webpack_require__(148);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/schema.js
var renderable_schema = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-item.js
var render_item = __webpack_require__(99);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable.js
var renderable = __webpack_require__(98);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/immer/dist/immer.esm.js
var immer_esm = __webpack_require__(151);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader/quad.vert.js
var quad_vert = __webpack_require__(205);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/postprocessing.frag.js
/* harmony default export */ var postprocessing_frag = ("\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\n\nuniform sampler2D tColor;\nuniform sampler2D tDepth;\nuniform vec2 uTexSize;\n\nuniform float uNear;\nuniform float uFar;\nuniform float uFogNear;\nuniform float uFogFar;\nuniform vec3 uFogColor;\n\nuniform float uOcclusionBias;\nuniform float uOcclusionRadius;\n\nuniform float uOutlineScale;\nuniform float uOutlineThreshold;\n\nconst float noiseAmount = 0.0002;\nconst vec4 occlusionColor = vec4(0.0, 0.0, 0.0, 1.0);\n\n#include common\n\nfloat noise(const in vec2 coords) {\n\tfloat a = 12.9898;\n\tfloat b = 78.233;\n\tfloat c = 43758.5453;\n\tfloat dt = dot(coords, vec2(a,b));\n\tfloat sn = mod(dt, 3.14159);\n\n\treturn fract(sin(sn) * c);\n}\n\nfloat perspectiveDepthToViewZ(const in float invClipZ, const in float near, const in float far) {\n\treturn (near * far) / ((far - near) * invClipZ - far);\n}\n\nfloat orthographicDepthToViewZ(const in float linearClipZ, const in float near, const in float far) {\n\treturn linearClipZ * (near - far) - near;\n}\n\nfloat getViewZ(const in float depth) {\n\t#if dOrthographic == 1\n\t\treturn orthographicDepthToViewZ(depth, uNear, uFar);\n\t#else\n\t\treturn perspectiveDepthToViewZ(depth, uNear, uFar);\n\t#endif\n}\n\nfloat getDepth(const in vec2 coords) {\n\t#ifdef dPackedDepth\n\t\treturn unpackRGBAToDepth(texture2D(tDepth, coords));\n\t#else\n\t\treturn texture2D(tDepth, coords).r;\n\t#endif\n}\n\nfloat calcSSAO(const in vec2 coords, const in float depth) {\n\tfloat occlusionFactor = 0.0;\n\n\tfor (int i = -dOcclusionKernelSize; i <= dOcclusionKernelSize; i++) {\n\t\tfor (int j = -dOcclusionKernelSize; j <= dOcclusionKernelSize; j++) {\n\t\t\tvec2 coordsDelta = coords + uOcclusionRadius / float(dOcclusionKernelSize) * vec2(float(i) / uTexSize.x, float(j) / uTexSize.y);\n            coordsDelta += noiseAmount * (noise(coordsDelta) - 0.5) / uTexSize;\n            coordsDelta = clamp(coordsDelta, 0.5 / uTexSize, 1.0 - 1.0 / uTexSize);\n\t\t\tif (getDepth(coordsDelta) < depth) occlusionFactor += 1.0;\n\t\t}\n\t}\n\n\treturn occlusionFactor / float((2 * dOcclusionKernelSize + 1) * (2 * dOcclusionKernelSize + 1));\n}\n\nvec2 calcEdgeDepth(const in vec2 coords) {\n    vec2 invTexSize = 1.0 / uTexSize;\n    float halfScaleFloor = floor(uOutlineScale * 0.5);\n    float halfScaleCeil = ceil(uOutlineScale * 0.5);\n\n    vec2 bottomLeftUV = coords - invTexSize * halfScaleFloor;\n    vec2 topRightUV = coords + invTexSize * halfScaleCeil;\n    vec2 bottomRightUV = coords + vec2(invTexSize.x * halfScaleCeil, -invTexSize.y * halfScaleFloor);\n    vec2 topLeftUV = coords + vec2(-invTexSize.x * halfScaleFloor, invTexSize.y * halfScaleCeil);\n\n    float depth0 = getDepth(bottomLeftUV);\n    float depth1 = getDepth(topRightUV);\n    float depth2 = getDepth(bottomRightUV);\n    float depth3 = getDepth(topLeftUV);\n\n    float depthFiniteDifference0 = depth1 - depth0;\n    float depthFiniteDifference1 = depth3 - depth2;\n\n    return vec2(\n\t\tsqrt(pow(depthFiniteDifference0, 2.0) + pow(depthFiniteDifference1, 2.0)) * 100.0,\n\t\tmin(depth0, min(depth1, min(depth2, depth3)))\n\t);\n}\n\nvoid main(void) {\n\tvec2 coords = gl_FragCoord.xy / uTexSize;\n\tvec4 color = texture2D(tColor, coords);\n\n\t#ifdef dOutlineEnable\n\t\tvec2 edgeDepth = calcEdgeDepth(coords);\n\t\tfloat edgeFlag = step(edgeDepth.x, uOutlineThreshold);\n    \tcolor.rgb *= edgeFlag;\n\n\t\tfloat viewDist = abs(getViewZ(edgeDepth.y));\n\t\tfloat fogFactor = smoothstep(uFogNear, uFogFar, viewDist) * (1.0 - edgeFlag);\n\t\tcolor.rgb = mix(color.rgb, uFogColor, fogFactor);\n\t#endif\n\n\t// occlusion needs to be handled after outline to darken them properly\n\t#ifdef dOcclusionEnable\n\t\tfloat depth = getDepth(coords);\n\t\tif (depth != 1.0) {\n\t\t\tfloat occlusionFactor = calcSSAO(coords, depth);\n\t\t\tcolor = mix(color, occlusionColor, uOcclusionBias * occlusionFactor);\n\t\t}\n\t#endif\n\n\tgl_FragColor = color;\n}\n");
//# sourceMappingURL=postprocessing.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-canvas3d/passes/postprocessing.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var PostprocessingSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util["a" /* QuadSchema */]), { tColor: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'ubyte', 'nearest'), tDepth: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'ubyte', 'nearest'), uTexSize: Object(renderable_schema["i" /* UniformSpec */])('v2'), dOrthographic: Object(renderable_schema["c" /* DefineSpec */])('number'), uNear: Object(renderable_schema["i" /* UniformSpec */])('f'), uFar: Object(renderable_schema["i" /* UniformSpec */])('f'), uFogNear: Object(renderable_schema["i" /* UniformSpec */])('f'), uFogFar: Object(renderable_schema["i" /* UniformSpec */])('f'), uFogColor: Object(renderable_schema["i" /* UniformSpec */])('v3'), dOcclusionEnable: Object(renderable_schema["c" /* DefineSpec */])('boolean'), dOcclusionKernelSize: Object(renderable_schema["c" /* DefineSpec */])('number'), uOcclusionBias: Object(renderable_schema["i" /* UniformSpec */])('f'), uOcclusionRadius: Object(renderable_schema["i" /* UniformSpec */])('f'), dOutlineEnable: Object(renderable_schema["c" /* DefineSpec */])('boolean'), uOutlineScale: Object(renderable_schema["i" /* UniformSpec */])('f'), uOutlineThreshold: Object(renderable_schema["i" /* UniformSpec */])('f'), dPackedDepth: Object(renderable_schema["c" /* DefineSpec */])('boolean') });
var PostprocessingParams = {
    occlusion: param_definition["ParamDefinition"].MappedStatic('off', {
        on: param_definition["ParamDefinition"].Group({
            kernelSize: param_definition["ParamDefinition"].Numeric(4, { min: 1, max: 32, step: 1 }),
            bias: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.01 }),
            radius: param_definition["ParamDefinition"].Numeric(64, { min: 0, max: 256, step: 1 }),
        }),
        off: param_definition["ParamDefinition"].Group({})
    }, { cycle: true, description: 'Darken occluded crevices with the ambient occlusion effect' }),
    outline: param_definition["ParamDefinition"].MappedStatic('off', {
        on: param_definition["ParamDefinition"].Group({
            scale: param_definition["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 1 }),
            threshold: param_definition["ParamDefinition"].Numeric(0.8, { min: 0, max: 5, step: 0.01 }),
        }),
        off: param_definition["ParamDefinition"].Group({})
    }, { cycle: true, description: 'Draw outline around 3D objects' })
};
function getPostprocessingRenderable(ctx, colorTexture, depthTexture, packedDepth, props) {
    var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(PostprocessingParams)), props);
    var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util["b" /* QuadValues */]), { tColor: mol_util["e" /* ValueCell */].create(colorTexture), tDepth: mol_util["e" /* ValueCell */].create(depthTexture), uTexSize: mol_util["e" /* ValueCell */].create(linear_algebra["Vec2"].create(colorTexture.getWidth(), colorTexture.getHeight())), dOrthographic: mol_util["e" /* ValueCell */].create(0), uNear: mol_util["e" /* ValueCell */].create(1), uFar: mol_util["e" /* ValueCell */].create(10000), uFogNear: mol_util["e" /* ValueCell */].create(10000), uFogFar: mol_util["e" /* ValueCell */].create(10000), uFogColor: mol_util["e" /* ValueCell */].create(linear_algebra["Vec3"].create(1, 1, 1)), dOcclusionEnable: mol_util["e" /* ValueCell */].create(p.occlusion.name === 'on'), dOcclusionKernelSize: mol_util["e" /* ValueCell */].create(p.occlusion.name === 'on' ? p.occlusion.params.kernelSize : 4), uOcclusionBias: mol_util["e" /* ValueCell */].create(p.occlusion.name === 'on' ? p.occlusion.params.bias : 0.5), uOcclusionRadius: mol_util["e" /* ValueCell */].create(p.occlusion.name === 'on' ? p.occlusion.params.radius : 64), dOutlineEnable: mol_util["e" /* ValueCell */].create(p.outline.name === 'on'), uOutlineScale: mol_util["e" /* ValueCell */].create((p.outline.name === 'on' ? p.outline.params.scale : 1) * ctx.pixelRatio), uOutlineThreshold: mol_util["e" /* ValueCell */].create(p.outline.name === 'on' ? p.outline.params.threshold : 0.8), dPackedDepth: mol_util["e" /* ValueCell */].create(packedDepth) });
    var schema = Object(tslib_es6["__assign"])({}, PostprocessingSchema);
    var shaderCode = Object(shader_code["f" /* ShaderCode */])('postprocessing', quad_vert["a" /* default */], postprocessing_frag);
    var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
    return Object(renderable["a" /* createComputeRenderable */])(renderItem, values);
}
var postprocessing_PostprocessingPass = /** @class */ (function () {
    function PostprocessingPass(webgl, camera, drawPass, props) {
        this.webgl = webgl;
        this.camera = camera;
        var gl = webgl.gl;
        this.target = webgl.createRenderTarget(gl.drawingBufferWidth, gl.drawingBufferHeight);
        this.props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(PostprocessingParams)), props);
        var colorTarget = drawPass.colorTarget, depthTexture = drawPass.depthTexture, packedDepth = drawPass.packedDepth;
        this.renderable = getPostprocessingRenderable(webgl, colorTarget.texture, depthTexture, packedDepth, this.props);
    }
    Object.defineProperty(PostprocessingPass.prototype, "enabled", {
        get: function () {
            return this.props.occlusion.name === 'on' || this.props.outline.name === 'on';
        },
        enumerable: false,
        configurable: true
    });
    PostprocessingPass.prototype.setSize = function (width, height) {
        this.target.setSize(width, height);
        mol_util["e" /* ValueCell */].update(this.renderable.values.uTexSize, linear_algebra["Vec2"].set(this.renderable.values.uTexSize.ref.value, width, height));
    };
    PostprocessingPass.prototype.setProps = function (props) {
        var _this = this;
        this.props = Object(immer_esm["b" /* produce */])(this.props, function (p) {
            if (props.occlusion !== undefined) {
                p.occlusion.name = props.occlusion.name;
                mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.dOcclusionEnable, props.occlusion.name === 'on');
                if (props.occlusion.name === 'on') {
                    p.occlusion.params = Object(tslib_es6["__assign"])({}, props.occlusion.params);
                    mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.dOcclusionKernelSize, props.occlusion.params.kernelSize);
                    mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.uOcclusionBias, props.occlusion.params.bias);
                    mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.uOcclusionRadius, props.occlusion.params.radius);
                }
            }
            if (props.outline !== undefined) {
                p.outline.name = props.outline.name;
                mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.dOutlineEnable, props.outline.name === 'on');
                if (props.outline.name === 'on') {
                    p.outline.params = Object(tslib_es6["__assign"])({}, props.outline.params);
                    mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.uOutlineScale, props.outline.params.scale);
                    mol_util["e" /* ValueCell */].updateIfChanged(_this.renderable.values.uOutlineThreshold, props.outline.params.threshold);
                }
            }
        });
        this.renderable.update();
    };
    PostprocessingPass.prototype.render = function (toDrawingBuffer) {
        mol_util["e" /* ValueCell */].update(this.renderable.values.uFar, this.camera.far);
        mol_util["e" /* ValueCell */].update(this.renderable.values.uNear, this.camera.near);
        mol_util["e" /* ValueCell */].update(this.renderable.values.uFogFar, this.camera.fogFar);
        mol_util["e" /* ValueCell */].update(this.renderable.values.uFogNear, this.camera.fogNear);
        mol_util["e" /* ValueCell */].update(this.renderable.values.dOrthographic, this.camera.state.mode === 'orthographic' ? 1 : 0);
        var _a = this.webgl, gl = _a.gl, state = _a.state;
        if (toDrawingBuffer) {
            this.webgl.unbindFramebuffer();
            gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight);
        }
        else {
            this.target.bind();
        }
        state.disable(gl.SCISSOR_TEST);
        state.disable(gl.BLEND);
        state.disable(gl.DEPTH_TEST);
        state.depthMask(false);
        this.renderable.render();
    };
    return PostprocessingPass;
}());

//# sourceMappingURL=postprocessing.js.map

/***/ }),
/* 319 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ MultiSampleParams; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ multi_sample_MultiSamplePass; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/compute/util.js
var util = __webpack_require__(148);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/schema.js
var renderable_schema = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-item.js
var render_item = __webpack_require__(99);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable.js
var renderable = __webpack_require__(98);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/camera.js + 1 modules
var mol_canvas3d_camera = __webpack_require__(232);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader/quad.vert.js
var quad_vert = __webpack_require__(205);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/compose.frag.js
/* harmony default export */ var compose_frag = ("\nprecision highp float;\nprecision highp sampler2D;\n\nuniform sampler2D tColor;\nuniform vec2 uTexSize;\nuniform float uWeight;\n\nvoid main() {\n    vec2 coords = gl_FragCoord.xy / uTexSize;\n    gl_FragColor = texture2D(tColor, coords) * uWeight;\n}\n");
//# sourceMappingURL=compose.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-canvas3d/passes/multi-sample.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var ComposeSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util["a" /* QuadSchema */]), { tColor: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'ubyte', 'nearest'), uTexSize: Object(renderable_schema["i" /* UniformSpec */])('v2'), uWeight: Object(renderable_schema["i" /* UniformSpec */])('f') });
function getComposeRenderable(ctx, colorTexture) {
    var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util["b" /* QuadValues */]), { tColor: mol_util["e" /* ValueCell */].create(colorTexture), uTexSize: mol_util["e" /* ValueCell */].create(linear_algebra["Vec2"].create(colorTexture.getWidth(), colorTexture.getHeight())), uWeight: mol_util["e" /* ValueCell */].create(1.0) });
    var schema = Object(tslib_es6["__assign"])({}, ComposeSchema);
    var shaderCode = Object(shader_code["f" /* ShaderCode */])('compose', quad_vert["a" /* default */], compose_frag);
    var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
    return Object(renderable["a" /* createComputeRenderable */])(renderItem, values);
}
var MultiSampleParams = {
    mode: param_definition["ParamDefinition"].Select('off', [['off', 'Off'], ['on', 'On'], ['temporal', 'Temporal']]),
    sampleLevel: param_definition["ParamDefinition"].Numeric(2, { min: 0, max: 5, step: 1 }),
};
var multi_sample_MultiSamplePass = /** @class */ (function () {
    function MultiSamplePass(webgl, camera, drawPass, postprocessing, props) {
        this.webgl = webgl;
        this.camera = camera;
        this.drawPass = drawPass;
        this.postprocessing = postprocessing;
        this.sampleIndex = -1;
        this.currentTime = 0;
        this.lastRenderTime = 0;
        var gl = webgl.gl;
        this.colorTarget = webgl.createRenderTarget(gl.drawingBufferWidth, gl.drawingBufferHeight);
        this.composeTarget = webgl.createRenderTarget(gl.drawingBufferWidth, gl.drawingBufferHeight);
        this.holdTarget = webgl.createRenderTarget(gl.drawingBufferWidth, gl.drawingBufferHeight);
        this.compose = getComposeRenderable(webgl, drawPass.colorTarget.texture);
        this.props = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(MultiSampleParams)), props);
    }
    Object.defineProperty(MultiSamplePass.prototype, "enabled", {
        get: function () {
            if (this.props.mode === 'temporal') {
                if (this.currentTime - this.lastRenderTime > 200) {
                    return this.sampleIndex !== -1;
                }
                else {
                    this.sampleIndex = 0;
                    return false;
                }
            }
            else if (this.props.mode === 'on') {
                return true;
            }
            else {
                return false;
            }
        },
        enumerable: false,
        configurable: true
    });
    MultiSamplePass.prototype.update = function (changed, currentTime) {
        if (changed)
            this.lastRenderTime = currentTime;
        this.currentTime = currentTime;
    };
    MultiSamplePass.prototype.setSize = function (width, height) {
        this.colorTarget.setSize(width, height);
        this.composeTarget.setSize(width, height);
        this.holdTarget.setSize(width, height);
        mol_util["e" /* ValueCell */].update(this.compose.values.uTexSize, linear_algebra["Vec2"].set(this.compose.values.uTexSize.ref.value, width, height));
    };
    MultiSamplePass.prototype.setProps = function (props) {
        if (props.mode !== undefined)
            this.props.mode = props.mode;
        if (props.sampleLevel !== undefined)
            this.props.sampleLevel = props.sampleLevel;
    };
    MultiSamplePass.prototype.render = function (toDrawingBuffer, transparentBackground) {
        if (this.props.mode === 'temporal') {
            this.renderTemporalMultiSample(toDrawingBuffer, transparentBackground);
        }
        else {
            this.renderMultiSample(toDrawingBuffer, transparentBackground);
        }
    };
    MultiSamplePass.prototype.renderMultiSample = function (toDrawingBuffer, transparentBackground) {
        var _a = this, camera = _a.camera, compose = _a.compose, composeTarget = _a.composeTarget, drawPass = _a.drawPass, postprocessing = _a.postprocessing, webgl = _a.webgl;
        var gl = webgl.gl, state = webgl.state;
        // based on the Multisample Anti-Aliasing Render Pass
        // contributed to three.js by bhouston / http://clara.io/
        //
        // This manual approach to MSAA re-renders the scene once for
        // each sample with camera jitter and accumulates the results.
        var offsetList = JitterVectors[Math.max(0, Math.min(this.props.sampleLevel, 5))];
        var baseSampleWeight = 1.0 / offsetList.length;
        var roundingRange = 1 / 32;
        camera.viewOffset.enabled = true;
        mol_util["e" /* ValueCell */].update(compose.values.tColor, postprocessing.enabled ? postprocessing.target.texture : drawPass.colorTarget.texture);
        compose.update();
        var width = drawPass.colorTarget.getWidth();
        var height = drawPass.colorTarget.getHeight();
        // render the scene multiple times, each slightly jitter offset
        // from the last and accumulate the results.
        for (var i = 0; i < offsetList.length; ++i) {
            var offset = offsetList[i];
            mol_canvas3d_camera["a" /* Camera */].setViewOffset(camera.viewOffset, width, height, offset[0], offset[1], width, height);
            camera.update();
            // the theory is that equal weights for each sample lead to an accumulation of rounding
            // errors. The following equation varies the sampleWeight per sample so that it is uniformly
            // distributed across a range of values whose rounding errors cancel each other out.
            var uniformCenteredDistribution = -0.5 + (i + 0.5) / offsetList.length;
            var sampleWeight = baseSampleWeight + roundingRange * uniformCenteredDistribution;
            mol_util["e" /* ValueCell */].update(compose.values.uWeight, sampleWeight);
            // render scene and optionally postprocess
            drawPass.render(false, transparentBackground);
            if (postprocessing.enabled)
                postprocessing.render(false);
            // compose rendered scene with compose target
            composeTarget.bind();
            gl.viewport(0, 0, width, height);
            state.enable(gl.BLEND);
            state.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
            state.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
            state.disable(gl.DEPTH_TEST);
            state.disable(gl.SCISSOR_TEST);
            state.depthMask(false);
            if (i === 0) {
                state.clearColor(0, 0, 0, 0);
                gl.clear(gl.COLOR_BUFFER_BIT);
            }
            compose.render();
        }
        mol_util["e" /* ValueCell */].update(compose.values.uWeight, 1.0);
        mol_util["e" /* ValueCell */].update(compose.values.tColor, composeTarget.texture);
        compose.update();
        if (toDrawingBuffer) {
            webgl.unbindFramebuffer();
        }
        else {
            this.colorTarget.bind();
        }
        gl.viewport(0, 0, width, height);
        state.disable(gl.BLEND);
        compose.render();
        camera.viewOffset.enabled = false;
        camera.update();
    };
    MultiSamplePass.prototype.renderTemporalMultiSample = function (toDrawingBuffer, transparentBackground) {
        var _a = this, camera = _a.camera, compose = _a.compose, composeTarget = _a.composeTarget, holdTarget = _a.holdTarget, postprocessing = _a.postprocessing, drawPass = _a.drawPass, webgl = _a.webgl;
        var gl = webgl.gl, state = webgl.state;
        // based on the Multisample Anti-Aliasing Render Pass
        // contributed to three.js by bhouston / http://clara.io/
        //
        // This manual approach to MSAA re-renders the scene once for
        // each sample with camera jitter and accumulates the results.
        var offsetList = JitterVectors[Math.max(0, Math.min(this.props.sampleLevel, 5))];
        if (this.sampleIndex === -1)
            return;
        if (this.sampleIndex >= offsetList.length) {
            this.sampleIndex = -1;
            return;
        }
        var i = this.sampleIndex;
        if (i === 0) {
            drawPass.render(false, transparentBackground);
            if (postprocessing.enabled)
                postprocessing.render(false);
            mol_util["e" /* ValueCell */].update(compose.values.uWeight, 1.0);
            mol_util["e" /* ValueCell */].update(compose.values.tColor, postprocessing.enabled ? postprocessing.target.texture : drawPass.colorTarget.texture);
            compose.update();
            holdTarget.bind();
            state.disable(gl.BLEND);
            compose.render();
        }
        var sampleWeight = 1.0 / offsetList.length;
        camera.viewOffset.enabled = true;
        mol_util["e" /* ValueCell */].update(compose.values.tColor, postprocessing.enabled ? postprocessing.target.texture : drawPass.colorTarget.texture);
        mol_util["e" /* ValueCell */].update(compose.values.uWeight, sampleWeight);
        compose.update();
        var width = drawPass.colorTarget.getWidth();
        var height = drawPass.colorTarget.getHeight();
        // render the scene multiple times, each slightly jitter offset
        // from the last and accumulate the results.
        var numSamplesPerFrame = Math.pow(2, this.props.sampleLevel);
        for (var i_1 = 0; i_1 < numSamplesPerFrame; ++i_1) {
            var offset = offsetList[this.sampleIndex];
            mol_canvas3d_camera["a" /* Camera */].setViewOffset(camera.viewOffset, width, height, offset[0], offset[1], width, height);
            camera.update();
            // render scene and optionally postprocess
            drawPass.render(false, transparentBackground);
            if (postprocessing.enabled)
                postprocessing.render(false);
            // compose rendered scene with compose target
            composeTarget.bind();
            state.enable(gl.BLEND);
            state.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
            state.blendFuncSeparate(gl.ONE, gl.ONE, gl.ONE, gl.ONE);
            state.disable(gl.DEPTH_TEST);
            state.disable(gl.SCISSOR_TEST);
            state.depthMask(false);
            if (this.sampleIndex === 0) {
                state.clearColor(0, 0, 0, 0);
                gl.clear(gl.COLOR_BUFFER_BIT);
            }
            compose.render();
            this.sampleIndex += 1;
            if (this.sampleIndex >= offsetList.length)
                break;
        }
        var accumulationWeight = this.sampleIndex * sampleWeight;
        if (accumulationWeight > 0) {
            mol_util["e" /* ValueCell */].update(compose.values.uWeight, 1.0);
            mol_util["e" /* ValueCell */].update(compose.values.tColor, composeTarget.texture);
            compose.update();
            if (toDrawingBuffer) {
                webgl.unbindFramebuffer();
            }
            else {
                this.colorTarget.bind();
            }
            gl.viewport(0, 0, width, height);
            state.disable(gl.BLEND);
            compose.render();
        }
        if (accumulationWeight < 1.0) {
            mol_util["e" /* ValueCell */].update(compose.values.uWeight, 1.0 - accumulationWeight);
            mol_util["e" /* ValueCell */].update(compose.values.tColor, holdTarget.texture);
            compose.update();
            if (toDrawingBuffer) {
                webgl.unbindFramebuffer();
            }
            else {
                this.colorTarget.bind();
            }
            gl.viewport(0, 0, width, height);
            if (accumulationWeight === 0)
                state.disable(gl.BLEND);
            else
                state.enable(gl.BLEND);
            compose.render();
        }
        camera.viewOffset.enabled = false;
        camera.update();
        if (this.sampleIndex >= offsetList.length)
            this.sampleIndex = -1;
    };
    return MultiSamplePass;
}());

var JitterVectors = [
    [
        [0, 0]
    ],
    [
        [4, 4], [-4, -4]
    ],
    [
        [-2, -6], [6, -2], [-6, 2], [2, 6]
    ],
    [
        [1, -3], [-1, 3], [5, 1], [-3, -5],
        [-5, 5], [-7, -1], [3, 7], [7, -7]
    ],
    [
        [1, 1], [-1, -3], [-3, 2], [4, -1],
        [-5, -2], [2, 5], [5, 3], [3, -5],
        [-2, 6], [0, -7], [-4, -6], [-6, 4],
        [-8, 0], [7, -4], [6, 7], [-7, -8]
    ],
    [
        [-4, -7], [-7, -5], [-3, -5], [-5, -4],
        [-1, -4], [-2, -2], [-6, -1], [-4, 0],
        [-7, 1], [-1, 2], [-6, 3], [-3, 3],
        [-7, 6], [-3, 6], [-5, 7], [-1, 7],
        [5, -7], [1, -6], [6, -5], [4, -4],
        [2, -3], [7, -2], [1, -1], [4, -1],
        [2, 1], [6, 2], [0, 4], [4, 4],
        [2, 5], [7, 5], [5, 6], [3, 7]
    ]
];
JitterVectors.forEach(function (offsetList) {
    offsetList.forEach(function (offset) {
        // 0.0625 = 1 / 16
        offset[0] *= 0.0625;
        offset[1] *= 0.0625;
    });
});
//# sourceMappingURL=multi-sample.js.map

/***/ }),
/* 320 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureFocusRepresentationTags", function() { return StructureFocusRepresentationTags; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureFocusRepresentation", function() { return StructureFocusRepresentation; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_props_computed_representations_interactions__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(334);
/* harmony import */ var _mol_model_props_computed_themes_interaction_type__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(330);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(4);
/* harmony import */ var _mol_plugin_state_helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(162);
/* harmony import */ var _mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(28);
/* harmony import */ var _behavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(170);
/* harmony import */ var _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(10);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(13);
/* harmony import */ var _mol_theme_size__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(150);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(2);
/* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(26);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var StructureFocusRepresentationParams = function (plugin) {
    var reprParams = _mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Representation.StructureRepresentation3D.definition.params(void 0, plugin);
    return {
        expandRadius: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Numeric(5, { min: 1, max: 10, step: 1 }),
        targetParams: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Group(reprParams, {
            label: 'Target',
            customDefault: Object(_mol_plugin_state_helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_4__["createStructureRepresentationParams"])(plugin, void 0, { type: 'ball-and-stick', size: 'physical', typeParams: { sizeFactor: 0.26, alpha: 0.51 } })
        }),
        surroundingsParams: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Group(reprParams, {
            label: 'Surroundings',
            customDefault: Object(_mol_plugin_state_helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_4__["createStructureRepresentationParams"])(plugin, void 0, { type: 'ball-and-stick', size: 'physical', typeParams: { sizeFactor: 0.16 } })
        }),
        nciParams: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Group(reprParams, {
            label: 'Non-covalent Int.',
            customDefault: Object(_mol_plugin_state_helpers_structure_representation_params__WEBPACK_IMPORTED_MODULE_4__["createStructureRepresentationParams"])(plugin, void 0, {
                type: _mol_model_props_computed_representations_interactions__WEBPACK_IMPORTED_MODULE_1__[/* InteractionsRepresentationProvider */ "a"],
                color: _mol_model_props_computed_themes_interaction_type__WEBPACK_IMPORTED_MODULE_2__[/* InteractionTypeColorThemeProvider */ "a"],
                size: _mol_theme_size__WEBPACK_IMPORTED_MODULE_9__[/* SizeTheme */ "a"].BuiltIn.uniform
            })
        }),
        components: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].MultiSelect(FocusComponents, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].arrayToOptions(FocusComponents)),
        excludeTargetFromSurroundings: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Boolean(false, { label: 'Exclude Target', description: 'Exclude the focus "target" from the surroudings component.' }),
        ignoreHydrogens: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Boolean(false)
    };
};
var FocusComponents = ['target', 'surroundings', 'interactions'];
var StructureFocusRepresentationTags;
(function (StructureFocusRepresentationTags) {
    StructureFocusRepresentationTags["TargetSel"] = "structure-focus-target-sel";
    StructureFocusRepresentationTags["TargetRepr"] = "structure-focus-target-repr";
    StructureFocusRepresentationTags["SurrSel"] = "structure-focus-surr-sel";
    StructureFocusRepresentationTags["SurrRepr"] = "structure-focus-surr-repr";
    StructureFocusRepresentationTags["SurrNciRepr"] = "structure-focus-surr-nci-repr";
})(StructureFocusRepresentationTags || (StructureFocusRepresentationTags = {}));
var TagSet = new Set([StructureFocusRepresentationTags.TargetSel, StructureFocusRepresentationTags.TargetRepr, StructureFocusRepresentationTags.SurrSel, StructureFocusRepresentationTags.SurrRepr, StructureFocusRepresentationTags.SurrNciRepr]);
var StructureFocusRepresentationBehavior = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StructureFocusRepresentationBehavior, _super);
    function StructureFocusRepresentationBehavior() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.currentSource = void 0;
        return _this;
    }
    Object.defineProperty(StructureFocusRepresentationBehavior.prototype, "surrLabel", {
        get: function () { return "[Focus] Surroundings (" + this.params.expandRadius + " \u00C5)"; },
        enumerable: false,
        configurable: true
    });
    StructureFocusRepresentationBehavior.prototype.getReprParams = function (reprParams) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.params.targetParams), { type: {
                name: reprParams.type.name,
                params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, reprParams.type.params), { ignoreHydrogens: this.params.ignoreHydrogens })
            } });
    };
    StructureFocusRepresentationBehavior.prototype.ensureShape = function (cell) {
        var state = this.plugin.state.data, tree = state.tree;
        var builder = state.build();
        var refs = _mol_state__WEBPACK_IMPORTED_MODULE_8__["StateSelection"].findUniqueTagsInSubtree(tree, cell.transform.ref, TagSet);
        // Selections
        if (!refs[StructureFocusRepresentationTags.TargetSel]) {
            refs[StructureFocusRepresentationTags.TargetSel] = builder
                .to(cell)
                .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromBundle, { bundle: _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Bundle.Empty, label: '[Focus] Target' }, { tags: StructureFocusRepresentationTags.TargetSel }).ref;
        }
        if (!refs[StructureFocusRepresentationTags.SurrSel]) {
            refs[StructureFocusRepresentationTags.SurrSel] = builder
                .to(cell)
                .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromExpression, { expression: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_7__["MolScriptBuilder"].struct.generator.empty(), label: this.surrLabel }, { tags: StructureFocusRepresentationTags.SurrSel }).ref;
        }
        var components = this.params.components;
        // Representations
        if (components.indexOf('target') >= 0 && !refs[StructureFocusRepresentationTags.TargetRepr]) {
            refs[StructureFocusRepresentationTags.TargetRepr] = builder
                .to(refs[StructureFocusRepresentationTags.TargetSel])
                .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Representation.StructureRepresentation3D, this.getReprParams(this.params.targetParams), { tags: StructureFocusRepresentationTags.TargetRepr }).ref;
        }
        if (components.indexOf('surroundings') >= 0 && !refs[StructureFocusRepresentationTags.SurrRepr]) {
            refs[StructureFocusRepresentationTags.SurrRepr] = builder
                .to(refs[StructureFocusRepresentationTags.SurrSel])
                .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Representation.StructureRepresentation3D, this.getReprParams(this.params.surroundingsParams), { tags: StructureFocusRepresentationTags.SurrRepr }).ref;
        }
        if (components.indexOf('interactions') >= 0 && !refs[StructureFocusRepresentationTags.SurrNciRepr]) {
            refs[StructureFocusRepresentationTags.SurrNciRepr] = builder
                .to(refs[StructureFocusRepresentationTags.SurrSel])
                .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Representation.StructureRepresentation3D, this.params.nciParams, { tags: StructureFocusRepresentationTags.SurrNciRepr }).ref;
        }
        return { state: state, builder: builder, refs: refs };
    };
    StructureFocusRepresentationBehavior.prototype.clear = function (root) {
        var state = this.plugin.state.data;
        this.currentSource = void 0;
        var foci = state.select(_mol_state__WEBPACK_IMPORTED_MODULE_8__["StateSelection"].Generators.byRef(root).subtree().withTag(StructureFocusRepresentationTags.TargetSel));
        var surrs = state.select(_mol_state__WEBPACK_IMPORTED_MODULE_8__["StateSelection"].Generators.byRef(root).subtree().withTag(StructureFocusRepresentationTags.SurrSel));
        if (foci.length === 0 && surrs.length === 0)
            return;
        var update = state.build();
        var bundle = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Bundle.Empty;
        for (var _i = 0, foci_1 = foci; _i < foci_1.length; _i++) {
            var f = foci_1[_i];
            update.to(f).update(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromBundle, function (old) { return (Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { bundle: bundle })); });
        }
        var expression = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_7__["MolScriptBuilder"].struct.generator.empty();
        for (var _a = 0, surrs_1 = surrs; _a < surrs_1.length; _a++) {
            var s = surrs_1[_a];
            update.to(s).update(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromExpression, function (old) { return (Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { expression: expression })); });
        }
        return _commands__WEBPACK_IMPORTED_MODULE_11__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true, doNotUpdateCurrent: true } });
    };
    StructureFocusRepresentationBehavior.prototype.focus = function (sourceLoci) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var parent, loci, residueLoci, residueBundle, target, surroundings, _a, state, builder, refs;
            var _this = this;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        parent = this.plugin.helpers.substructureParent.get(sourceLoci.structure);
                        if (!parent || !parent.obj)
                            return [2 /*return*/];
                        this.currentSource = sourceLoci;
                        loci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Loci.remap(sourceLoci, parent.obj.data);
                        residueLoci = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Loci.extendToWholeResidues(loci);
                        residueBundle = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Bundle.fromLoci(residueLoci);
                        target = _mol_model_structure__WEBPACK_IMPORTED_MODULE_3__["StructureElement"].Bundle.toExpression(residueBundle);
                        surroundings = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_7__["MolScriptBuilder"].struct.modifier.includeSurroundings({
                            0: target,
                            radius: this.params.expandRadius,
                            'as-whole-residues': true
                        });
                        if (this.params.excludeTargetFromSurroundings) {
                            surroundings = _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_7__["MolScriptBuilder"].struct.modifier.exceptBy({
                                0: surroundings,
                                by: target
                            });
                        }
                        _a = this.ensureShape(parent), state = _a.state, builder = _a.builder, refs = _a.refs;
                        builder.to(refs[StructureFocusRepresentationTags.TargetSel]).update(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromBundle, function (old) { return (Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { bundle: residueBundle })); });
                        builder.to(refs[StructureFocusRepresentationTags.SurrSel]).update(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_5__["StateTransforms"].Model.StructureSelectionFromExpression, function (old) { return (Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { expression: surroundings, label: _this.surrLabel })); });
                        return [4 /*yield*/, _commands__WEBPACK_IMPORTED_MODULE_11__["PluginCommands"].State.Update(this.plugin, { state: state, tree: builder, options: { doNotLogTiming: true, doNotUpdateCurrent: true } })];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureFocusRepresentationBehavior.prototype.register = function (ref) {
        var _this = this;
        this.subscribeObservable(this.plugin.managers.structure.focus.behaviors.current, function (entry) {
            if (entry)
                _this.focus(entry.loci);
            else
                _this.clear(_mol_state__WEBPACK_IMPORTED_MODULE_8__["StateTransform"].RootRef);
        });
    };
    StructureFocusRepresentationBehavior.prototype.update = function (params) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var old, state, builder, all, components, hasComponent, _i, _a, repr, _b, _c, repr, _d, _e, repr;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        old = this.params;
                        this.params = params;
                        if (old.excludeTargetFromSurroundings !== params.excludeTargetFromSurroundings) {
                            if (this.currentSource) {
                                this.focus(this.currentSource);
                            }
                            return [2 /*return*/, true];
                        }
                        state = this.plugin.state.data;
                        builder = state.build();
                        all = _mol_state__WEBPACK_IMPORTED_MODULE_8__["StateSelection"].Generators.root.subtree();
                        components = this.params.components;
                        hasComponent = components.indexOf('target') >= 0;
                        for (_i = 0, _a = state.select(all.withTag(StructureFocusRepresentationTags.TargetRepr)); _i < _a.length; _i++) {
                            repr = _a[_i];
                            if (!hasComponent)
                                builder.delete(repr.transform.ref);
                            else
                                builder.to(repr).update(this.getReprParams(this.params.targetParams));
                        }
                        hasComponent = components.indexOf('surroundings') >= 0;
                        for (_b = 0, _c = state.select(all.withTag(StructureFocusRepresentationTags.SurrRepr)); _b < _c.length; _b++) {
                            repr = _c[_b];
                            if (!hasComponent)
                                builder.delete(repr.transform.ref);
                            else
                                builder.to(repr).update(this.getReprParams(this.params.surroundingsParams));
                        }
                        hasComponent = components.indexOf('interactions') >= 0;
                        for (_d = 0, _e = state.select(all.withTag(StructureFocusRepresentationTags.SurrNciRepr)); _d < _e.length; _d++) {
                            repr = _e[_d];
                            if (!hasComponent)
                                builder.delete(repr.transform.ref);
                            else
                                builder.to(repr).update(this.params.nciParams);
                        }
                        return [4 /*yield*/, _commands__WEBPACK_IMPORTED_MODULE_11__["PluginCommands"].State.Update(this.plugin, { state: state, tree: builder, options: { doNotLogTiming: true, doNotUpdateCurrent: true } })];
                    case 1:
                        _f.sent();
                        if (params.expandRadius !== old.expandRadius) {
                            if (this.currentSource) {
                                this.focus(this.currentSource);
                            }
                            return [2 /*return*/, true];
                        }
                        return [2 /*return*/, true];
                }
            });
        });
    };
    return StructureFocusRepresentationBehavior;
}(_behavior__WEBPACK_IMPORTED_MODULE_6__["PluginBehavior"].WithSubscribers));
var StructureFocusRepresentation = _behavior__WEBPACK_IMPORTED_MODULE_6__["PluginBehavior"].create({
    name: 'create-structure-focus-representation',
    display: { name: 'Structure Focus Representation' },
    category: 'interaction',
    ctor: StructureFocusRepresentationBehavior,
    params: function (_, plugin) { return StructureFocusRepresentationParams(plugin); }
});
//# sourceMappingURL=structure-focus-representation.js.map

/***/ }),
/* 321 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Scheduler; });
var Scheduler = /*@__PURE__*/ (function () {
    function Scheduler(SchedulerAction, now) {
        if (now === void 0) {
            now = Scheduler.now;
        }
        this.SchedulerAction = SchedulerAction;
        this.now = now;
    }
    Scheduler.prototype.schedule = function (work, delay, state) {
        if (delay === void 0) {
            delay = 0;
        }
        return new this.SchedulerAction(this, work).schedule(state, delay);
    };
    Scheduler.now = function () { return Date.now(); };
    return Scheduler;
}());

//# sourceMappingURL=Scheduler.js.map


/***/ }),
/* 322 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StructureComponentControls", function() { return /* binding */ components_StructureComponentControls; });
__webpack_require__.d(__webpack_exports__, "AddComponentControls", function() { return /* binding */ components_AddComponentControls; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-representation-params.js
var structure_representation_params = __webpack_require__(162);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/component.js + 2 modules
var structure_component = __webpack_require__(246);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/hierarchy.js + 1 modules
var hierarchy = __webpack_require__(255);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/action-menu.js
var action_menu = __webpack_require__(56);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/update-transform.js
var update_transform = __webpack_require__(183);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/generic.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var generic_GenericEntryListControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(GenericEntryListControls, _super);
    function GenericEntryListControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(GenericEntryListControls.prototype, "current", {
        get: function () {
            return this.plugin.managers.structure.hierarchy.behaviors.selection;
        },
        enumerable: false,
        configurable: true
    });
    GenericEntryListControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.current, function () { return _this.forceUpdate(); });
    };
    Object.defineProperty(GenericEntryListControls.prototype, "unitcell", {
        get: function () {
            var _a;
            var selection = this.plugin.managers.structure.hierarchy.selection;
            if (selection.structures.length === 0)
                return null;
            var refs = [];
            for (var _i = 0, _b = selection.structures; _i < _b.length; _i++) {
                var s = _b[_i];
                var model = s.model;
                if ((model === null || model === void 0 ? void 0 : model.unitcell) && ((_a = model.unitcell) === null || _a === void 0 ? void 0 : _a.cell.obj))
                    refs.push(model.unitcell);
            }
            if (refs.length === 0)
                return null;
            return react["createElement"](generic_GenericEntry, { refs: refs, labelMultiple: 'Unit Cells' });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(GenericEntryListControls.prototype, "customControls", {
        get: function () {
            var _this = this;
            var controls = [];
            this.plugin.genericRepresentationControls.forEach(function (provider, key) {
                var _a = provider(_this.plugin.managers.structure.hierarchy.selection), refs = _a[0], labelMultiple = _a[1];
                if (refs.length > 0) {
                    controls.push(react["createElement"]("div", { key: key },
                        react["createElement"](generic_GenericEntry, { refs: refs, labelMultiple: labelMultiple })));
                }
            });
            return controls.length > 0 ? controls : null;
        },
        enumerable: false,
        configurable: true
    });
    GenericEntryListControls.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { style: { marginTop: '6px' } },
                this.unitcell,
                this.customControls));
    };
    return GenericEntryListControls;
}(base["PurePluginUIComponent"]));

var generic_GenericEntry = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(GenericEntry, _super);
    function GenericEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showOptions: false };
        _this.toggleVisibility = function (e) {
            e.preventDefault();
            _this.plugin.managers.structure.hierarchy.toggleVisibility(_this.props.refs);
            e.currentTarget.blur();
        };
        _this.highlight = function (e) {
            e.preventDefault();
            if (!_this.pivot.cell.parent)
                return;
            commands["PluginCommands"].Interactivity.Object.Highlight(_this.plugin, {
                state: _this.pivot.cell.parent,
                ref: _this.props.refs.map(function (c) { return c.cell.transform.ref; })
            });
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            commands["PluginCommands"].Interactivity.ClearHighlights(_this.plugin);
        };
        _this.focus = function (e) {
            var _a;
            e.preventDefault();
            var allHidden = true;
            for (var _i = 0, _b = _this.props.refs; _i < _b.length; _i++) {
                var uc = _b[_i];
                if (!uc.cell.state.isHidden) {
                    allHidden = false;
                    break;
                }
            }
            if (allHidden) {
                _this.plugin.managers.structure.hierarchy.toggleVisibility(_this.props.refs, 'show');
            }
            var loci = [];
            for (var _c = 0, _d = _this.props.refs; _c < _d.length; _c++) {
                var uc = _d[_c];
                if (uc.cell.state.isHidden) {
                    continue;
                }
                var l = (_a = uc.cell.obj) === null || _a === void 0 ? void 0 : _a.data.repr.getLoci();
                if (l)
                    loci.push(l);
            }
            _this.plugin.managers.camera.focusLoci(loci);
        };
        _this.toggleOptions = function () { return _this.setState({ showOptions: !_this.state.showOptions }); };
        return _this;
    }
    GenericEntry.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            var _a;
            if (mol_state["State"].ObjectEvent.isCell(e, (_a = _this.pivot) === null || _a === void 0 ? void 0 : _a.cell))
                _this.forceUpdate();
        });
    };
    Object.defineProperty(GenericEntry.prototype, "pivot", {
        get: function () { return this.props.refs[0]; },
        enumerable: false,
        configurable: true
    });
    GenericEntry.prototype.render = function () {
        var _a = this.props, refs = _a.refs, labelMultiple = _a.labelMultiple;
        if (refs.length === 0)
            return null;
        var pivot = refs[0];
        var label, description;
        if (refs.length === 1) {
            var obj = pivot.cell.obj;
            if (!obj)
                return null;
            label = obj === null || obj === void 0 ? void 0 : obj.label;
            description = obj === null || obj === void 0 ? void 0 : obj.description;
        }
        else {
            label = refs.length + " " + (labelMultiple || 'Objects');
        }
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"]("button", { className: 'msp-form-control msp-control-button-label', title: label + ". Click to focus.", onClick: this.focus, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight, style: { textAlign: 'left' } },
                    label,
                    " ",
                    react["createElement"]("small", null, description)),
                react["createElement"](common["IconButton"], { svg: pivot.cell.state.isHidden ? icons["VisibilityOffOutlinedSvg"] : icons["VisibilityOutlinedSvg"], toggleState: false, className: 'msp-form-control', onClick: this.toggleVisibility, title: "" + (pivot.cell.state.isHidden ? 'Show' : 'Hide'), small: true, flex: true }),
                refs.length === 1 && react["createElement"](common["IconButton"], { svg: icons["MoreHorizSvg"], className: 'msp-form-control', onClick: this.toggleOptions, title: 'Options', toggleState: this.state.showOptions, flex: true })),
            (refs.length === 1 && this.state.showOptions && pivot.cell.parent) && react["createElement"](react["Fragment"], null,
                react["createElement"]("div", { className: 'msp-control-offset' },
                    react["createElement"](update_transform["UpdateTransformControl"], { state: pivot.cell.parent, transform: pivot.cell.transform, customHeader: 'none', autoHideApply: true }))));
    };
    return GenericEntry;
}(base["PurePluginUIComponent"]));

//# sourceMappingURL=generic.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/components.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var components_StructureComponentControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureComponentControls, _super);
    function StructureComponentControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    StructureComponentControls.prototype.defaultState = function () {
        return {
            header: 'Components',
            isCollapsed: false,
            isDisabled: false,
            brand: { accent: 'blue', svg: icons["CubeOutlineSvg"] }
        };
    };
    StructureComponentControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) { return _this.setState({
            description: hierarchy["StructureHierarchyManager"].getSelectedStructuresDescription(_this.plugin)
        }); });
    };
    StructureComponentControls.prototype.renderControls = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"](components_ComponentEditorControls, null),
            react["createElement"](components_ComponentListControls, null),
            react["createElement"](generic_GenericEntryListControls, null));
    };
    return StructureComponentControls;
}(base["CollapsableControls"]));

var components_ComponentEditorControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ComponentEditorControls, _super);
    function ComponentEditorControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isEmpty: true,
            isBusy: false,
            canUndo: false
        };
        _this.togglePreset = _this.toggleAction('preset');
        _this.toggleAdd = _this.toggleAction('add');
        _this.toggleOptions = _this.toggleAction('options');
        _this.hideAction = function () { return _this.setState({ action: void 0 }); };
        _this.applyPreset = function (item) {
            _this.hideAction();
            if (!item)
                return;
            var mng = _this.plugin.managers.structure;
            var structures = mng.hierarchy.selection.structures;
            if (item.value === null)
                mng.component.clear(structures);
            else
                mng.component.applyPreset(structures, item.value);
        };
        _this.undo = function () {
            var task = _this.plugin.state.data.undo();
            if (task)
                _this.plugin.runTask(task);
        };
        return _this;
    }
    Object.defineProperty(ComponentEditorControls.prototype, "isDisabled", {
        get: function () {
            return this.state.isBusy || this.state.isEmpty;
        },
        enumerable: false,
        configurable: true
    });
    ComponentEditorControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) { return _this.setState({
            action: _this.state.action !== 'options' || c.structures.length === 0 ? void 0 : 'options',
            isEmpty: c.structures.length === 0
        }); });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v, action: _this.state.action !== 'options' ? void 0 : 'options' });
        });
        this.subscribe(this.plugin.state.data.events.historyUpdated, function (_a) {
            var state = _a.state;
            _this.setState({ canUndo: state.canUndo });
        });
    };
    ComponentEditorControls.prototype.toggleAction = function (action) {
        var _this = this;
        return function () { return _this.setState({ action: _this.state.action === action ? void 0 : action }); };
    };
    Object.defineProperty(ComponentEditorControls.prototype, "presetControls", {
        get: function () {
            return react["createElement"](action_menu["a" /* ActionMenu */], { items: this.presetActions, onSelect: this.applyPreset });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ComponentEditorControls.prototype, "presetActions", {
        get: function () {
            var pivot = this.plugin.managers.structure.component.pivotStructure;
            var providers = this.plugin.builders.structure.representation.getPresets(pivot === null || pivot === void 0 ? void 0 : pivot.cell.obj);
            return action_menu["a" /* ActionMenu */].createItems(providers, { label: function (p) { return p.display.name; }, category: function (p) { return p.display.group; }, description: function (p) { return p.display.description; } });
        },
        enumerable: false,
        configurable: true
    });
    ComponentEditorControls.prototype.render = function () {
        var undoTitle = this.state.canUndo
            ? "Undo " + this.plugin.state.data.latestUndoLabel
            : 'Some mistakes of the past can be undone.';
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["ToggleButton"], { icon: icons["BookmarksOutlinedSvg"], label: 'Preset', title: 'Apply a representation preset for the current structure(s).', toggle: this.togglePreset, isSelected: this.state.action === 'preset', disabled: this.isDisabled }),
                react["createElement"](common["ToggleButton"], { icon: icons["AddSvg"], label: 'Add', title: 'Add a new representation component for a selection.', toggle: this.toggleAdd, isSelected: this.state.action === 'add', disabled: this.isDisabled }),
                react["createElement"](common["ToggleButton"], { icon: icons["TuneSvg"], label: '', title: 'Options that are applied to all applicable representations.', style: { flex: '0 0 40px', padding: 0 }, toggle: this.toggleOptions, isSelected: this.state.action === 'options', disabled: this.isDisabled }),
                react["createElement"](common["IconButton"], { svg: icons["RestoreSvg"], className: 'msp-flex-item', flex: '40px', onClick: this.undo, disabled: !this.state.canUndo || this.isDisabled, title: undoTitle })),
            this.state.action === 'preset' && this.presetControls,
            this.state.action === 'add' && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](components_AddComponentControls, { onApply: this.hideAction })),
            this.state.action === 'options' && react["createElement"]("div", { className: 'msp-control-offset' },
                react["createElement"](components_ComponentOptionsControls, { isDisabled: this.isDisabled })));
    };
    return ComponentEditorControls;
}(base["PurePluginUIComponent"]));
var components_AddComponentControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(AddComponentControls, _super);
    function AddComponentControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = _this.createState();
        _this.apply = function () {
            var structures = _this.props.forSelection ? _this.currentStructures : _this.selectedStructures;
            _this.props.onApply();
            _this.plugin.managers.structure.component.add(_this.state.values, structures);
        };
        _this.paramsChanged = function (values) { return _this.setState({ values: values }); };
        return _this;
    }
    AddComponentControls.prototype.createState = function () {
        var params = structure_component["StructureComponentManager"].getAddParams(this.plugin);
        return { params: params, values: param_definition["ParamDefinition"].getDefaultValues(params) };
    };
    Object.defineProperty(AddComponentControls.prototype, "selectedStructures", {
        get: function () {
            return this.plugin.managers.structure.component.currentStructures;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(AddComponentControls.prototype, "currentStructures", {
        get: function () {
            return this.plugin.managers.structure.hierarchy.current.structures;
        },
        enumerable: false,
        configurable: true
    });
    AddComponentControls.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            react["createElement"](parameters["ParameterControls"], { params: this.state.params, values: this.state.values, onChangeValues: this.paramsChanged }),
            react["createElement"](common["Button"], { icon: icons["AddSvg"], title: 'Use Selection and optional Representation to create a new Component.', className: 'msp-btn-commit msp-btn-commit-on', onClick: this.apply, style: { marginTop: '1px' } }, "Create Component"));
    };
    return AddComponentControls;
}(base["PurePluginUIComponent"]));

var components_ComponentOptionsControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ComponentOptionsControls, _super);
    function ComponentOptionsControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.update = function (options) { return _this.plugin.managers.structure.component.setOptions(options); };
        return _this;
    }
    ComponentOptionsControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.component.events.optionsUpdated, function () { return _this.forceUpdate(); });
    };
    ComponentOptionsControls.prototype.render = function () {
        return react["createElement"](parameters["ParameterControls"], { params: structure_component["StructureComponentManager"].OptionsParams, values: this.plugin.managers.structure.component.state.options, onChangeValues: this.update, isDisabled: this.props.isDisabled });
    };
    return ComponentOptionsControls;
}(base["PurePluginUIComponent"]));
var components_ComponentListControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ComponentListControls, _super);
    function ComponentListControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ComponentListControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () {
            _this.forceUpdate();
        });
    };
    ComponentListControls.prototype.render = function () {
        var componentGroups = this.plugin.managers.structure.hierarchy.currentComponentGroups;
        if (componentGroups.length === 0)
            return null;
        return react["createElement"]("div", { style: { marginTop: '6px' } }, componentGroups.map(function (g) { return react["createElement"](components_StructureComponentGroup, { key: g[0].cell.transform.ref, group: g }); }));
    };
    return ComponentListControls;
}(base["PurePluginUIComponent"]));
var components_StructureComponentGroup = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureComponentGroup, _super);
    function StructureComponentGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { action: void 0 };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            _this.plugin.managers.structure.component.toggleVisibility(_this.props.group);
        };
        _this.selectAction = function (item) {
            if (!item)
                return;
            _this.setState({ action: void 0 });
            (item === null || item === void 0 ? void 0 : item.value)();
        };
        _this.remove = function () { return _this.plugin.managers.structure.hierarchy.remove(_this.props.group, true); };
        _this.toggleAction = function () { return _this.setState({ action: _this.state.action === 'action' ? void 0 : 'action' }); };
        _this.toggleLabel = function () { return _this.setState({ action: _this.state.action === 'label' ? void 0 : 'label' }); };
        _this.highlight = function (e) {
            e.preventDefault();
            if (!_this.props.group[0].cell.parent)
                return;
            commands["PluginCommands"].Interactivity.Object.Highlight(_this.plugin, { state: _this.props.group[0].cell.parent, ref: _this.props.group.map(function (c) { return c.cell.transform.ref; }) });
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            commands["PluginCommands"].Interactivity.ClearHighlights(_this.plugin);
        };
        _this.focus = function () {
            var allHidden = true;
            for (var _i = 0, _a = _this.props.group; _i < _a.length; _i++) {
                var c = _a[_i];
                if (!c.cell.state.isHidden) {
                    allHidden = false;
                    break;
                }
            }
            if (allHidden) {
                _this.plugin.managers.structure.hierarchy.toggleVisibility(_this.props.group, 'show');
            }
            _this.plugin.managers.camera.focusSpheres(_this.props.group, function (e) {
                var _a;
                if (e.cell.state.isHidden)
                    return;
                return (_a = e.cell.obj) === null || _a === void 0 ? void 0 : _a.data.boundary.sphere;
            });
        };
        _this.updateLabel = function (v) {
            _this.plugin.managers.structure.component.updateLabel(_this.pivot, v);
        };
        return _this;
    }
    Object.defineProperty(StructureComponentGroup.prototype, "pivot", {
        get: function () {
            return this.props.group[0];
        },
        enumerable: false,
        configurable: true
    });
    StructureComponentGroup.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (mol_state["State"].ObjectEvent.isCell(e, _this.pivot.cell))
                _this.forceUpdate();
        });
    };
    Object.defineProperty(StructureComponentGroup.prototype, "colorByActions", {
        get: function () {
            var _this = this;
            var _a, _b;
            var mng = this.plugin.managers.structure.component;
            var repr = this.pivot.representations[0];
            var name = (_a = repr.cell.transform.params) === null || _a === void 0 ? void 0 : _a.colorTheme.name;
            var themes = Object(structure_representation_params["getStructureThemeTypes"])(this.plugin, (_b = this.pivot.cell.obj) === null || _b === void 0 ? void 0 : _b.data);
            return action_menu["a" /* ActionMenu */].createItemsFromSelectOptions(themes, {
                value: function (o) { return function () { return mng.updateRepresentationsTheme(_this.props.group, { color: o[0] }); }; },
                selected: function (o) { return o[0] === name; }
            });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureComponentGroup.prototype, "actions", {
        get: function () {
            var _this = this;
            var mng = this.plugin.managers.structure.component;
            var ret = [
                Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('Add Representation')
                ], structure_component["StructureComponentManager"].getRepresentationTypes(this.plugin, this.props.group[0])
                    .map(function (t) { return action_menu["a" /* ActionMenu */].Item(t[1], function () { return mng.addRepresentation(_this.props.group, t[0]); }); }))
            ];
            if (this.pivot.representations.length > 0) {
                ret.push(Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('Set Coloring', { isIndependent: true })
                ], this.colorByActions));
            }
            if (mng.canBeModified(this.props.group[0])) {
                ret.push([
                    action_menu["a" /* ActionMenu */].Header('Modify by Selection'),
                    action_menu["a" /* ActionMenu */].Item('Include', function () { return mng.modifyByCurrentSelection(_this.props.group, 'union'); }, { icon: icons["UnionSvg"] }),
                    action_menu["a" /* ActionMenu */].Item('Subtract', function () { return mng.modifyByCurrentSelection(_this.props.group, 'subtract'); }, { icon: icons["SubtractSvg"] }),
                    action_menu["a" /* ActionMenu */].Item('Intersect', function () { return mng.modifyByCurrentSelection(_this.props.group, 'intersect'); }, { icon: icons["IntersectSvg"] })
                ]);
            }
            ret.push(action_menu["a" /* ActionMenu */].Item('Select This', function () { return mng.selectThis(_this.props.group); }, { icon: icons["SetSvg"] }));
            if (mng.canBeModified(this.props.group[0])) {
                ret.push(action_menu["a" /* ActionMenu */].Item('Edit Label', this.toggleLabel));
            }
            return ret;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureComponentGroup.prototype, "reprLabel", {
        get: function () {
            var _a;
            // TODO: handle generic reprs.
            var pivot = this.pivot;
            if (pivot.representations.length === 0)
                return 'No repr.';
            if (pivot.representations.length === 1)
                return (_a = pivot.representations[0].cell.obj) === null || _a === void 0 ? void 0 : _a.label;
            return pivot.representations.length + " reprs";
        },
        enumerable: false,
        configurable: true
    });
    StructureComponentGroup.prototype.render = function () {
        var _this = this;
        var _a;
        var component = this.pivot;
        var cell = component.cell;
        var label = (_a = cell.obj) === null || _a === void 0 ? void 0 : _a.label;
        var reprLabel = this.reprLabel;
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["Button"], { noOverflow: true, className: 'msp-control-button-label', title: label + ". Click to focus.", onClick: this.focus, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight, style: { textAlign: 'left' } },
                    label,
                    react["createElement"]("small", { className: 'msp-25-lower-contrast-text', style: { float: 'right' } }, reprLabel)),
                react["createElement"](common["IconButton"], { svg: cell.state.isHidden ? icons["VisibilityOffOutlinedSvg"] : icons["VisibilityOutlinedSvg"], toggleState: false, onClick: this.toggleVisible, title: (cell.state.isHidden ? 'Show' : 'Hide') + " component", small: true, className: 'msp-form-control', flex: true }),
                react["createElement"](common["IconButton"], { svg: icons["DeleteOutlinedSvg"], toggleState: false, onClick: this.remove, title: 'Remove', small: true, className: 'msp-form-control', flex: true }),
                react["createElement"](common["IconButton"], { svg: icons["MoreHorizSvg"], onClick: this.toggleAction, title: 'Actions', toggleState: this.state.action === 'action', className: 'msp-form-control', flex: true })),
            this.state.action === 'label' && react["createElement"]("div", { className: 'msp-control-offset', style: { marginBottom: '6px' } },
                react["createElement"](common["ControlRow"], { label: 'Label', control: react["createElement"]("div", { style: { display: 'flex', textAlignLast: 'center' } },
                        react["createElement"](common["TextInput"], { onChange: this.updateLabel, value: label, style: { flex: '1 1 auto', minWidth: 0 }, className: 'msp-form-control', blurOnEnter: true, blurOnEscape: true }),
                        react["createElement"](common["IconButton"], { svg: icons["CheckSvg"], onClick: this.toggleLabel, className: 'msp-form-control msp-control-button-label', flex: true })) })),
            this.state.action === 'action' && react["createElement"]("div", { className: 'msp-accent-offset' },
                react["createElement"]("div", { style: { marginBottom: '6px' } },
                    react["createElement"](action_menu["a" /* ActionMenu */], { items: this.actions, onSelect: this.selectAction, noOffset: true })),
                react["createElement"]("div", { style: { marginBottom: '6px' } }, component.representations.map(function (r) { return react["createElement"](components_StructureRepresentationEntry, { group: _this.props.group, key: r.cell.transform.ref, representation: r }); }))));
    };
    return StructureComponentGroup;
}(base["PurePluginUIComponent"]));
var components_StructureRepresentationEntry = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureRepresentationEntry, _super);
    function StructureRepresentationEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.remove = function () { return _this.plugin.managers.structure.component.removeRepresentations(_this.props.group, _this.props.representation); };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            _this.plugin.managers.structure.component.toggleVisibility(_this.props.group, _this.props.representation);
        };
        _this.update = function (params) { return _this.plugin.managers.structure.component.updateRepresentations(_this.props.group, _this.props.representation, params); };
        return _this;
    }
    StructureRepresentationEntry.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (mol_state["State"].ObjectEvent.isCell(e, _this.props.representation.cell))
                _this.forceUpdate();
        });
    };
    StructureRepresentationEntry.prototype.render = function () {
        var _a;
        var repr = this.props.representation.cell;
        return react["createElement"]("div", { className: 'msp-representation-entry' },
            repr.parent && react["createElement"](common["ExpandGroup"], { header: (((_a = repr.obj) === null || _a === void 0 ? void 0 : _a.label) || '') + " Representation", noOffset: true },
                react["createElement"](update_transform["UpdateTransformControl"], { state: repr.parent, transform: repr.transform, customHeader: 'none', customUpdate: this.update, noMargin: true })),
            react["createElement"](common["IconButton"], { svg: icons["DeleteOutlinedSvg"], onClick: this.remove, title: 'Remove', small: true, className: 'msp-default-bg', toggleState: false, style: {
                    position: 'absolute', top: 0, right: '32px', lineHeight: '24px', height: '24px', textAlign: 'right', width: '44px', paddingRight: '6px', background: 'none'
                } }),
            react["createElement"](common["IconButton"], { svg: this.props.representation.cell.state.isHidden ? icons["VisibilityOffOutlinedSvg"] : icons["VisibilityOutlinedSvg"], toggleState: false, onClick: this.toggleVisible, title: 'Toggle Visibility', small: true, className: 'msp-default-bg', style: {
                    position: 'absolute', top: 0, right: 0, lineHeight: '24px', height: '24px', textAlign: 'right', width: '32px', paddingRight: '6px', background: 'none'
                } }));
    };
    return StructureRepresentationEntry;
}(base["PurePluginUIComponent"]));
//# sourceMappingURL=components.js.map

/***/ }),
/* 323 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "ViewportControls", function() { return /* binding */ viewport_ViewportControls; });
__webpack_require__.d(__webpack_exports__, "Logo", function() { return /* binding */ Logo; });
__webpack_require__.d(__webpack_exports__, "Viewport", function() { return /* binding */ viewport_Viewport; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/debounceTime.js
var debounceTime = __webpack_require__(388);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/util.js
var util = __webpack_require__(332);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/config.js
var config = __webpack_require__(101);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/selection.js
var selection = __webpack_require__(206);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/snapshots.js
var snapshots = __webpack_require__(285);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport/screenshot.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */










var screenshot_DownloadScreenshotControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(DownloadScreenshotControls, _super);
    function DownloadScreenshotControls() {
        var _a, _b, _c;
        var _this = _super.apply(this, arguments) || this;
        _this.state = {
            showPreview: true,
            isDisabled: false,
            resolution: (_a = _this.plugin.helpers.viewportScreenshot) === null || _a === void 0 ? void 0 : _a.currentResolution,
            transparent: (_b = _this.plugin.helpers.viewportScreenshot) === null || _b === void 0 ? void 0 : _b.transparent,
            axes: (_c = _this.plugin.helpers.viewportScreenshot) === null || _c === void 0 ? void 0 : _c.axes
        };
        _this.imgRef = react["createRef"]();
        _this.updateQueue = new Subject["a" /* Subject */]();
        _this.preview = function () { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _a;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!this.imgRef.current)
                            return [2 /*return*/];
                        _a = this.imgRef.current;
                        return [4 /*yield*/, this.plugin.helpers.viewportScreenshot.imageData()];
                    case 1:
                        _a.src = _b.sent();
                        return [2 /*return*/];
                }
            });
        }); };
        _this.download = function () {
            var _a;
            (_a = _this.plugin.helpers.viewportScreenshot) === null || _a === void 0 ? void 0 : _a.download();
            _this.props.close();
        };
        _this.openTab = function () {
            // modified from https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript/16245768#16245768
            var base64 = _this.imgRef.current.src;
            var byteCharacters = atob(base64.substr("data:image/png;base64,".length));
            var byteArrays = [];
            var sliceSize = Math.min(byteCharacters.length, 1024 * 1024);
            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var byteNumbers = new Uint8Array(Math.min(sliceSize, byteCharacters.length - offset));
                for (var i = 0, _i = byteNumbers.length; i < _i; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(offset + i);
                }
                byteArrays.push(byteNumbers);
            }
            var blob = new Blob(byteArrays, { type: 'image/png' });
            var blobUrl = URL.createObjectURL(blob);
            window.open(blobUrl, '_blank');
            _this.props.close();
        };
        _this.setProps = function (p) {
            if (p.name === 'resolution') {
                _this.plugin.helpers.viewportScreenshot.currentResolution = p.value;
                _this.setState({ resolution: p.value });
            }
            else if (p.name === 'transparent') {
                _this.plugin.helpers.viewportScreenshot.transparent = p.value;
                _this.setState({ transparent: p.value });
            }
            else if (p.name === 'axes') {
                _this.plugin.helpers.viewportScreenshot.axes = p.value;
                _this.setState({ axes: p.value });
            }
        };
        _this.downloadToFileJson = function () {
            commands["PluginCommands"].State.Snapshots.DownloadToFile(_this.plugin, { type: 'json' });
        };
        _this.downloadToFileZip = function () {
            commands["PluginCommands"].State.Snapshots.DownloadToFile(_this.plugin, { type: 'zip' });
        };
        _this.open = function (e) {
            if (!e.target.files || !e.target.files[0])
                return;
            commands["PluginCommands"].State.Snapshots.OpenFile(_this.plugin, { file: e.target.files[0] });
        };
        return _this;
    }
    DownloadScreenshotControls.prototype.handlePreview = function () {
        if (this.state.showPreview) {
            this.preview();
        }
    };
    DownloadScreenshotControls.prototype.componentDidUpdate = function () {
        this.updateQueue.next();
    };
    DownloadScreenshotControls.prototype.componentDidMount = function () {
        var _this = this;
        if (!this.plugin.canvas3d)
            return;
        this.subscribe(Object(debounceTime["a" /* debounceTime */])(250)(this.updateQueue), function () { return _this.handlePreview(); });
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () {
            var _a;
            _this.plugin.helpers.viewportScreenshot.imagePass.setProps({
                multiSample: { mode: 'on', sampleLevel: 2 },
                postprocessing: (_a = _this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.props.postprocessing
            });
            _this.updateQueue.next();
        });
        this.subscribe(Object(debounceTime["a" /* debounceTime */])(250)(this.plugin.canvas3d.didDraw), function () {
            if (_this.state.isDisabled)
                return;
            _this.updateQueue.next();
        });
        this.subscribe(this.plugin.state.data.behaviors.isUpdating, function (v) {
            _this.setState({ isDisabled: v });
            if (!v)
                _this.updateQueue.next();
        });
        this.handlePreview();
    };
    DownloadScreenshotControls.prototype.render = function () {
        return react["createElement"]("div", null,
            react["createElement"]("div", { className: 'msp-image-preview' },
                react["createElement"]("img", { ref: this.imgRef }),
                react["createElement"]("br", null),
                react["createElement"]("span", null, "Right-click the image to Copy.")),
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["Button"], { icon: icons["GetAppSvg"], onClick: this.download, disabled: this.state.isDisabled }, "Download"),
                react["createElement"](common["Button"], { icon: icons["LaunchSvg"], onClick: this.openTab, disabled: this.state.isDisabled }, "Open in new Tab")),
            react["createElement"](parameters["ParameterControls"], { params: this.plugin.helpers.viewportScreenshot.params, values: this.plugin.helpers.viewportScreenshot.values, onChange: this.setProps, isDisabled: this.state.isDisabled }),
            react["createElement"](common["ExpandGroup"], { header: 'State' },
                react["createElement"](snapshots["StateExportImportControls"], { onAction: this.props.close }),
                react["createElement"](common["ExpandGroup"], { header: 'Save Options', initiallyExpanded: false, noOffset: true },
                    react["createElement"](snapshots["LocalStateSnapshotParams"], null))));
    };
    return DownloadScreenshotControls;
}(base["PluginUIComponent"]));

//# sourceMappingURL=screenshot.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport/simple-settings.js + 1 modules
var simple_settings = __webpack_require__(392);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */













var viewport_ViewportControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ViewportControls, _super);
    function ViewportControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.allCollapsedState = {
            isSettingsExpanded: false,
            isScreenshotExpanded: false
        };
        _this.state = Object(tslib_es6["__assign"])({}, _this.allCollapsedState);
        _this.resetCamera = function () {
            commands["PluginCommands"].Camera.Reset(_this.plugin, {});
        };
        _this.toggleSettingsExpanded = _this.toggle('isSettingsExpanded');
        _this.toggleScreenshotExpanded = _this.toggle('isScreenshotExpanded');
        _this.toggleControls = function () {
            commands["PluginCommands"].Layout.Update(_this.plugin, { state: { showControls: !_this.plugin.layout.state.showControls } });
        };
        _this.toggleExpanded = function () {
            commands["PluginCommands"].Layout.Update(_this.plugin, { state: { isExpanded: !_this.plugin.layout.state.isExpanded } });
        };
        _this.setSettings = function (p) {
            var _a;
            commands["PluginCommands"].Canvas3D.SetSettings(_this.plugin, { settings: (_a = {}, _a[p.name] = p.value, _a) });
        };
        _this.setLayout = function (p) {
            var _a;
            commands["PluginCommands"].Layout.Update(_this.plugin, { state: (_a = {}, _a[p.name] = p.value, _a) });
        };
        _this.screenshot = function () {
            var _a;
            (_a = _this.plugin.helpers.viewportScreenshot) === null || _a === void 0 ? void 0 : _a.download();
        };
        _this.onMouseMove = function (e) {
            // ignore mouse moves when no button is held
            if (e.buttons === 0)
                e.stopPropagation();
        };
        return _this;
    }
    ViewportControls.prototype.toggle = function (panel) {
        var _this = this;
        return function (e) {
            var _a;
            _this.setState(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.allCollapsedState), (_a = {}, _a[panel] = !_this.state[panel], _a)));
            e === null || e === void 0 ? void 0 : e.currentTarget.blur();
        };
    };
    ViewportControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.layout.events.updated, function () { return _this.forceUpdate(); });
    };
    ViewportControls.prototype.icon = function (icon, onClick, title, isOn) {
        if (isOn === void 0) { isOn = true; }
        return react["createElement"](common["IconButton"], { svg: icon, toggleState: isOn, onClick: onClick, title: title, style: { background: 'transparent' } });
    };
    ViewportControls.prototype.render = function () {
        return react["createElement"]("div", { className: 'msp-viewport-controls', onMouseMove: this.onMouseMove },
            react["createElement"]("div", { className: 'msp-viewport-controls-buttons' },
                react["createElement"]("div", null,
                    react["createElement"]("div", { className: 'msp-semi-transparent-background' }),
                    this.icon(icons["AutorenewSvg"], this.resetCamera, 'Reset Camera')),
                react["createElement"]("div", null,
                    react["createElement"]("div", { className: 'msp-semi-transparent-background' }),
                    this.icon(icons["CameraOutlinedSvg"], this.toggleScreenshotExpanded, 'Screenshot / State Snapshot', this.state.isScreenshotExpanded)),
                react["createElement"]("div", null,
                    react["createElement"]("div", { className: 'msp-semi-transparent-background' }),
                    this.icon(icons["BuildOutlinedSvg"], this.toggleControls, 'Toggle Controls Panel', this.plugin.layout.state.showControls),
                    this.plugin.config.get(config["PluginConfig"].Viewport.ShowExpand) && this.icon(icons["FullscreenSvg"], this.toggleExpanded, 'Toggle Expanded Viewport', this.plugin.layout.state.isExpanded),
                    this.icon(icons["TuneSvg"], this.toggleSettingsExpanded, 'Settings / Controls Info', this.state.isSettingsExpanded)),
                this.plugin.config.get(config["PluginConfig"].Viewport.ShowSelectionMode) && react["createElement"]("div", null,
                    react["createElement"]("div", { className: 'msp-semi-transparent-background' }),
                    react["createElement"](selection["ToggleSelectionModeButton"], null))),
            this.state.isScreenshotExpanded && react["createElement"]("div", { className: 'msp-viewport-controls-panel' },
                react["createElement"](common["ControlGroup"], { header: 'Screenshot / State', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleScreenshotExpanded, topRightIcon: icons["CloseSvg"], noTopMargin: true, childrenClassName: 'msp-viewport-controls-panel-controls' },
                    react["createElement"](screenshot_DownloadScreenshotControls, { close: this.toggleScreenshotExpanded }))),
            this.state.isSettingsExpanded && react["createElement"]("div", { className: 'msp-viewport-controls-panel' },
                react["createElement"](common["ControlGroup"], { header: 'Settings / Controls Info', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleSettingsExpanded, topRightIcon: icons["CloseSvg"], noTopMargin: true, childrenClassName: 'msp-viewport-controls-panel-controls' },
                    react["createElement"](simple_settings["SimpleSettingsControl"], null))));
    };
    return ViewportControls;
}(base["PluginUIComponent"]));

var Logo = function () {
    return react["createElement"]("a", { className: 'msp-logo', href: 'https://molstar.org', target: '_blank' });
};
var viewport_Viewport = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Viewport, _super);
    function Viewport() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.container = react["createRef"]();
        _this.canvas = react["createRef"]();
        _this.state = {
            noWebGl: false,
            showLogo: true
        };
        _this.handleLogo = function () {
            var _a;
            _this.setState({ showLogo: !((_a = _this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.reprCount.value) });
        };
        _this.handleResize = function () {
            var container = _this.container.current;
            var canvas = _this.canvas.current;
            if (container && canvas) {
                Object(util["b" /* resizeCanvas */])(canvas, container);
                _this.plugin.canvas3d.handleResize();
            }
        };
        return _this;
    }
    Viewport.prototype.componentDidMount = function () {
        var _this = this;
        if (!this.canvas.current || !this.container.current || !this.plugin.initViewer(this.canvas.current, this.container.current)) {
            this.setState({ noWebGl: true });
            return;
        }
        this.handleLogo();
        this.handleResize();
        var canvas3d = this.plugin.canvas3d;
        this.subscribe(canvas3d.reprCount, this.handleLogo);
        var resized = new Subject["a" /* Subject */]();
        var resize = function () { return resized.next(); };
        this.subscribe(resized.pipe(Object(debounceTime["a" /* debounceTime */])(1000 / 24)), function () { return _this.handleResize(); });
        this.subscribe(canvas3d.input.resize, resize);
        this.subscribe(canvas3d.interaction.click, function (e) { return _this.plugin.behaviors.interaction.click.next(e); });
        this.subscribe(canvas3d.interaction.hover, function (e) { return _this.plugin.behaviors.interaction.hover.next(e); });
        this.subscribe(this.plugin.layout.events.updated, resize);
    };
    Viewport.prototype.componentWillUnmount = function () {
        _super.prototype.componentWillUnmount.call(this);
        // TODO viewer cleanup
    };
    Viewport.prototype.renderMissing = function () {
        return react["createElement"]("div", { className: 'msp-no-webgl' },
            react["createElement"]("div", null,
                react["createElement"]("p", null,
                    react["createElement"]("b", null, "WebGL does not seem to be available.")),
                react["createElement"]("p", null, "This can be caused by an outdated browser, graphics card driver issue, or bad weather. Sometimes, just restarting the browser helps."),
                react["createElement"]("p", null,
                    "For a list of supported browsers, refer to ",
                    react["createElement"]("a", { href: 'http://caniuse.com/#feat=webgl', target: '_blank' }, "http://caniuse.com/#feat=webgl"),
                    ".")));
    };
    Viewport.prototype.render = function () {
        if (this.state.noWebGl)
            return this.renderMissing();
        return react["createElement"]("div", { className: 'msp-viewport' },
            react["createElement"]("div", { className: 'msp-viewport-host3d', ref: this.container },
                react["createElement"]("canvas", { ref: this.canvas })),
            this.state.showLogo && react["createElement"](Logo, null));
    };
    return Viewport;
}(base["PluginUIComponent"]));

//# sourceMappingURL=viewport.js.map

/***/ }),
/* 324 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IsNativeEndianLittle; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return flipByteOrder; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return uint8ToString; });
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
var IsNativeEndianLittle = new Uint16Array(new Uint8Array([0x12, 0x34]).buffer)[0] === 0x3412;
function flipByteOrder(data, bytes) {
    var buffer = new ArrayBuffer(data.length);
    var ret = new Uint8Array(buffer);
    for (var i = 0, n = data.length; i < n; i += bytes) {
        for (var j = 0; j < bytes; j++) {
            ret[i + bytes - j - 1] = data[i + j];
        }
    }
    return buffer;
}
var ChunkSize = 0x7000;
function uint8ToString(array) {
    if (array.length > ChunkSize) {
        var c = [];
        for (var i = 0; i < array.length; i += ChunkSize) {
            c.push(String.fromCharCode.apply(null, array.subarray(i, i + ChunkSize)));
        }
        return c.join('');
    }
    else {
        return String.fromCharCode.apply(null, array);
    }
}
//# sourceMappingURL=binary.js.map

/***/ }),
/* 325 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ComponentBond; });
/* harmony import */ var _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(57);
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(62);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/* harmony import */ var _common_property__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(188);
/**
 * Copyright (c) 2017-2020 Mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var ComponentBond;
(function (ComponentBond) {
    ComponentBond.Descriptor = {
        name: 'chem_comp_bond',
        cifExport: {
            prefix: '',
            categories: [{
                    name: 'chem_comp_bond',
                    instance: function (ctx) {
                        var p = ComponentBond.Provider.get(ctx.firstModel);
                        if (!p)
                            return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.Empty;
                        var chem_comp_bond = p.data;
                        if (!chem_comp_bond)
                            return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.Empty;
                        var comp_names = ctx.structures[0].uniqueResidueNames;
                        var comp_id = chem_comp_bond.comp_id, _rowCount = chem_comp_bond._rowCount;
                        var indices = [];
                        for (var i = 0; i < _rowCount; i++) {
                            if (comp_names.has(comp_id.value(i)))
                                indices[indices.length] = i;
                        }
                        return _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_1__[/* CifWriter */ "a"].Category.ofTable(chem_comp_bond, indices);
                    }
                }]
        }
    };
    ComponentBond.Provider = _common_property__WEBPACK_IMPORTED_MODULE_3__[/* FormatPropertyProvider */ "a"].create(ComponentBond.Descriptor);
    function chemCompBondFromTable(model, table) {
        return _mol_data_db__WEBPACK_IMPORTED_MODULE_2__["Table"].pick(table, _mol_io_reader_cif_schema_mmcif__WEBPACK_IMPORTED_MODULE_0__[/* mmCIF_Schema */ "a"].chem_comp_bond, function (i) {
            return model.properties.chemicalComponentMap.has(table.comp_id.value(i));
        });
    }
    ComponentBond.chemCompBondFromTable = chemCompBondFromTable;
    function getEntriesFromChemCompBond(data) {
        var entries = new Map();
        function addEntry(id) {
            var e = new Entry(id);
            entries.set(id, e);
            return e;
        }
        var comp_id = data.comp_id, atom_id_1 = data.atom_id_1, atom_id_2 = data.atom_id_2, value_order = data.value_order, pdbx_aromatic_flag = data.pdbx_aromatic_flag, _rowCount = data._rowCount;
        var entry = addEntry(comp_id.value(0));
        for (var i = 0; i < _rowCount; i++) {
            var id = comp_id.value(i);
            var nameA = atom_id_1.value(i);
            var nameB = atom_id_2.value(i);
            var order = value_order.value(i);
            var aromatic = pdbx_aromatic_flag.value(i) === 'Y';
            if (entry.id !== id) {
                entry = addEntry(id);
            }
            var flags = 1 /* Covalent */;
            var ord = 1;
            if (aromatic)
                flags |= 16 /* Aromatic */;
            switch (order.toLowerCase()) {
                case 'doub':
                case 'delo':
                    ord = 2;
                    break;
                case 'trip':
                    ord = 3;
                    break;
                case 'quad':
                    ord = 4;
                    break;
            }
            entry.add(nameA, nameB, ord, flags);
        }
        return entries;
    }
    ComponentBond.getEntriesFromChemCompBond = getEntriesFromChemCompBond;
    var Entry = /** @class */ (function () {
        function Entry(id) {
            this.id = id;
            this.map = new Map();
        }
        Entry.prototype.add = function (a, b, order, flags, swap) {
            if (swap === void 0) { swap = true; }
            var e = this.map.get(a);
            if (e !== void 0) {
                var f = e.get(b);
                if (f === void 0) {
                    e.set(b, { order: order, flags: flags });
                }
            }
            else {
                var map = new Map();
                map.set(b, { order: order, flags: flags });
                this.map.set(a, map);
            }
            if (swap)
                this.add(b, a, order, flags, false);
        };
        return Entry;
    }());
    ComponentBond.Entry = Entry;
})(ComponentBond || (ComponentBond = {}));
//# sourceMappingURL=comp.js.map

/***/ }),
/* 326 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return atom_site_operator_mapping; });
/* unused harmony export AtomSiteOperatorMappingCategoryName */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return AtomSiteOperatorMappingSchema; });
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(62);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(7);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




function atom_site_operator_mapping(ctx) {
    var entries = getEntries(ctx);
    if (entries.length === 0)
        return;
    return [Category, entries, { ignoreFilter: true }];
}
var AtomSiteOperatorMappingCategoryName = 'molstar_atom_site_operator_mapping';
var AtomSiteOperatorMappingSchema = {
    molstar_atom_site_operator_mapping: {
        label_asym_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
        auth_asym_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
        operator_name: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
        suffix: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
        // assembly
        assembly_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
        assembly_operator_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Int(),
        // symmetry
        symmetry_operator_index: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Int(),
        symmetry_hkl: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Vector(3),
        // NCS
        ncs_id: _mol_data_db__WEBPACK_IMPORTED_MODULE_3__["Column"].Schema.Str(),
    }
};
var asmValueKind = function (i, xs) { return typeof xs[i].operator.assembly === 'undefined' ? 1 /* NotPresent */ : 0 /* Present */; };
var symmetryValueKind = function (i, xs) { return xs[i].operator.spgrOp === -1 ? 1 /* NotPresent */ : 0 /* Present */; };
var Fields = _mol_io_writer_cif__WEBPACK_IMPORTED_MODULE_2__[/* CifWriter */ "a"].fields()
    .str('label_asym_id', function (i, xs) { return xs[i].label_asym_id; })
    .str('auth_asym_id', function (i, xs) { return xs[i].auth_asym_id; })
    .str('operator_name', function (i, xs) { return xs[i].operator.name; })
    .str('suffix', function (i, xs) { return xs[i].operator.suffix; })
    // assembly
    // TODO: include oper list as well?
    .str('assembly_id', function (i, xs) { var _a; return ((_a = xs[i].operator.assembly) === null || _a === void 0 ? void 0 : _a.id) || ''; }, { valueKind: asmValueKind })
    .int('assembly_operator_id', function (i, xs) { var _a; return ((_a = xs[i].operator.assembly) === null || _a === void 0 ? void 0 : _a.operId) || 0; }, { valueKind: asmValueKind })
    // symmetry
    .int('symmetry_operator_index', function (i, xs) { return xs[i].operator.spgrOp; }, { valueKind: symmetryValueKind })
    .vec('symmetry_hkl', [function (i, xs) { return xs[i].operator.hkl[0]; }, function (i, xs) { return xs[i].operator.hkl[1]; }, function (i, xs) { return xs[i].operator.hkl[2]; }], { valueKind: symmetryValueKind })
    // NCS
    .str('ncs_id', function (i, xs) { return xs[i].operator.ncsId || ''; }, { valueKind: function (i, xs) { return !xs[i].operator.ncsId ? 1 /* NotPresent */ : 0 /* Present */; } })
    .getFields();
var Category = {
    name: 'molstar_atom_site_operator_mapping',
    instance: function (entries) {
        return { fields: Fields, source: [{ data: entries, rowCount: entries.length }] };
    }
};
function getEntries(ctx) {
    var existing = new Set();
    var entries = [];
    for (var _i = 0, _a = ctx.structures; _i < _a.length; _i++) {
        var s = _a[_i];
        var l = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureElement */ "d"].Location.create(s);
        for (var _b = 0, _c = s.units; _b < _c.length; _b++) {
            var unit = _c[_b];
            var operator = unit.conformation.operator;
            if (!operator.suffix || unit.kind !== 0 /* Atomic */)
                continue;
            l.unit = unit;
            var elements = unit.elements;
            var chainsIt = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["Segmentation"].transientSegments(unit.model.atomicHierarchy.chainAtomSegments, elements);
            while (chainsIt.hasNext) {
                var chainSegment = chainsIt.move();
                l.element = elements[chainSegment.start];
                var label_asym_id = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureProperties */ "e"].chain.label_asym_id(l);
                var key = "" + label_asym_id + operator.suffix;
                if (existing.has(key))
                    continue;
                existing.add(key);
                var auth_asym_id = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureProperties */ "e"].chain.label_asym_id(l);
                entries.push({ label_asym_id: label_asym_id, auth_asym_id: auth_asym_id, operator: operator });
            }
        }
    }
    return entries;
}
//# sourceMappingURL=atom_site_operator_mapping.js.map

/***/ }),
/* 327 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ChainIdColorThemeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return getChainIdColorThemeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ChainIdColorTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ChainIdColorThemeProvider; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(2);
/* harmony import */ var _mol_util_color_palette__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(111);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var DefaultList = 'many-distinct';
var DefaultColor = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"])(0xFAFAFA);
var Description = 'Gives every chain a color based on its `asym_id` value.';
var ChainIdColorThemeParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ asymId: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].Select('auth', _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].arrayToOptions(['auth', 'label'])) }, Object(_mol_util_color_palette__WEBPACK_IMPORTED_MODULE_4__[/* getPaletteParams */ "b"])({ type: 'colors', colorList: DefaultList }));
function getChainIdColorThemeParams(ctx) {
    var params = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].clone(ChainIdColorThemeParams);
    return params;
}
function getAsymId(unit, type) {
    switch (unit.kind) {
        case 0 /* Atomic */:
            return type === 'auth'
                ? _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].chain.auth_asym_id
                : _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].chain.label_asym_id;
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            return _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureProperties"].coarse.asym_id;
    }
}
function getAsymIdKey(location, type) {
    var asymId = getAsymId(location.unit, type)(location);
    return location.structure.models.length > 1
        ? getKey(location.unit.model, asymId)
        : asymId;
}
function getKey(model, asymId) {
    return asymId + " | " + ((_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Model"].Index.get(model).value || 0) + 1);
}
function getAsymIdSerialMap(structure, type) {
    var map = new Map();
    var _loop_1 = function (m) {
        var asymIdOffset = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Model"].AsymIdOffset.get(m).value;
        var offset = (type === 'auth' ? asymIdOffset === null || asymIdOffset === void 0 ? void 0 : asymIdOffset.auth : asymIdOffset === null || asymIdOffset === void 0 ? void 0 : asymIdOffset.label) || 0;
        m.properties.structAsymMap.forEach(function (_a, label_id) {
            var auth_id = _a.auth_id;
            var asymId = type === 'auth' ? auth_id : label_id;
            var k = structure.models.length > 1
                ? getKey(m, asymId)
                : asymId;
            if (!map.has(k))
                map.set(k, map.size + offset);
        });
    };
    for (var _i = 0, _a = structure.models; _i < _a.length; _i++) {
        var m = _a[_i];
        _loop_1(m);
    }
    return map;
}
function ChainIdColorTheme(ctx, props) {
    var color;
    var legend;
    if (ctx.structure) {
        var l_1 = _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.create(ctx.structure);
        var asymIdSerialMap_1 = getAsymIdSerialMap(ctx.structure.root, props.asymId);
        var labelTable_1 = Array.from(asymIdSerialMap_1.keys());
        props.palette.params.valueLabel = function (i) { return labelTable_1[i]; };
        var palette_1 = Object(_mol_util_color_palette__WEBPACK_IMPORTED_MODULE_4__[/* getPalette */ "a"])(asymIdSerialMap_1.size, props);
        legend = palette_1.legend;
        color = function (location) {
            var serial = undefined;
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.is(location)) {
                var k = getAsymIdKey(location, props.asymId);
                serial = asymIdSerialMap_1.get(k);
            }
            else if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["Bond"].isLocation(location)) {
                l_1.unit = location.aUnit;
                l_1.element = location.aUnit.elements[location.aIndex];
                var k = getAsymIdKey(l_1, props.asymId);
                serial = asymIdSerialMap_1.get(k);
            }
            return serial === undefined ? DefaultColor : palette_1.color(serial);
        };
    }
    else {
        color = function () { return DefaultColor; };
    }
    return {
        factory: ChainIdColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: Description,
        legend: legend
    };
}
var ChainIdColorThemeProvider = {
    name: 'chain-id',
    label: 'Chain Id',
    category: "Chain Property" /* Chain */,
    factory: ChainIdColorTheme,
    getParams: getChainIdColorThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_3__["ParamDefinition"].getDefaultValues(ChainIdColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; }
};
//# sourceMappingURL=chain-id.js.map

/***/ }),
/* 328 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Slider; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return Slider2; });
/* unused harmony export Handle */
/* unused harmony export SliderBase */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _common__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(19);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var Slider = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Slider, _super);
    function Slider() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isChanging: false, current: 0 };
        _this.begin = function () {
            _this.setState({ isChanging: true });
        };
        _this.end = function (v) {
            _this.setState({ isChanging: false });
            _this.props.onChange(v);
        };
        _this.updateCurrent = function (current) {
            _this.setState({ current: current });
        };
        _this.updateManually = function (v) {
            _this.setState({ isChanging: true });
            var n = v;
            if (_this.props.step === 1)
                n = Math.round(n);
            if (n < _this.props.min)
                n = _this.props.min;
            if (n > _this.props.max)
                n = _this.props.max;
            _this.setState({ current: n, isChanging: true });
        };
        _this.onManualBlur = function () {
            _this.setState({ isChanging: false });
            _this.props.onChange(_this.state.current);
        };
        return _this;
    }
    Slider.getDerivedStateFromProps = function (props, state) {
        if (state.isChanging || props.value === state.current)
            return null;
        return { current: props.value };
    };
    Slider.prototype.render = function () {
        var step = this.props.step;
        if (step === void 0)
            step = 1;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-slider' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](SliderBase, { min: this.props.min, max: this.props.max, step: step, value: this.state.current, disabled: this.props.disabled, onBeforeChange: this.begin, onChange: this.updateCurrent, onAfterChange: this.end })),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["TextInput"], { numeric: true, delayMs: 50, value: this.state.current, blurOnEnter: true, onBlur: this.onManualBlur, isDisabled: this.props.disabled, onChange: this.updateManually })));
    };
    return Slider;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

var Slider2 = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Slider2, _super);
    function Slider2() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isChanging: false, current: [0, 1] };
        _this.begin = function () {
            _this.setState({ isChanging: true });
        };
        _this.end = function (v) {
            _this.setState({ isChanging: false });
            _this.props.onChange(v);
        };
        _this.updateCurrent = function (current) {
            _this.setState({ current: current });
        };
        _this.updateMax = function (v) {
            var n = v;
            if (_this.props.step === 1)
                n = Math.round(n);
            if (n < _this.state.current[0])
                n = _this.state.current[0];
            else if (n < _this.props.min)
                n = _this.props.min;
            if (n > _this.props.max)
                n = _this.props.max;
            _this.props.onChange([_this.state.current[0], n]);
        };
        _this.updateMin = function (v) {
            var n = v;
            if (_this.props.step === 1)
                n = Math.round(n);
            if (n < _this.props.min)
                n = _this.props.min;
            if (n > _this.state.current[1])
                n = _this.state.current[1];
            else if (n > _this.props.max)
                n = _this.props.max;
            _this.props.onChange([n, _this.state.current[1]]);
        };
        return _this;
    }
    Slider2.getDerivedStateFromProps = function (props, state) {
        if (state.isChanging || (props.value[0] === state.current[0]) && (props.value[1] === state.current[1]))
            return null;
        return { current: props.value };
    };
    Slider2.prototype.render = function () {
        var step = this.props.step;
        if (step === void 0)
            step = 1;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-slider2' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["TextInput"], { numeric: true, delayMs: 50, value: this.state.current[0], onEnter: this.props.onEnter, blurOnEnter: true, isDisabled: this.props.disabled, onChange: this.updateMin })),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](SliderBase, { min: this.props.min, max: this.props.max, step: step, value: this.state.current, disabled: this.props.disabled, onBeforeChange: this.begin, onChange: this.updateCurrent, onAfterChange: this.end, range: true, pushable: true })),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_common__WEBPACK_IMPORTED_MODULE_2__["TextInput"], { numeric: true, delayMs: 50, value: this.state.current[1], onEnter: this.props.onEnter, blurOnEnter: true, isDisabled: this.props.disabled, onChange: this.updateMax })));
    };
    return Slider2;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

/**
 * The following code was adapted from react-components/slider library.
 *
 * The MIT License (MIT)
 * Copyright (c) 2015-present Alipay.com, https://www.alipay.com/
 *
 * 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 classNames(_classes) {
    var classes = [];
    var hasOwn = {}.hasOwnProperty;
    for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        if (!arg)
            continue;
        var argType = typeof arg;
        if (argType === 'string' || argType === 'number') {
            classes.push(arg);
        }
        else if (Array.isArray(arg)) {
            classes.push(classNames.apply(null, arg));
        }
        else if (argType === 'object') {
            for (var key in arg) {
                if (hasOwn.call(arg, key) && arg[key]) {
                    classes.push(key);
                }
            }
        }
    }
    return classes.join(' ');
}
function isNotTouchEvent(e) {
    return e.touches.length > 1 || (e.type.toLowerCase() === 'touchend' && e.touches.length > 0);
}
function getTouchPosition(vertical, e) {
    return vertical ? e.touches[0].clientY : e.touches[0].pageX;
}
function getMousePosition(vertical, e) {
    return vertical ? e.clientY : e.pageX;
}
function getHandleCenterPosition(vertical, handle) {
    var coords = handle.getBoundingClientRect();
    return vertical ?
        coords.top + (coords.height * 0.5) :
        coords.left + (coords.width * 0.5);
}
function pauseEvent(e) {
    e.stopPropagation();
    e.preventDefault();
}
var Handle = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Handle, _super);
    function Handle() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Handle.prototype.render = function () {
        var _a = this.props, className = _a.className, tipFormatter = _a.tipFormatter, vertical = _a.vertical, offset = _a.offset, value = _a.value, index = _a.index;
        var style = vertical ? { bottom: offset + "%" } : { left: offset + "%" };
        return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: className, style: style, title: tipFormatter(value, index) }));
    };
    return Handle;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

var SliderBase = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SliderBase, _super);
    function SliderBase(props) {
        var _this = _super.call(this, props) || this;
        _this.sliderElement = react__WEBPACK_IMPORTED_MODULE_1__["createRef"]();
        _this.handleElements = [];
        _this.dragOffset = 0;
        _this.startPosition = 0;
        _this.startValue = 0;
        _this._getPointsCache = void 0;
        _this.onMouseDown = function (e) {
            if (e.button !== 0) {
                return;
            }
            var position = getMousePosition(_this.props.vertical, e);
            if (!_this.isEventFromHandle(e)) {
                _this.dragOffset = 0;
            }
            else {
                var handlePosition = getHandleCenterPosition(_this.props.vertical, e.target);
                _this.dragOffset = position - handlePosition;
                position = handlePosition;
            }
            _this.onStart(position);
            _this.addDocumentEvents('mouse');
            pauseEvent(e);
        };
        _this.onTouchMove = function (e) {
            if (isNotTouchEvent(e)) {
                _this.end('touch');
                return;
            }
            var position = getTouchPosition(_this.props.vertical, e);
            _this.onMove(e, position - _this.dragOffset);
        };
        _this.onTouchStart = function (e) {
            if (isNotTouchEvent(e))
                return;
            var position = getTouchPosition(_this.props.vertical, e);
            if (!_this.isEventFromHandle(e)) {
                _this.dragOffset = 0;
            }
            else {
                var handlePosition = getHandleCenterPosition(_this.props.vertical, e.target);
                _this.dragOffset = position - handlePosition;
                position = handlePosition;
            }
            _this.onStart(position);
            _this.addDocumentEvents('touch');
            pauseEvent(e);
        };
        _this.eventHandlers = {
            'touchmove': function (e) { return _this.onTouchMove(e); },
            'touchend': function (e) { return _this.end('touch'); },
            'mousemove': function (e) { return _this.onMouseMove(e); },
            'mouseup': function (e) { return _this.end('mouse'); },
        };
        _this.calcOffset = function (value) {
            var _a = _this.props, min = _a.min, max = _a.max;
            var ratio = (value - min) / (max - min);
            return ratio * 100;
        };
        var range = props.range, min = props.min, max = props.max;
        var initialValue = range ? Array.apply(null, Array(+range + 1)).map(function () { return min; }) : min;
        var defaultValue = ('defaultValue' in props ? props.defaultValue : initialValue);
        var value = (props.value !== undefined ? props.value : defaultValue);
        var bounds = (range ? value : [min, value]).map(function (v) { return _this.trimAlignValue(v); });
        var recent;
        if (range && bounds[0] === bounds[bounds.length - 1] && bounds[0] === max) {
            recent = 0;
        }
        else {
            recent = bounds.length - 1;
        }
        _this.state = {
            handle: null,
            recent: recent,
            bounds: bounds,
        };
        return _this;
    }
    SliderBase.prototype.componentDidUpdate = function (prevProps) {
        var _this = this;
        if (!('value' in this.props || 'min' in this.props || 'max' in this.props))
            return;
        var bounds = this.state.bounds;
        if (prevProps.range) {
            var value = this.props.value || bounds;
            var nextBounds = value.map(function (v) { return _this.trimAlignValue(v, _this.props); });
            if (nextBounds.every(function (v, i) { return v === bounds[i]; }))
                return;
            this.setState({ bounds: nextBounds });
            if (bounds.some(function (v) { return _this.isValueOutOfBounds(v, _this.props); })) {
                this.props.onChange(nextBounds);
            }
        }
        else {
            var value = this.props.value !== undefined ? this.props.value : bounds[1];
            var nextValue = this.trimAlignValue(value, this.props);
            if (nextValue === bounds[1] && bounds[0] === prevProps.min)
                return;
            this.setState({ bounds: [prevProps.min, nextValue] });
            if (this.isValueOutOfBounds(bounds[1], this.props)) {
                this.props.onChange(nextValue);
            }
        }
    };
    SliderBase.prototype.onChange = function (state) {
        var props = this.props;
        var isNotControlled = !('value' in props);
        if (isNotControlled) {
            this.setState(state);
        }
        else if (state.handle !== undefined) {
            this.setState({ handle: state.handle });
        }
        var data = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.state), state);
        var changedValue = props.range ? data.bounds : data.bounds[1];
        props.onChange(changedValue);
    };
    SliderBase.prototype.onMouseMove = function (e) {
        var position = getMousePosition(this.props.vertical, e);
        this.onMove(e, position - this.dragOffset);
    };
    SliderBase.prototype.onMove = function (e, position) {
        pauseEvent(e);
        var props = this.props;
        var state = this.state;
        var diffPosition = position - this.startPosition;
        diffPosition = this.props.vertical ? -diffPosition : diffPosition;
        var diffValue = diffPosition / this.getSliderLength() * (props.max - props.min);
        var value = this.trimAlignValue(this.startValue + diffValue);
        var oldValue = state.bounds[state.handle];
        if (value === oldValue)
            return;
        var nextBounds = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(state.bounds);
        nextBounds[state.handle] = value;
        var nextHandle = state.handle;
        if (props.pushable !== false) {
            var originalValue = state.bounds[nextHandle];
            this.pushSurroundingHandles(nextBounds, nextHandle, originalValue);
        }
        else if (props.allowCross) {
            nextBounds.sort(function (a, b) { return a - b; });
            nextHandle = nextBounds.indexOf(value);
        }
        this.onChange({
            handle: nextHandle,
            bounds: nextBounds,
        });
    };
    SliderBase.prototype.onStart = function (position) {
        var props = this.props;
        props.onBeforeChange(this.getValue());
        var value = this.calcValueByPos(position);
        this.startValue = value;
        this.startPosition = position;
        var state = this.state;
        var bounds = state.bounds;
        var valueNeedChanging = 1;
        if (this.props.range) {
            var closestBound = 0;
            for (var i = 1; i < bounds.length - 1; ++i) {
                if (value > bounds[i]) {
                    closestBound = i;
                }
            }
            if (Math.abs(bounds[closestBound + 1] - value) < Math.abs(bounds[closestBound] - value)) {
                closestBound = closestBound + 1;
            }
            valueNeedChanging = closestBound;
            var isAtTheSamePoint = (bounds[closestBound + 1] === bounds[closestBound]);
            if (isAtTheSamePoint) {
                valueNeedChanging = state.recent;
            }
            if (isAtTheSamePoint && (value !== bounds[closestBound + 1])) {
                valueNeedChanging = value < bounds[closestBound + 1] ? closestBound : closestBound + 1;
            }
        }
        this.setState({
            handle: valueNeedChanging,
            recent: valueNeedChanging,
        });
        var oldValue = state.bounds[valueNeedChanging];
        if (value === oldValue)
            return;
        var nextBounds = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(state.bounds);
        nextBounds[valueNeedChanging] = value;
        this.onChange({ bounds: nextBounds });
    };
    /**
     * Returns an array of possible slider points, taking into account both
     * `marks` and `step`. The result is cached.
     */
    SliderBase.prototype.getPoints = function () {
        var _a = this.props, marks = _a.marks, step = _a.step, min = _a.min, max = _a.max;
        var cache = this._getPointsCache;
        if (!cache || cache.marks !== marks || cache.step !== step) {
            var pointsObject = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, marks);
            if (step !== null) {
                for (var point = min; point <= max; point += step) {
                    pointsObject[point] = point;
                }
            }
            var points = Object.keys(pointsObject).map(parseFloat);
            points.sort(function (a, b) { return a - b; });
            this._getPointsCache = { marks: marks, step: step, points: points };
        }
        return this._getPointsCache.points;
    };
    SliderBase.prototype.getPrecision = function (step) {
        var stepString = step.toString();
        var precision = 0;
        if (stepString.indexOf('.') >= 0) {
            precision = stepString.length - stepString.indexOf('.') - 1;
        }
        return precision;
    };
    SliderBase.prototype.getSliderLength = function () {
        var slider = this.sliderElement.current;
        if (!slider) {
            return 0;
        }
        return this.props.vertical ? slider.clientHeight : slider.clientWidth;
    };
    SliderBase.prototype.getSliderStart = function () {
        var slider = this.sliderElement.current;
        var rect = slider.getBoundingClientRect();
        return this.props.vertical ? rect.top : rect.left;
    };
    SliderBase.prototype.getValue = function () {
        var bounds = this.state.bounds;
        return (this.props.range ? bounds : bounds[1]);
    };
    SliderBase.prototype.addDocumentEvents = function (type) {
        if (type === 'touch') {
            document.addEventListener('touchmove', this.eventHandlers.touchmove);
            document.addEventListener('touchend', this.eventHandlers.touchend);
        }
        else if (type === 'mouse') {
            document.addEventListener('mousemove', this.eventHandlers.mousemove);
            document.addEventListener('mouseup', this.eventHandlers.mouseup);
        }
    };
    SliderBase.prototype.calcValue = function (offset) {
        var _a = this.props, vertical = _a.vertical, min = _a.min, max = _a.max;
        var ratio = Math.abs(offset / this.getSliderLength());
        var value = vertical ? (1 - ratio) * (max - min) + min : ratio * (max - min) + min;
        return value;
    };
    SliderBase.prototype.calcValueByPos = function (position) {
        var pixelOffset = position - this.getSliderStart();
        var nextValue = this.trimAlignValue(this.calcValue(pixelOffset));
        return nextValue;
    };
    SliderBase.prototype.end = function (type) {
        this.removeEvents(type);
        this.props.onAfterChange(this.getValue());
        this.setState({ handle: null });
    };
    SliderBase.prototype.isEventFromHandle = function (e) {
        for (var _i = 0, _a = this.handleElements; _i < _a.length; _i++) {
            var h = _a[_i];
            if (h.current === e.target)
                return true;
        }
        return false;
    };
    SliderBase.prototype.isValueOutOfBounds = function (value, props) {
        return value < props.min || value > props.max;
    };
    SliderBase.prototype.pushHandle = function (bounds, handle, direction, amount) {
        var originalValue = bounds[handle];
        var currentValue = bounds[handle];
        while (direction * (currentValue - originalValue) < amount) {
            if (!this.pushHandleOnePoint(bounds, handle, direction)) {
                // can't push handle enough to create the needed `amount` gap, so we
                // revert its position to the original value
                bounds[handle] = originalValue;
                return false;
            }
            currentValue = bounds[handle];
        }
        // the handle was pushed enough to create the needed `amount` gap
        return true;
    };
    SliderBase.prototype.pushHandleOnePoint = function (bounds, handle, direction) {
        var points = this.getPoints();
        var pointIndex = points.indexOf(bounds[handle]);
        var nextPointIndex = pointIndex + direction;
        if (nextPointIndex >= points.length || nextPointIndex < 0) {
            // reached the minimum or maximum available point, can't push anymore
            return false;
        }
        var nextHandle = handle + direction;
        var nextValue = points[nextPointIndex];
        var threshold = this.props.pushable;
        var diffToNext = direction * (bounds[nextHandle] - nextValue);
        if (!this.pushHandle(bounds, nextHandle, direction, +threshold - diffToNext)) {
            // couldn't push next handle, so we won't push this one either
            return false;
        }
        // push the handle
        bounds[handle] = nextValue;
        return true;
    };
    SliderBase.prototype.pushSurroundingHandles = function (bounds, handle, originalValue) {
        var threshold = this.props.pushable;
        var value = bounds[handle];
        var direction = 0;
        if (bounds[handle + 1] - value < threshold) {
            direction = +1;
        }
        else if (value - bounds[handle - 1] < threshold) {
            direction = -1;
        }
        if (direction === 0) {
            return;
        }
        var nextHandle = handle + direction;
        var diffToNext = direction * (bounds[nextHandle] - value);
        if (!this.pushHandle(bounds, nextHandle, direction, +threshold - diffToNext)) {
            // revert to original value if pushing is impossible
            bounds[handle] = originalValue;
        }
    };
    SliderBase.prototype.removeEvents = function (type) {
        if (type === 'touch') {
            document.removeEventListener('touchmove', this.eventHandlers.touchmove);
            document.removeEventListener('touchend', this.eventHandlers.touchend);
        }
        else if (type === 'mouse') {
            document.removeEventListener('mousemove', this.eventHandlers.mousemove);
            document.removeEventListener('mouseup', this.eventHandlers.mouseup);
        }
    };
    SliderBase.prototype.trimAlignValue = function (v, props) {
        var _a = (this.state || {}), handle = _a.handle, bounds = _a.bounds;
        var _b = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.props), (props || {})), marks = _b.marks, step = _b.step, min = _b.min, max = _b.max, allowCross = _b.allowCross;
        var val = v;
        if (val <= min) {
            val = min;
        }
        if (val >= max) {
            val = max;
        }
        /* eslint-disable eqeqeq */
        if (!allowCross && handle != null && handle > 0 && val <= bounds[handle - 1]) {
            val = bounds[handle - 1];
        }
        if (!allowCross && handle != null && handle < bounds.length - 1 && val >= bounds[handle + 1]) {
            val = bounds[handle + 1];
        }
        /* eslint-enable eqeqeq */
        var points = Object.keys(marks).map(parseFloat);
        if (step !== null) {
            var closestStep = (Math.round((val - min) / step) * step) + min;
            points.push(closestStep);
        }
        var diffs = points.map(function (point) { return Math.abs(val - point); });
        var closestPoint = points[diffs.indexOf(Math.min.apply(Math, diffs))];
        return step !== null ? parseFloat(closestPoint.toFixed(this.getPrecision(step))) : closestPoint;
    };
    SliderBase.prototype.render = function () {
        var _a;
        var _this = this;
        var _b = this.state, handle = _b.handle, bounds = _b.bounds;
        var _c = this.props, className = _c.className, prefixCls = _c.prefixCls, disabled = _c.disabled, vertical = _c.vertical, range = _c.range, step = _c.step, marks = _c.marks, tipFormatter = _c.tipFormatter;
        var customHandle = this.props.handle;
        var offsets = bounds.map(this.calcOffset);
        var handleClassName = prefixCls + "-handle";
        var handlesClassNames = bounds.map(function (v, i) {
            var _a;
            return classNames((_a = {},
                _a[handleClassName] = true,
                _a[handleClassName + "-" + (i + 1)] = true,
                _a[handleClassName + "-lower"] = i === 0,
                _a[handleClassName + "-upper"] = i === bounds.length - 1,
                _a));
        });
        var isNoTip = (step === null) || (tipFormatter === null);
        var commonHandleProps = {
            prefixCls: prefixCls,
            noTip: isNoTip,
            tipFormatter: tipFormatter,
            vertical: vertical,
        };
        if (this.handleElements.length !== bounds.length) {
            this.handleElements = []; // = [];
            for (var i = 0; i < bounds.length; i++)
                this.handleElements.push(react__WEBPACK_IMPORTED_MODULE_1__["createRef"]());
        }
        var handles = bounds.map(function (v, i) { return react__WEBPACK_IMPORTED_MODULE_1__["cloneElement"](customHandle, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, commonHandleProps), { className: handlesClassNames[i], value: v, offset: offsets[i], dragging: handle === i, index: i, key: i, ref: _this.handleElements[i] })); });
        if (!range) {
            handles.shift();
        }
        var sliderClassName = classNames((_a = {},
            _a[prefixCls] = true,
            _a[prefixCls + "-with-marks"] = Object.keys(marks).length,
            _a[prefixCls + "-disabled"] = disabled,
            _a[prefixCls + "-vertical"] = this.props.vertical,
            _a[className] = !!className,
            _a));
        return (react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { ref: this.sliderElement, className: sliderClassName, onTouchStart: disabled ? _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"] : this.onTouchStart, onMouseDown: disabled ? _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"] : this.onMouseDown },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: prefixCls + "-rail" }),
            handles));
    };
    SliderBase.defaultProps = {
        prefixCls: 'msp-slider-base',
        className: '',
        min: 0,
        max: 100,
        step: 1,
        marks: {},
        handle: react__WEBPACK_IMPORTED_MODULE_1__["createElement"](Handle, { className: '', vertical: false, offset: 0, tipFormatter: function (v) { return v; }, value: 0, index: 0 }),
        onBeforeChange: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"],
        onChange: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"],
        onAfterChange: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* noop */ "k"],
        tipFormatter: function (value, index) { return value; },
        disabled: false,
        range: false,
        vertical: false,
        allowCross: true,
        pushable: false,
    };
    return SliderBase;
}(react__WEBPACK_IMPORTED_MODULE_1__["Component"]));

//# sourceMappingURL=slider.js.map

/***/ }),
/* 329 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return download; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function openUrl(url) {
    var opened = window.open(url, '_blank');
    if (!opened) {
        window.location.href = url;
    }
}
function click(node) {
    try {
        node.dispatchEvent(new MouseEvent('click'));
    }
    catch (e) {
        var evt = document.createEvent('MouseEvents');
        evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
        node.dispatchEvent(evt);
    }
}
function download(data, downloadName) {
    // using ideas from https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.js
    if (downloadName === void 0) { downloadName = 'download'; }
    if (!data)
        return;
    if ('download' in HTMLAnchorElement.prototype) {
        var a_1 = document.createElement('a');
        a_1.download = downloadName;
        a_1.rel = 'noopener';
        if (typeof data === 'string') {
            a_1.href = data;
            click(a_1);
        }
        else {
            a_1.href = URL.createObjectURL(data);
            setTimeout(function () { return URL.revokeObjectURL(a_1.href); }, 4E4); // 40s
            setTimeout(function () { return click(a_1); });
        }
    }
    else if (typeof navigator !== 'undefined' && navigator.msSaveOrOpenBlob) {
        // native saveAs in IE 10+
        navigator.msSaveOrOpenBlob(data, downloadName);
    }
    else {
        var ua = window.navigator.userAgent;
        var isSafari = /Safari/i.test(ua);
        var isChromeIos_1 = /CriOS\/[\d]+/.test(ua);
        var open_1 = function (str) {
            openUrl(isChromeIos_1 ? str : str.replace(/^data:[^;]*;/, 'data:attachment/file;'));
        };
        if ((isSafari || isChromeIos_1) && FileReader) {
            if (data instanceof Blob) {
                // no downloading of blob urls in Safari
                var reader_1 = new FileReader();
                reader_1.onloadend = function () { return open_1(reader_1.result); };
                reader_1.readAsDataURL(data);
            }
            else {
                open_1(data);
            }
        }
        else {
            var url_1 = URL.createObjectURL(data);
            location.href = url_1;
            setTimeout(function () { return URL.revokeObjectURL(url_1); }, 4E4); // 40s
        }
    }
}
//# sourceMappingURL=download.js.map

/***/ }),
/* 330 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export InteractionTypeColorThemeParams */
/* unused harmony export getInteractionTypeColorThemeParams */
/* unused harmony export InteractionTypeColorTheme */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InteractionTypeColorThemeProvider; });
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _interactions__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(108);
/* harmony import */ var _mol_util_legend__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(141);
/* harmony import */ var _interactions_interactions__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(200);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var DefaultColor = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["Color"])(0xCCCCCC);
var Description = 'Assigns colors according the interaction type of a link.';
var InteractionTypeColors = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["ColorMap"])({
    HydrogenBond: 0x2B83BA,
    Hydrophobic: 0x808080,
    HalogenBond: 0x40FFBF,
    Ionic: 0xF0C814,
    MetalCoordination: 0x8C4099,
    CationPi: 0xFF8000,
    PiStacking: 0x8CB366,
    WeakHydrogenBond: 0xC5DDEC,
});
var InteractionTypeColorTable = [
    ['Hydrogen Bond', InteractionTypeColors.HydrogenBond],
    ['Hydrophobic', InteractionTypeColors.Hydrophobic],
    ['Halogen Bond', InteractionTypeColors.HalogenBond],
    ['Ionic', InteractionTypeColors.Ionic],
    ['Metal Coordination', InteractionTypeColors.MetalCoordination],
    ['Cation Pi', InteractionTypeColors.CationPi],
    ['Pi Stacking', InteractionTypeColors.PiStacking],
    ['Weak HydrogenBond', InteractionTypeColors.WeakHydrogenBond],
];
function typeColor(type) {
    switch (type) {
        case 4 /* HydrogenBond */:
            return InteractionTypeColors.HydrogenBond;
        case 6 /* Hydrophobic */:
            return InteractionTypeColors.Hydrophobic;
        case 5 /* HalogenBond */:
            return InteractionTypeColors.HalogenBond;
        case 1 /* Ionic */:
            return InteractionTypeColors.Ionic;
        case 7 /* MetalCoordination */:
            return InteractionTypeColors.MetalCoordination;
        case 2 /* CationPi */:
            return InteractionTypeColors.CationPi;
        case 3 /* PiStacking */:
            return InteractionTypeColors.PiStacking;
        case 8 /* WeakHydrogenBond */:
            return InteractionTypeColors.WeakHydrogenBond;
        case 0 /* Unknown */:
            return DefaultColor;
    }
}
var InteractionTypeColorThemeParams = {};
function getInteractionTypeColorThemeParams(ctx) {
    return InteractionTypeColorThemeParams; // TODO return copy
}
function InteractionTypeColorTheme(ctx, props) {
    var color;
    var interactions = ctx.structure ? _interactions__WEBPACK_IMPORTED_MODULE_2__[/* InteractionsProvider */ "a"].get(ctx.structure) : undefined;
    var contextHash = interactions === null || interactions === void 0 ? void 0 : interactions.version;
    if (interactions && interactions.value) {
        color = function (location) {
            if (_interactions_interactions__WEBPACK_IMPORTED_MODULE_4__[/* Interactions */ "a"].isLocation(location)) {
                var _a = location.data.interactions, unitsContacts = _a.unitsContacts, contacts = _a.contacts;
                var _b = location.element, unitA = _b.unitA, unitB = _b.unitB, indexA = _b.indexA, indexB = _b.indexB;
                if (unitA === unitB) {
                    var links = unitsContacts.get(unitA.id);
                    var idx = links.getDirectedEdgeIndex(indexA, indexB);
                    return typeColor(links.edgeProps.type[idx]);
                }
                else {
                    var idx = contacts.getEdgeIndex(indexA, unitA, indexB, unitB);
                    return typeColor(contacts.edges[idx].props.type);
                }
            }
            return DefaultColor;
        };
    }
    else {
        color = function () { return DefaultColor; };
    }
    return {
        factory: InteractionTypeColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        contextHash: contextHash,
        description: Description,
        legend: Object(_mol_util_legend__WEBPACK_IMPORTED_MODULE_3__[/* TableLegend */ "b"])(InteractionTypeColorTable)
    };
}
var InteractionTypeColorThemeProvider = {
    name: 'interaction-type',
    label: 'Interaction Type',
    category: "Miscellaneous" /* Misc */,
    factory: InteractionTypeColorTheme,
    getParams: getInteractionTypeColorThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(InteractionTypeColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.structure; },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? _interactions__WEBPACK_IMPORTED_MODULE_2__[/* InteractionsProvider */ "a"].attach(ctx, data.structure, void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.customPropertyDescriptors.reference(_interactions__WEBPACK_IMPORTED_MODULE_2__[/* InteractionsProvider */ "a"].descriptor, false); }
    }
};
//# sourceMappingURL=interaction-type.js.map

/***/ }),
/* 331 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return DrawPassParams; });
/* unused harmony export DefaultDrawPassProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return DrawPass; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _helper_camera_helper__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(284);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DrawPassParams = {
    cameraHelper: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].Group(_helper_camera_helper__WEBPACK_IMPORTED_MODULE_1__[/* CameraHelperParams */ "b"])
};
var DefaultDrawPassProps = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(DrawPassParams);
var DrawPass = /** @class */ (function () {
    function DrawPass(webgl, renderer, scene, camera, debugHelper, handleHelper, props) {
        if (props === void 0) { props = {}; }
        this.webgl = webgl;
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        this.debugHelper = debugHelper;
        this.handleHelper = handleHelper;
        var gl = webgl.gl, extensions = webgl.extensions, resources = webgl.resources;
        var width = gl.drawingBufferWidth;
        var height = gl.drawingBufferHeight;
        this.colorTarget = webgl.createRenderTarget(width, height);
        this.packedDepth = !extensions.depthTexture;
        this.depthTarget = this.packedDepth ? webgl.createRenderTarget(width, height) : null;
        this.depthTexture = this.depthTarget ? this.depthTarget.texture : resources.texture('image-depth', 'depth', 'ushort', 'nearest');
        if (!this.packedDepth) {
            this.depthTexture.define(width, height);
            this.depthTexture.attachFramebuffer(this.colorTarget.framebuffer, 'depth');
        }
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultDrawPassProps), props);
        this.cameraHelper = new _helper_camera_helper__WEBPACK_IMPORTED_MODULE_1__[/* CameraHelper */ "a"](webgl, p.cameraHelper);
    }
    DrawPass.prototype.setSize = function (width, height) {
        this.colorTarget.setSize(width, height);
        if (this.depthTarget) {
            this.depthTarget.setSize(width, height);
        }
        else {
            this.depthTexture.define(width, height);
        }
    };
    DrawPass.prototype.setProps = function (props) {
        if (props.cameraHelper)
            this.cameraHelper.setProps(props.cameraHelper);
    };
    Object.defineProperty(DrawPass.prototype, "props", {
        get: function () {
            return {
                cameraHelper: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.cameraHelper.props)
            };
        },
        enumerable: false,
        configurable: true
    });
    DrawPass.prototype.render = function (toDrawingBuffer, transparentBackground) {
        var _a = this, webgl = _a.webgl, renderer = _a.renderer, colorTarget = _a.colorTarget, depthTarget = _a.depthTarget;
        if (toDrawingBuffer) {
            webgl.unbindFramebuffer();
        }
        else {
            colorTarget.bind();
            if (!this.packedDepth) {
                // TODO unlcear why it is not enough to call `attachFramebuffer` in `Texture.reset`
                this.depthTexture.attachFramebuffer(this.colorTarget.framebuffer, 'depth');
            }
        }
        renderer.setViewport(0, 0, colorTarget.getWidth(), colorTarget.getHeight());
        this.renderInternal('color', transparentBackground);
        // do a depth pass if not rendering to drawing buffer and
        // extensions.depthTexture is unsupported (i.e. depthTarget is set)
        if (!toDrawingBuffer && depthTarget) {
            depthTarget.bind();
            this.renderInternal('depth', transparentBackground);
        }
    };
    DrawPass.prototype.renderInternal = function (variant, transparentBackground) {
        var _a = this, renderer = _a.renderer, scene = _a.scene, camera = _a.camera, debugHelper = _a.debugHelper, cameraHelper = _a.cameraHelper, handleHelper = _a.handleHelper;
        renderer.render(scene, camera, variant, true, transparentBackground);
        if (debugHelper.isEnabled) {
            debugHelper.syncVisibility();
            renderer.render(debugHelper.scene, camera, variant, false, transparentBackground);
        }
        if (handleHelper.isEnabled) {
            renderer.render(handleHelper.scene, camera, variant, false, transparentBackground);
        }
        if (cameraHelper.isEnabled) {
            cameraHelper.update(camera);
            renderer.render(cameraHelper.scene, cameraHelper.camera, variant, false, transparentBackground);
        }
    };
    return DrawPass;
}());

//# sourceMappingURL=draw.js.map

/***/ }),
/* 332 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export setCanvasSize */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return resizeCanvas; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return canvasToBlob; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

/** Set canvas size taking `devicePixelRatio` into account */
function setCanvasSize(canvas, width, height) {
    canvas.width = Math.round(window.devicePixelRatio * width);
    canvas.height = Math.round(window.devicePixelRatio * height);
    Object.assign(canvas.style, { width: width + "px", height: height + "px" });
}
/** Resize canvas to container element taking `devicePixelRatio` into account */
function resizeCanvas(canvas, container) {
    var width = window.innerWidth;
    var height = window.innerHeight;
    if (container !== document.body) {
        var bounds = container.getBoundingClientRect();
        width = bounds.right - bounds.left;
        height = bounds.bottom - bounds.top;
    }
    setCanvasSize(canvas, width, height);
}
function _canvasToBlob(canvas, callback, type, quality) {
    var bin = atob(canvas.toDataURL(type, quality).split(',')[1]);
    var len = bin.length;
    var len32 = len >> 2;
    var a8 = new Uint8Array(len);
    var a32 = new Uint32Array(a8.buffer, 0, len32);
    var j = 0;
    for (var i = 0; i < len32; ++i) {
        a32[i] = bin.charCodeAt(j++) |
            bin.charCodeAt(j++) << 8 |
            bin.charCodeAt(j++) << 16 |
            bin.charCodeAt(j++) << 24;
    }
    var tailLength = len & 3;
    while (tailLength--)
        a8[j] = bin.charCodeAt(j++);
    callback(new Blob([a8], { type: type || 'image/png' }));
}
function canvasToBlob(canvas, type, quality) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            return [2 /*return*/, new Promise(function (resolve, reject) {
                    var callback = function (blob) {
                        if (blob)
                            resolve(blob);
                        else
                            reject('no blob returned');
                    };
                    if (!HTMLCanvasElement.prototype.toBlob) {
                        _canvasToBlob(canvas, callback, type, quality);
                    }
                    else {
                        canvas.toBlob(callback, type, quality);
                    }
                })];
        });
    });
}
//# sourceMappingURL=util.js.map

/***/ }),
/* 333 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "c", function() { return /* binding */ getGLContext; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ checkError; });
__webpack_require__.d(__webpack_exports__, "d", function() { return /* binding */ readPixels; });
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ createContext; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/compat.js
var compat = __webpack_require__(91);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/framebuffer.js
var webgl_framebuffer = __webpack_require__(261);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/extensions.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function createExtensions(gl) {
    var instancedArrays = Object(compat["g" /* getInstancedArrays */])(gl);
    if (instancedArrays === null) {
        throw new Error('Could not find support for "instanced_arrays"');
    }
    var textureFloat = Object(compat["j" /* getTextureFloat */])(gl);
    if (textureFloat === null) {
        throw new Error('Could not find support for "texture_float"');
    }
    var elementIndexUint = Object(compat["e" /* getElementIndexUint */])(gl);
    if (elementIndexUint === null) {
        throw new Error('Could not find support for "element_index_uint"');
    }
    var standardDerivatives = Object(compat["i" /* getStandardDerivatives */])(gl);
    if (debug["a" /* isDebugMode */] && standardDerivatives === null) {
        // - non-support handled downstream (flat shading option is ignored)
        // - can't be a required extension because it is not supported by `headless-gl`
        console.log('Could not find support for "standard_derivatives"');
    }
    var textureFloatLinear = Object(compat["k" /* getTextureFloatLinear */])(gl);
    if (debug["a" /* isDebugMode */] && textureFloatLinear === null) {
        // TODO handle non-support downstream (no gpu gaussian calc, no gpu mc???)
        // - can't be a required extension because it is not supported by `headless-gl`
        console.log('Could not find support for "texture_float_linear"');
    }
    var depthTexture = Object(compat["c" /* getDepthTexture */])(gl);
    if (debug["a" /* isDebugMode */] && depthTexture === null) {
        console.log('Could not find support for "depth_texture"');
    }
    var blendMinMax = Object(compat["a" /* getBlendMinMax */])(gl);
    if (debug["a" /* isDebugMode */] && blendMinMax === null) {
        // TODO handle non-support downstream (e.g. no gpu gaussian calc)
        // - can't be a required extension because it is not supported by `headless-gl`
        console.log('Could not find support for "blend_minmax"');
    }
    var vertexArrayObject = Object(compat["l" /* getVertexArrayObject */])(gl);
    if (debug["a" /* isDebugMode */] && vertexArrayObject === null) {
        console.log('Could not find support for "vertex_array_object"');
    }
    var fragDepth = Object(compat["f" /* getFragDepth */])(gl);
    if (debug["a" /* isDebugMode */] && fragDepth === null) {
        console.log('Could not find support for "frag_depth"');
    }
    var colorBufferFloat = Object(compat["b" /* getColorBufferFloat */])(gl);
    if (debug["a" /* isDebugMode */] && colorBufferFloat === null) {
        console.log('Could not find support for "color_buffer_float"');
    }
    var drawBuffers = Object(compat["d" /* getDrawBuffers */])(gl);
    if (debug["a" /* isDebugMode */] && drawBuffers === null) {
        console.log('Could not find support for "draw_buffers"');
    }
    var shaderTextureLod = Object(compat["h" /* getShaderTextureLod */])(gl);
    if (debug["a" /* isDebugMode */] && shaderTextureLod === null) {
        console.log('Could not find support for "shader_texture_lod"');
    }
    return {
        instancedArrays: instancedArrays,
        standardDerivatives: standardDerivatives,
        textureFloat: textureFloat,
        textureFloatLinear: textureFloatLinear,
        elementIndexUint: elementIndexUint,
        depthTexture: depthTexture,
        blendMinMax: blendMinMax,
        vertexArrayObject: vertexArrayObject,
        fragDepth: fragDepth,
        colorBufferFloat: colorBufferFloat,
        drawBuffers: drawBuffers,
        shaderTextureLod: shaderTextureLod,
    };
}
//# sourceMappingURL=extensions.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/state.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function createState(gl) {
    var enabledCapabilities = {};
    var currentFrontFace = gl.getParameter(gl.FRONT_FACE);
    var currentCullFace = gl.getParameter(gl.CULL_FACE_MODE);
    var currentDepthMask = gl.getParameter(gl.DEPTH_WRITEMASK);
    var currentColorMask = gl.getParameter(gl.COLOR_WRITEMASK);
    var currentClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
    var currentBlendSrcRGB = gl.getParameter(gl.BLEND_SRC_RGB);
    var currentBlendDstRGB = gl.getParameter(gl.BLEND_DST_RGB);
    var currentBlendSrcAlpha = gl.getParameter(gl.BLEND_SRC_ALPHA);
    var currentBlendDstAlpha = gl.getParameter(gl.BLEND_DST_ALPHA);
    var currentBlendEqRGB = gl.getParameter(gl.BLEND_EQUATION_RGB);
    var currentBlendEqAlpha = gl.getParameter(gl.BLEND_EQUATION_ALPHA);
    return {
        currentProgramId: -1,
        currentMaterialId: -1,
        currentRenderItemId: -1,
        enable: function (cap) {
            if (enabledCapabilities[cap] !== true) {
                gl.enable(cap);
                enabledCapabilities[cap] = true;
            }
        },
        disable: function (cap) {
            if (enabledCapabilities[cap] !== false) {
                gl.disable(cap);
                enabledCapabilities[cap] = false;
            }
        },
        frontFace: function (mode) {
            if (mode !== currentFrontFace) {
                gl.frontFace(mode);
                currentFrontFace = mode;
            }
        },
        cullFace: function (mode) {
            if (mode !== currentCullFace) {
                gl.cullFace(mode);
                currentCullFace = mode;
            }
        },
        depthMask: function (flag) {
            if (flag !== currentDepthMask) {
                gl.depthMask(flag);
                currentDepthMask = flag;
            }
        },
        colorMask: function (red, green, blue, alpha) {
            if (red !== currentColorMask[0] || green !== currentColorMask[1] || blue !== currentColorMask[2] || alpha !== currentColorMask[3]) {
                gl.colorMask(red, green, blue, alpha);
                currentColorMask[0] = red;
                currentColorMask[1] = green;
                currentColorMask[2] = blue;
                currentColorMask[3] = alpha;
            }
        },
        clearColor: function (red, green, blue, alpha) {
            if (red !== currentClearColor[0] || green !== currentClearColor[1] || blue !== currentClearColor[2] || alpha !== currentClearColor[3]) {
                gl.clearColor(red, green, blue, alpha);
                currentClearColor[0] = red;
                currentClearColor[1] = green;
                currentClearColor[2] = blue;
                currentClearColor[3] = alpha;
            }
        },
        blendFunc: function (src, dst) {
            if (src !== currentBlendSrcRGB || dst !== currentBlendDstRGB || src !== currentBlendSrcAlpha || dst !== currentBlendDstAlpha) {
                gl.blendFunc(src, dst);
                currentBlendSrcRGB = src;
                currentBlendDstRGB = dst;
                currentBlendSrcAlpha = src;
                currentBlendDstAlpha = dst;
            }
        },
        blendFuncSeparate: function (srcRGB, dstRGB, srcAlpha, dstAlpha) {
            if (srcRGB !== currentBlendSrcRGB || dstRGB !== currentBlendDstRGB || srcAlpha !== currentBlendSrcAlpha || dstAlpha !== currentBlendDstAlpha) {
                gl.blendFuncSeparate(srcRGB, dstRGB, srcAlpha, dstAlpha);
                currentBlendSrcRGB = srcRGB;
                currentBlendDstRGB = dstRGB;
                currentBlendSrcAlpha = srcAlpha;
                currentBlendDstAlpha = dstAlpha;
            }
        },
        blendEquation: function (mode) {
            if (mode !== currentBlendEqRGB || mode !== currentBlendEqAlpha) {
                gl.blendEquation(mode);
                currentBlendEqRGB = mode;
                currentBlendEqAlpha = mode;
            }
        },
        blendEquationSeparate: function (modeRGB, modeAlpha) {
            if (modeRGB !== currentBlendEqRGB || modeAlpha !== currentBlendEqAlpha) {
                gl.blendEquationSeparate(modeRGB, modeAlpha);
                currentBlendEqRGB = modeRGB;
                currentBlendEqAlpha = modeAlpha;
            }
        },
        reset: function () {
            enabledCapabilities = {};
            currentFrontFace = gl.getParameter(gl.FRONT_FACE);
            currentCullFace = gl.getParameter(gl.CULL_FACE_MODE);
            currentDepthMask = gl.getParameter(gl.DEPTH_WRITEMASK);
            currentColorMask = gl.getParameter(gl.COLOR_WRITEMASK);
            currentClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
            currentBlendSrcRGB = gl.getParameter(gl.BLEND_SRC_RGB);
            currentBlendDstRGB = gl.getParameter(gl.BLEND_DST_RGB);
            currentBlendSrcAlpha = gl.getParameter(gl.BLEND_SRC_ALPHA);
            currentBlendDstAlpha = gl.getParameter(gl.BLEND_DST_ALPHA);
            currentBlendEqRGB = gl.getParameter(gl.BLEND_EQUATION_RGB);
            currentBlendEqAlpha = gl.getParameter(gl.BLEND_EQUATION_ALPHA);
        }
    };
}
//# sourceMappingURL=state.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/image.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var PixelData;
(function (PixelData) {
    function create(array, width, height) {
        return { array: array, width: width, height: height };
    }
    PixelData.create = create;
    /** horizontally flips the pixel data in-place */
    function flipY(pixelData) {
        var array = pixelData.array, width = pixelData.width, height = pixelData.height;
        var width4 = width * 4;
        for (var i = 0, maxI = height / 2; i < maxI; ++i) {
            for (var j = 0, maxJ = width4; j < maxJ; ++j) {
                var index1 = i * width4 + j;
                var index2 = (height - i - 1) * width4 + j;
                var tmp = array[index1];
                array[index1] = array[index2];
                array[index2] = tmp;
            }
        }
        return pixelData;
    }
    PixelData.flipY = flipY;
})(PixelData || (PixelData = {}));
//# sourceMappingURL=image.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/uniform.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function getUniformType(gl, kind) {
    switch (kind) {
        case 'f':
        case 'f[]': return gl.FLOAT;
        case 'i':
        case 'i[]': return gl.INT;
        case 'v2':
        case 'v2[]': return gl.FLOAT_VEC2;
        case 'v3':
        case 'v3[]': return gl.FLOAT_VEC3;
        case 'v4':
        case 'v4[]': return gl.FLOAT_VEC4;
        case 'm3':
        case 'm3[]': return gl.FLOAT_MAT3;
        case 'm4':
        case 'm4[]': return gl.FLOAT_MAT4;
        default: console.error("unknown uniform kind '" + kind + "'");
    }
}
function uniform1f(gl, location, value) { gl.uniform1f(location, value); }
function uniform1fv(gl, location, value) { gl.uniform1fv(location, value); }
function uniform1i(gl, location, value) { gl.uniform1i(location, value); }
function uniform1iv(gl, location, value) { gl.uniform1iv(location, value); }
function uniform2fv(gl, location, value) { gl.uniform2fv(location, value); }
function uniform3fv(gl, location, value) { gl.uniform3fv(location, value); }
function uniform4fv(gl, location, value) { gl.uniform4fv(location, value); }
function uniformMatrix3fv(gl, location, value) { gl.uniformMatrix3fv(location, false, value); }
function uniformMatrix4fv(gl, location, value) { gl.uniformMatrix4fv(location, false, value); }
function getUniformSetter(kind) {
    switch (kind) {
        case 'f': return uniform1f;
        case 'f[]': return uniform1fv;
        case 'i':
        case 't': return uniform1i;
        case 'i[]':
        case 't[]': return uniform1iv;
        case 'v2':
        case 'v2[]': return uniform2fv;
        case 'v3':
        case 'v3[]': return uniform3fv;
        case 'v4':
        case 'v4[]': return uniform4fv;
        case 'm3':
        case 'm3[]': return uniformMatrix3fv;
        case 'm4':
        case 'm4[]': return uniformMatrix4fv;
    }
}
function getUniformSetters(schema) {
    var setters = {};
    Object.keys(schema).forEach(function (k) {
        var spec = schema[k];
        if (spec.type === 'uniform') {
            setters[k] = getUniformSetter(spec.kind);
        }
        else if (spec.type === 'texture') {
            setters[k] = getUniformSetter('t');
        }
    });
    return setters;
}
//# sourceMappingURL=uniform.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/buffer.js
var webgl_buffer = __webpack_require__(281);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/id-factory.js
var id_factory = __webpack_require__(96);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/program.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var getNextProgramId = Object(id_factory["a" /* idFactory */])();
function getLocations(gl, program, schema) {
    var locations = {};
    Object.keys(schema).forEach(function (k) {
        var spec = schema[k];
        if (spec.type === 'attribute') {
            var loc = gl.getAttribLocation(program, k);
            // unused attributes will result in a `-1` location which is usually fine
            // if (loc === -1) console.info(`Could not get attribute location for '${k}'`)
            locations[k] = loc;
        }
        else if (spec.type === 'uniform' || spec.type === 'texture') {
            var loc = gl.getUniformLocation(program, k);
            // unused uniforms will result in a `null` location which is usually fine
            // if (loc === null) console.info(`Could not get uniform location for '${k}'`)
            locations[k] = loc;
        }
    });
    return locations;
}
function checkActiveAttributes(gl, program, schema) {
    var attribCount = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
    for (var i = 0; i < attribCount; ++i) {
        var info = gl.getActiveAttrib(program, i);
        if (info) {
            var name_1 = info.name, type = info.type;
            if (name_1.startsWith('__activeAttribute')) {
                // name assigned by `gl.shim.ts`, ignore for checks
                continue;
            }
            var spec = schema[name_1];
            if (spec === undefined) {
                throw new Error("missing 'uniform' or 'texture' with name '" + name_1 + "' in schema");
            }
            if (spec.type !== 'attribute') {
                throw new Error("'" + name_1 + "' must be of type 'attribute' but is '" + spec.type + "'");
            }
            var attribType = Object(webgl_buffer["d" /* getAttribType */])(gl, spec.kind, spec.itemSize);
            if (attribType !== type) {
                throw new Error("unexpected attribute type for " + name_1);
            }
        }
    }
}
function checkActiveUniforms(gl, program, schema) {
    var attribCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
    for (var i = 0; i < attribCount; ++i) {
        var info = gl.getActiveUniform(program, i);
        if (info) {
            var name_2 = info.name, type = info.type;
            if (name_2.startsWith('__activeUniform')) {
                // name assigned by `gl.shim.ts`, ignore for checks
                continue;
            }
            var baseName = name_2.replace(/[[0-9]+\]$/, ''); // 'array' uniforms
            var spec = schema[baseName];
            if (spec === undefined) {
                throw new Error("missing 'uniform' or 'texture' with name '" + name_2 + "' in schema");
            }
            if (spec.type === 'uniform') {
                var uniformType = getUniformType(gl, spec.kind);
                if (uniformType !== type) {
                    throw new Error("unexpected uniform type for " + name_2);
                }
            }
            else if (spec.type === 'texture') {
                if (spec.kind === 'image-float32' || spec.kind === 'image-uint8') {
                    if (type !== gl.SAMPLER_2D) {
                        throw new Error("unexpected sampler type for '" + name_2 + "'");
                    }
                }
                else if (spec.kind === 'volume-float32' || spec.kind === 'volume-uint8') {
                    if (type !== gl.SAMPLER_3D) {
                        throw new Error("unexpected sampler type for '" + name_2 + "'");
                    }
                }
                else {
                    // TODO
                }
            }
            else {
                throw new Error("'" + name_2 + "' must be of type 'uniform' or 'texture' but is '" + spec.type + "'");
            }
        }
    }
}
function checkProgram(gl, program) {
    // no-op in FF on Mac, see https://bugzilla.mozilla.org/show_bug.cgi?id=1284425
    // gl.validateProgram(program)
    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        throw new Error("Could not compile WebGL program. \n\n" + gl.getProgramInfoLog(program));
    }
}
function getProgram(gl) {
    var program = gl.createProgram();
    if (program === null) {
        throw new Error('Could not create WebGL program');
    }
    return program;
}
function createProgram(gl, state, extensions, getShader, props) {
    var defineValues = props.defineValues, _shaderCode = props.shaderCode, schema = props.schema;
    var program = getProgram(gl);
    var programId = getNextProgramId();
    var shaderCode = Object(shader_code["i" /* addShaderDefines */])(gl, extensions, defineValues, _shaderCode);
    var vertShader = getShader('vert', shaderCode.vert);
    var fragShader = getShader('frag', shaderCode.frag);
    var locations;
    var uniformSetters;
    function init() {
        vertShader.attach(program);
        fragShader.attach(program);
        gl.linkProgram(program);
        if (debug["a" /* isDebugMode */]) {
            checkProgram(gl, program);
        }
        locations = getLocations(gl, program, schema);
        uniformSetters = getUniformSetters(schema);
        if (debug["a" /* isDebugMode */]) {
            checkActiveAttributes(gl, program, schema);
            checkActiveUniforms(gl, program, schema);
        }
    }
    init();
    var destroyed = false;
    return {
        id: programId,
        use: function () {
            // console.log('use', programId)
            state.currentProgramId = programId;
            gl.useProgram(program);
        },
        setUniforms: function (uniformValues) {
            for (var i = 0, il = uniformValues.length; i < il; ++i) {
                var _a = uniformValues[i], k = _a[0], v = _a[1];
                if (v) {
                    var l = locations[k];
                    if (l !== null)
                        uniformSetters[k](gl, l, v.ref.value);
                }
            }
        },
        bindAttributes: function (attributeBuffers) {
            for (var i = 0, il = attributeBuffers.length; i < il; ++i) {
                var _a = attributeBuffers[i], k = _a[0], buffer = _a[1];
                var l = locations[k];
                if (l !== -1)
                    buffer.bind(l);
            }
        },
        bindTextures: function (textures) {
            for (var i = 0, il = textures.length; i < il; ++i) {
                var _a = textures[i], k = _a[0], texture = _a[1];
                var l = locations[k];
                if (l !== null) {
                    // TODO if the order and count of textures in a material can be made invariant
                    //      bind needs to be called only when the material changes
                    texture.bind(i);
                    uniformSetters[k](gl, l, i);
                }
            }
        },
        reset: function () {
            program = getProgram(gl);
            init();
        },
        destroy: function () {
            if (destroyed)
                return;
            vertShader.destroy();
            fragShader.destroy();
            gl.deleteProgram(program);
            destroyed = true;
        }
    };
}
//# sourceMappingURL=program.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/shader.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var getNextShaderId = Object(id_factory["a" /* idFactory */])();
function addLineNumbers(source) {
    var lines = source.split('\n');
    for (var i = 0; i < lines.length; ++i) {
        lines[i] = (i + 1) + ': ' + lines[i];
    }
    return lines.join('\n');
}
function shader_getShader(gl, props) {
    var type = props.type, source = props.source;
    var shader = gl.createShader(type === 'vert' ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
    if (shader === null) {
        throw new Error("Error creating " + type + " shader");
    }
    gl.shaderSource(shader, source);
    gl.compileShader(shader);
    if (debug["a" /* isDebugMode */] && gl.getShaderParameter(shader, gl.COMPILE_STATUS) === false) {
        console.warn("'" + type + "' shader info log '" + gl.getShaderInfoLog(shader) + "'\n" + addLineNumbers(source));
        throw new Error("Error compiling " + type + " shader");
    }
    return shader;
}
function createShader(gl, props) {
    var shader = shader_getShader(gl, props);
    return {
        id: getNextShaderId(),
        attach: function (program) {
            gl.attachShader(program, shader);
        },
        reset: function () {
            shader = shader_getShader(gl, props);
        },
        destroy: function () {
            gl.deleteShader(shader);
        }
    };
}
//# sourceMappingURL=shader.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/reference-cache.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
function createReference(value, usageCount) {
    if (usageCount === void 0) { usageCount = 0; }
    return { value: value, usageCount: usageCount };
}
function createReferenceItem(ref) {
    return {
        free: function () {
            ref.usageCount -= 1;
        },
        value: ref.value
    };
}
function createReferenceCache(hashFn, ctor, deleteFn) {
    var map = new Map();
    return {
        get: function (props) {
            var id = hashFn(props);
            var ref = map.get(id);
            if (!ref) {
                ref = createReference(ctor(props));
                map.set(id, ref);
            }
            ref.usageCount += 1;
            return createReferenceItem(ref);
        },
        clear: function () {
            map.forEach(function (ref, id) {
                if (ref.usageCount <= 0) {
                    if (ref.usageCount < 0) {
                        console.warn('Reference usageCount below zero.');
                    }
                    deleteFn(ref.value);
                    map.delete(id);
                }
            });
        },
        get count() {
            return map.size;
        },
        dispose: function () {
            map.forEach(function (ref) { return deleteFn(ref.value); });
            map.clear();
        },
    };
}
//# sourceMappingURL=reference-cache.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/renderbuffer.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var getNextRenderbufferId = Object(id_factory["a" /* idFactory */])();
function getFormat(gl, format) {
    switch (format) {
        case 'depth16': return gl.DEPTH_COMPONENT16;
        case 'stencil8': return gl.STENCIL_INDEX8;
        case 'rgba4': return gl.RGBA4;
        case 'depth-stencil': return gl.DEPTH_STENCIL;
    }
}
function getAttachment(gl, attachment) {
    switch (attachment) {
        case 'depth': return gl.DEPTH_ATTACHMENT;
        case 'stencil': return gl.STENCIL_ATTACHMENT;
        case 'depth-stencil': return gl.DEPTH_STENCIL_ATTACHMENT;
        case 'color0': return gl.COLOR_ATTACHMENT0;
    }
}
function getRenderbuffer(gl) {
    var renderbuffer = gl.createRenderbuffer();
    if (renderbuffer === null) {
        throw new Error('Could not create WebGL renderbuffer');
    }
    return renderbuffer;
}
function createRenderbuffer(gl, format, attachment, _width, _height) {
    var _renderbuffer = getRenderbuffer(gl);
    var bind = function () { return gl.bindRenderbuffer(gl.RENDERBUFFER, _renderbuffer); };
    var _format = getFormat(gl, format);
    var _attachment = getAttachment(gl, attachment);
    function init() {
        bind();
        gl.renderbufferStorage(gl.RENDERBUFFER, _format, _width, _height);
    }
    init();
    var destroyed = false;
    return {
        id: getNextRenderbufferId(),
        bind: bind,
        attachFramebuffer: function (framebuffer) {
            framebuffer.bind();
            bind();
            gl.framebufferRenderbuffer(gl.FRAMEBUFFER, _attachment, gl.RENDERBUFFER, _renderbuffer);
            if (debug["a" /* isDebugMode */])
                Object(webgl_framebuffer["a" /* checkFramebufferStatus */])(gl);
        },
        setSize: function (width, height) {
            _width = width;
            _height = height;
            init();
        },
        reset: function () {
            _renderbuffer = getRenderbuffer(gl);
            init();
        },
        destroy: function () {
            if (destroyed)
                return;
            gl.deleteRenderbuffer(_renderbuffer);
            destroyed = true;
        }
    };
}
//# sourceMappingURL=renderbuffer.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/texture.js
var texture = __webpack_require__(362);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/vertex-array.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var getNextVertexArrayId = Object(id_factory["a" /* idFactory */])();
function getVertexArray(extensions) {
    var vertexArrayObject = extensions.vertexArrayObject;
    if (!vertexArrayObject) {
        throw new Error('VertexArrayObject not supported');
    }
    var vertexArray = vertexArrayObject.createVertexArray();
    if (!vertexArray) {
        throw new Error('Could not create WebGL vertex array');
    }
    return vertexArray;
}
function getVertexArrayObject(extensions) {
    var vertexArrayObject = extensions.vertexArrayObject;
    if (vertexArrayObject === null) {
        throw new Error('VertexArrayObject not supported');
    }
    return vertexArrayObject;
}
function createVertexArray(extensions, program, attributeBuffers, elementsBuffer) {
    var id = getNextVertexArrayId();
    var vertexArray = getVertexArray(extensions);
    var vertexArrayObject = getVertexArrayObject(extensions);
    function update() {
        vertexArrayObject.bindVertexArray(vertexArray);
        if (elementsBuffer)
            elementsBuffer.bind();
        program.bindAttributes(attributeBuffers);
        vertexArrayObject.bindVertexArray(null);
    }
    update();
    var destroyed = false;
    return {
        id: id,
        bind: function () {
            vertexArrayObject.bindVertexArray(vertexArray);
        },
        update: update,
        reset: function () {
            vertexArray = getVertexArray(extensions);
            vertexArrayObject = getVertexArrayObject(extensions);
            update();
        },
        destroy: function () {
            if (destroyed)
                return;
            vertexArrayObject.deleteVertexArray(vertexArray);
            destroyed = true;
        }
    };
}
//# sourceMappingURL=vertex-array.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/resources.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










function defineValueHash(v) {
    return typeof v === 'boolean' ? (v ? 1 : 0) :
        typeof v === 'number' ? v : Object(util["m" /* hashString */])(v);
}
function wrapCached(resourceItem) {
    var wrapped = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, resourceItem.value), { destroy: function () {
            resourceItem.free();
        } });
    return wrapped;
}
function createResources(gl, state, stats, extensions) {
    var sets = {
        attribute: new Set(),
        elements: new Set(),
        framebuffer: new Set(),
        program: new Set(),
        renderbuffer: new Set(),
        shader: new Set(),
        texture: new Set(),
        vertexArray: new Set(),
    };
    function wrap(name, resource) {
        sets[name].add(resource);
        stats.resourceCounts[name] += 1;
        return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, resource), { destroy: function () {
                resource.destroy();
                sets[name].delete(resource);
                stats.resourceCounts[name] -= 1;
            } });
    }
    var shaderCache = createReferenceCache(function (props) { return JSON.stringify(props); }, function (props) { return wrap('shader', createShader(gl, props)); }, function (shader) { shader.destroy(); });
    function getShader(type, source) {
        return wrapCached(shaderCache.get({ type: type, source: source }));
    }
    var programCache = createReferenceCache(function (props) {
        var array = [props.shaderCode.id];
        Object.keys(props.defineValues).forEach(function (k) { return array.push(Object(util["m" /* hashString */])(k), defineValueHash(props.defineValues[k].ref.value)); });
        return Object(util["l" /* hashFnv32a */])(array).toString();
    }, function (props) { return wrap('program', createProgram(gl, state, extensions, getShader, props)); }, function (program) { program.destroy(); });
    return {
        attribute: function (array, itemSize, divisor, usageHint) {
            return wrap('attribute', Object(webgl_buffer["a" /* createAttributeBuffer */])(gl, extensions, array, itemSize, divisor, usageHint));
        },
        elements: function (array, usageHint) {
            return wrap('elements', Object(webgl_buffer["c" /* createElementsBuffer */])(gl, array, usageHint));
        },
        framebuffer: function () {
            return wrap('framebuffer', Object(webgl_framebuffer["b" /* createFramebuffer */])(gl));
        },
        program: function (defineValues, shaderCode, schema) {
            return wrapCached(programCache.get({ defineValues: defineValues, shaderCode: shaderCode, schema: schema }));
        },
        renderbuffer: function (format, attachment, width, height) {
            return wrap('renderbuffer', createRenderbuffer(gl, format, attachment, width, height));
        },
        shader: getShader,
        texture: function (kind, format, type, filter) {
            return wrap('texture', Object(texture["a" /* createTexture */])(gl, extensions, kind, format, type, filter));
        },
        vertexArray: function (program, attributeBuffers, elementsBuffer) {
            return wrap('vertexArray', createVertexArray(extensions, program, attributeBuffers, elementsBuffer));
        },
        reset: function () {
            sets.attribute.forEach(function (r) { return r.reset(); });
            sets.elements.forEach(function (r) { return r.reset(); });
            sets.framebuffer.forEach(function (r) { return r.reset(); });
            sets.renderbuffer.forEach(function (r) { return r.reset(); });
            sets.shader.forEach(function (r) { return r.reset(); });
            sets.program.forEach(function (r) { return r.reset(); });
            sets.vertexArray.forEach(function (r) { return r.reset(); });
            sets.texture.forEach(function (r) { return r.reset(); });
        },
        destroy: function () {
            sets.attribute.forEach(function (r) { return r.destroy(); });
            sets.elements.forEach(function (r) { return r.destroy(); });
            sets.framebuffer.forEach(function (r) { return r.destroy(); });
            sets.renderbuffer.forEach(function (r) { return r.destroy(); });
            sets.shader.forEach(function (r) { return r.destroy(); });
            sets.program.forEach(function (r) { return r.destroy(); });
            sets.vertexArray.forEach(function (r) { return r.destroy(); });
            sets.texture.forEach(function (r) { return r.destroy(); });
            shaderCache.clear();
            programCache.clear();
        }
    };
}
//# sourceMappingURL=resources.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-target.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var getNextRenderTargetId = Object(id_factory["a" /* idFactory */])();
function createRenderTarget(gl, resources, _width, _height) {
    var image = {
        array: new Uint8Array(_width * _height * 4),
        width: _width,
        height: _height
    };
    var framebuffer = resources.framebuffer();
    var targetTexture = resources.texture('image-uint8', 'rgba', 'ubyte', 'linear');
    // make a depth renderbuffer of the same size as the targetTexture
    var depthRenderbuffer = resources.renderbuffer('depth16', 'depth', _width, _height);
    function init() {
        targetTexture.load(image);
        targetTexture.attachFramebuffer(framebuffer, 'color0');
        depthRenderbuffer.attachFramebuffer(framebuffer);
    }
    init();
    var destroyed = false;
    function readBuffer(x, y, width, height, dst) {
        framebuffer.bind();
        gl.viewport(0, 0, _width, _height);
        readPixels(gl, x, y, width, height, dst);
    }
    function getBuffer() {
        readBuffer(0, 0, _width, _height, image.array);
        return image.array;
    }
    return {
        id: getNextRenderTargetId(),
        image: image,
        texture: targetTexture,
        framebuffer: framebuffer,
        getWidth: function () { return _width; },
        getHeight: function () { return _height; },
        bind: function () {
            framebuffer.bind();
            gl.viewport(0, 0, _width, _height);
        },
        setSize: function (width, height) {
            _width = width;
            _height = height;
            image.array = new Uint8Array(_width * _height * 4);
            image.width = _width;
            image.height = _height;
            targetTexture.load(image);
            depthRenderbuffer.setSize(_width, _height);
        },
        readBuffer: readBuffer,
        getBuffer: getBuffer,
        getPixelData: function () { return PixelData.flipY(PixelData.create(getBuffer(), _width, _height)); },
        reset: function () {
            init();
        },
        destroy: function () {
            if (destroyed)
                return;
            targetTexture.destroy();
            framebuffer.destroy();
            depthRenderbuffer.destroy();
            destroyed = true;
        }
    };
}
//# sourceMappingURL=render-target.js.map
// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/BehaviorSubject.js
var BehaviorSubject = __webpack_require__(279);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/webgl/context.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function getGLContext(canvas, contextAttributes) {
    function getContext(contextId) {
        try {
            return canvas.getContext(contextId, contextAttributes);
        }
        catch (e) {
            return null;
        }
    }
    return getContext('webgl2') || getContext('webgl') || getContext('experimental-webgl');
}
function getPixelRatio() {
    return (typeof window !== 'undefined') ? window.devicePixelRatio : 1;
}
function getErrorDescription(gl, error) {
    switch (error) {
        case gl.NO_ERROR: return 'no error';
        case gl.INVALID_ENUM: return 'invalid enum';
        case gl.INVALID_VALUE: return 'invalid value';
        case gl.INVALID_OPERATION: return 'invalid operation';
        case gl.INVALID_FRAMEBUFFER_OPERATION: return 'invalid framebuffer operation';
        case gl.OUT_OF_MEMORY: return 'out of memory';
        case gl.CONTEXT_LOST_WEBGL: return 'context lost';
    }
    return 'unknown error';
}
function checkError(gl) {
    var error = gl.getError();
    if (error !== gl.NO_ERROR) {
        throw new Error("WebGL error: '" + getErrorDescription(gl, error) + "'");
    }
}
function unbindResources(gl) {
    // bind null to all texture units
    var maxTextureImageUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
    for (var i = 0; i < maxTextureImageUnits; ++i) {
        gl.activeTexture(gl.TEXTURE0 + i);
        gl.bindTexture(gl.TEXTURE_2D, null);
        gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
        if (Object(compat["m" /* isWebGL2 */])(gl)) {
            gl.bindTexture(gl.TEXTURE_2D_ARRAY, null);
            gl.bindTexture(gl.TEXTURE_3D, null);
        }
    }
    // assign the smallest possible buffer to all attributes
    var buf = gl.createBuffer();
    gl.bindBuffer(gl.ARRAY_BUFFER, buf);
    var maxVertexAttribs = gl.getParameter(gl.MAX_VERTEX_ATTRIBS);
    for (var i = 0; i < maxVertexAttribs; ++i) {
        gl.vertexAttribPointer(i, 1, gl.FLOAT, false, 0, 0);
    }
    // bind null to all buffers
    gl.bindBuffer(gl.ARRAY_BUFFER, null);
    gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
    gl.bindRenderbuffer(gl.RENDERBUFFER, null);
    unbindFramebuffer(gl);
}
function unbindFramebuffer(gl) {
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
var tmpPixel = new Uint8Array(1 * 4);
function checkSync(gl, sync, resolve) {
    if (gl.getSyncParameter(sync, gl.SYNC_STATUS) === gl.SIGNALED) {
        gl.deleteSync(sync);
        resolve();
    }
    else {
        mol_task["a" /* Scheduler */].setImmediate(checkSync, gl, sync, resolve);
    }
}
function fence(gl, resolve) {
    var sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
    if (!sync) {
        console.warn('Could not create a WebGLSync object');
        gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, tmpPixel);
        resolve();
    }
    else {
        mol_task["a" /* Scheduler */].setImmediate(checkSync, gl, sync, resolve);
    }
}
var SentWebglSyncObjectNotSupportedInWebglMessage = false;
function waitForGpuCommandsComplete(gl) {
    return new Promise(function (resolve) {
        if (Object(compat["m" /* isWebGL2 */])(gl)) {
            // TODO seems quite slow
            fence(gl, resolve);
        }
        else {
            if (!SentWebglSyncObjectNotSupportedInWebglMessage) {
                console.info('Sync object not supported in WebGL');
                SentWebglSyncObjectNotSupportedInWebglMessage = true;
            }
            waitForGpuCommandsCompleteSync(gl);
            resolve();
        }
    });
}
function waitForGpuCommandsCompleteSync(gl) {
    gl.bindFramebuffer(gl.FRAMEBUFFER, null);
    gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, tmpPixel);
}
function readPixels(gl, x, y, width, height, buffer) {
    if (debug["a" /* isDebugMode */])
        Object(webgl_framebuffer["a" /* checkFramebufferStatus */])(gl);
    if (buffer instanceof Uint8Array) {
        gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, buffer);
    }
    else if (buffer instanceof Float32Array) {
        gl.readPixels(x, y, width, height, gl.RGBA, gl.FLOAT, buffer);
    }
    else {
        throw new Error('unsupported readPixels buffer type');
    }
    if (debug["a" /* isDebugMode */])
        checkError(gl);
}
function getDrawingBufferPixelData(gl) {
    var w = gl.drawingBufferWidth;
    var h = gl.drawingBufferHeight;
    var buffer = new Uint8Array(w * h * 4);
    unbindFramebuffer(gl);
    gl.viewport(0, 0, w, h);
    readPixels(gl, 0, 0, w, h, buffer);
    return PixelData.flipY(PixelData.create(buffer, w, h));
}
//
function createStats() {
    return {
        resourceCounts: {
            attribute: 0,
            elements: 0,
            framebuffer: 0,
            program: 0,
            renderbuffer: 0,
            shader: 0,
            texture: 0,
            vertexArray: 0,
        },
        drawCount: 0,
        instanceCount: 0,
        instancedDrawCount: 0,
    };
}
function createContext(gl) {
    var _this = this;
    var extensions = createExtensions(gl);
    var state = createState(gl);
    var stats = createStats();
    var resources = createResources(gl, state, stats, extensions);
    var parameters = {
        maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE),
        maxRenderbufferSize: gl.getParameter(gl.MAX_RENDERBUFFER_SIZE),
        maxDrawBuffers: Object(compat["m" /* isWebGL2 */])(gl) ? gl.getParameter(gl.MAX_DRAW_BUFFERS) : 0,
        maxVertexTextureImageUnits: gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS),
    };
    if (parameters.maxVertexTextureImageUnits < 8) {
        throw new Error('Need "MAX_VERTEX_TEXTURE_IMAGE_UNITS" >= 8');
    }
    var isContextLost = false;
    var contextRestored = new BehaviorSubject["a" /* BehaviorSubject */](0);
    var readPixelsAsync;
    if (Object(compat["m" /* isWebGL2 */])(gl)) {
        var pbo_1 = gl.createBuffer();
        var _buffer_1 = void 0;
        var _resolve_1 = void 0;
        var _reading_1 = false;
        var bindPBO_1 = function () {
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, pbo_1);
            gl.getBufferSubData(gl.PIXEL_PACK_BUFFER, 0, _buffer_1);
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
            _reading_1 = false;
            _resolve_1();
            _resolve_1 = void 0;
            _buffer_1 = void 0;
        };
        readPixelsAsync = function (x, y, width, height, buffer) { return new Promise(function (resolve, reject) {
            if (_reading_1) {
                reject('Can not call multiple readPixelsAsync at the same time');
                return;
            }
            _reading_1 = true;
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, pbo_1);
            gl.bufferData(gl.PIXEL_PACK_BUFFER, width * height * 4, gl.STREAM_READ);
            gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, 0);
            gl.bindBuffer(gl.PIXEL_PACK_BUFFER, null);
            // need to unbind/bind PBO before/after async awaiting the fence
            _resolve_1 = resolve;
            _buffer_1 = buffer;
            fence(gl, bindPBO_1);
        }); };
    }
    else {
        readPixelsAsync = function (x, y, width, height, buffer) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                readPixels(gl, x, y, width, height, buffer);
                return [2 /*return*/];
            });
        }); };
    }
    var renderTargets = new Set();
    return {
        gl: gl,
        isWebGL2: Object(compat["m" /* isWebGL2 */])(gl),
        get pixelRatio() {
            // this can change during the lifetime of a rendering context, so need to re-obtain on access
            return getPixelRatio();
        },
        extensions: extensions,
        state: state,
        stats: stats,
        resources: resources,
        get maxTextureSize() { return parameters.maxTextureSize; },
        get maxRenderbufferSize() { return parameters.maxRenderbufferSize; },
        get maxDrawBuffers() { return parameters.maxDrawBuffers; },
        get isContextLost() {
            return isContextLost || gl.isContextLost();
        },
        contextRestored: contextRestored,
        setContextLost: function () {
            isContextLost = true;
        },
        handleContextRestored: function () {
            Object.assign(extensions, createExtensions(gl));
            state.reset();
            state.currentMaterialId = -1;
            state.currentProgramId = -1;
            state.currentRenderItemId = -1;
            resources.reset();
            renderTargets.forEach(function (rt) { return rt.reset(); });
            isContextLost = false;
            contextRestored.next(Object(now["b" /* now */])());
        },
        createRenderTarget: function (width, height) {
            var renderTarget = createRenderTarget(gl, resources, width, height);
            renderTargets.add(renderTarget);
            return Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderTarget), { destroy: function () {
                    renderTarget.destroy();
                    renderTargets.delete(renderTarget);
                } });
        },
        unbindFramebuffer: function () { return unbindFramebuffer(gl); },
        readPixels: function (x, y, width, height, buffer) {
            readPixels(gl, x, y, width, height, buffer);
        },
        readPixelsAsync: readPixelsAsync,
        waitForGpuCommandsComplete: function () { return waitForGpuCommandsComplete(gl); },
        waitForGpuCommandsCompleteSync: function () { return waitForGpuCommandsCompleteSync(gl); },
        getDrawingBufferPixelData: function () { return getDrawingBufferPixelData(gl); },
        destroy: function () {
            resources.destroy();
            unbindResources(gl);
        }
    };
}
//# sourceMappingURL=context.js.map

/***/ }),
/* 334 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ InteractionsRepresentationProvider; });

// UNUSED EXPORTS: InteractionsParams, getInteractionParams, InteractionRepresentation

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var representation = __webpack_require__(40);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation.js
var structure_representation = __webpack_require__(54);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions.js
var computed_interactions = __webpack_require__(108);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/link.js
var util_link = __webpack_require__(63);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/units-visual.js
var units_visual = __webpack_require__(48);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/location-iterator.js
var location_iterator = __webpack_require__(86);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/interactions/interactions.js + 10 modules
var interactions_interactions = __webpack_require__(200);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/representations/interactions-intra-unit-cylinder.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function createIntraUnitInteractionsCylinderMesh(ctx, unit, structure, theme, props, mesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var location, interactions, features, contacts, x, y, z, members, offsets, edgeCount, a, b, flag, sizeFactor, builderProps;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            if (!mol_model_structure["Unit"].isAtomic(unit))
                return [2 /*return*/, mesh_mesh["a" /* Mesh */].createEmpty(mesh)];
            location = mol_model_structure["StructureElement"].Location.create(structure, unit);
            interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
            features = interactions.unitsFeatures.get(unit.id);
            contacts = interactions.unitsContacts.get(unit.id);
            x = features.x, y = features.y, z = features.z, members = features.members, offsets = features.offsets;
            edgeCount = contacts.edgeCount, a = contacts.a, b = contacts.b, flag = contacts.edgeProps.flag;
            sizeFactor = props.sizeFactor;
            if (!edgeCount)
                return [2 /*return*/, mesh_mesh["a" /* Mesh */].createEmpty(mesh)];
            builderProps = {
                linkCount: edgeCount * 2,
                position: function (posA, posB, edgeIndex) {
                    linear_algebra["Vec3"].set(posA, x[a[edgeIndex]], y[a[edgeIndex]], z[a[edgeIndex]]);
                    linear_algebra["Vec3"].set(posB, x[b[edgeIndex]], y[b[edgeIndex]], z[b[edgeIndex]]);
                },
                style: function (edgeIndex) { return util_link["c" /* LinkStyle */].Dashed; },
                radius: function (edgeIndex) {
                    location.element = unit.elements[members[offsets[a[edgeIndex]]]];
                    var sizeA = theme.size.size(location);
                    location.element = unit.elements[members[offsets[b[edgeIndex]]]];
                    var sizeB = theme.size.size(location);
                    return Math.min(sizeA, sizeB) * sizeFactor;
                },
                ignore: function (edgeIndex) { return flag[edgeIndex] === 1 /* Filtered */; }
            };
            return [2 /*return*/, Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh)];
        });
    });
}
var InteractionsIntraUnitParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), util_link["a" /* LinkCylinderParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.3, { min: 0, max: 10, step: 0.01 }) });
function InteractionsIntraUnitVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(InteractionsIntraUnitParams),
        createGeometry: createIntraUnitInteractionsCylinderMesh,
        createLocationIterator: createInteractionsIterator,
        getLoci: getInteractionLoci,
        eachLocation: eachInteraction,
        setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments);
            var interactionsHash = computed_interactions["a" /* InteractionsProvider */].get(newStructureGroup.structure).version;
            if (state.info.interactionsHash !== interactionsHash) {
                state.createGeometry = true;
                state.updateTransform = true;
                state.info.interactionsHash = interactionsHash;
            }
        }
    }, materialId);
}
function getInteractionLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = structure.unitMap.get(group.units[instanceId].id);
        var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
        var _a = interactions.unitsContacts.get(unit.id), a = _a.a, b = _a.b;
        return interactions_interactions["a" /* Interactions */].Loci(structure, interactions, [
            { unitA: unit, indexA: a[groupId], unitB: unit, indexB: b[groupId] },
            { unitA: unit, indexA: b[groupId], unitB: unit, indexB: a[groupId] },
        ]);
    }
    return mol_model_loci["EmptyLoci"];
}
function eachInteraction(loci, structureGroup, apply) {
    var changed = false;
    if (interactions_interactions["a" /* Interactions */].isLoci(loci)) {
        var structure = structureGroup.structure, group = structureGroup.group;
        if (!mol_model_structure["Structure"].areEquivalent(loci.data.structure, structure))
            return false;
        var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
        if (loci.data.interactions !== interactions)
            return false;
        var unit = group.units[0];
        var contacts = interactions.unitsContacts.get(unit.id);
        var groupCount = contacts.edgeCount * 2;
        for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
            var e = _a[_i];
            var unitIdx = group.unitIndexMap.get(e.unitA.id);
            if (unitIdx !== undefined) {
                var idx = contacts.getDirectedEdgeIndex(e.indexA, e.indexB);
                if (idx !== -1) {
                    if (apply(mol_data_int["Interval"].ofSingleton(unitIdx * groupCount + idx)))
                        changed = true;
                }
            }
        }
    }
    return changed;
}
function createInteractionsIterator(structureGroup) {
    var structure = structureGroup.structure, group = structureGroup.group;
    var unit = group.units[0];
    var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
    var contacts = interactions.unitsContacts.get(unit.id);
    var groupCount = contacts.edgeCount * 2;
    var instanceCount = group.units.length;
    var location = interactions_interactions["a" /* Interactions */].Location(interactions, structure);
    var element = location.element;
    var getLocation = function (groupIndex, instanceIndex) {
        var instanceUnit = group.units[instanceIndex];
        element.unitA = instanceUnit;
        element.indexA = contacts.a[groupIndex];
        element.unitB = instanceUnit;
        element.indexB = contacts.b[groupIndex];
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
}
//# sourceMappingURL=interactions-intra-unit-cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/complex-visual.js
var complex_visual = __webpack_require__(110);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/representations/interactions-inter-unit-cylinder.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var tmpLoc = mol_model_structure["StructureElement"].Location.create(void 0);
function createInterUnitInteractionCylinderMesh(ctx, structure, theme, props, mesh) {
    if (!structure.hasAtomic)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
    var contacts = interactions.contacts, unitsFeatures = interactions.unitsFeatures;
    var edgeCount = contacts.edgeCount, edges = contacts.edges;
    var sizeFactor = props.sizeFactor;
    if (!edgeCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var builderProps = {
        linkCount: edgeCount,
        position: function (posA, posB, edgeIndex) {
            var _a = edges[edgeIndex], unitA = _a.unitA, indexA = _a.indexA, unitB = _a.unitB, indexB = _a.indexB;
            var fA = unitsFeatures.get(unitA.id);
            var fB = unitsFeatures.get(unitB.id);
            linear_algebra["Vec3"].set(posA, fA.x[indexA], fA.y[indexA], fA.z[indexA]);
            linear_algebra["Vec3"].transformMat4(posA, posA, unitA.conformation.operator.matrix);
            linear_algebra["Vec3"].set(posB, fB.x[indexB], fB.y[indexB], fB.z[indexB]);
            linear_algebra["Vec3"].transformMat4(posB, posB, unitB.conformation.operator.matrix);
        },
        style: function (edgeIndex) { return util_link["c" /* LinkStyle */].Dashed; },
        radius: function (edgeIndex) {
            var b = edges[edgeIndex];
            var fA = unitsFeatures.get(b.unitA.id);
            tmpLoc.structure = structure;
            tmpLoc.unit = b.unitA;
            tmpLoc.element = b.unitA.elements[fA.members[fA.offsets[b.indexA]]];
            var sizeA = theme.size.size(tmpLoc);
            var fB = unitsFeatures.get(b.unitB.id);
            tmpLoc.unit = b.unitB;
            tmpLoc.element = b.unitB.elements[fB.members[fB.offsets[b.indexB]]];
            var sizeB = theme.size.size(tmpLoc);
            return Math.min(sizeA, sizeB) * sizeFactor;
        },
        ignore: function (edgeIndex) { return edges[edgeIndex].props.flag === 1 /* Filtered */; }
    };
    return Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
}
var InteractionsInterUnitParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["c" /* ComplexMeshParams */]), util_link["a" /* LinkCylinderParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.3, { min: 0, max: 10, step: 0.01 }) });
function InteractionsInterUnitVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(InteractionsInterUnitParams),
        createGeometry: createInterUnitInteractionCylinderMesh,
        createLocationIterator: interactions_inter_unit_cylinder_createInteractionsIterator,
        getLoci: interactions_inter_unit_cylinder_getInteractionLoci,
        eachLocation: interactions_inter_unit_cylinder_eachInteraction,
        setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructure, currentStructure) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments);
            var interactionsHash = computed_interactions["a" /* InteractionsProvider */].get(newStructure).version;
            if (state.info.interactionsHash !== interactionsHash) {
                state.createGeometry = true;
                state.updateTransform = true;
                state.info.interactionsHash = interactionsHash;
            }
        }
    }, materialId);
}
function interactions_inter_unit_cylinder_getInteractionLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
        var c = interactions.contacts.edges[groupId];
        return interactions_interactions["a" /* Interactions */].Loci(structure, interactions, [
            { unitA: c.unitA, indexA: c.indexA, unitB: c.unitB, indexB: c.indexB },
            { unitA: c.unitB, indexA: c.indexB, unitB: c.unitA, indexB: c.indexA },
        ]);
    }
    return mol_model_loci["EmptyLoci"];
}
function interactions_inter_unit_cylinder_eachInteraction(loci, structure, apply) {
    var changed = false;
    if (interactions_interactions["a" /* Interactions */].isLoci(loci)) {
        if (!mol_model_structure["Structure"].areEquivalent(loci.data.structure, structure))
            return false;
        var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
        if (loci.data.interactions !== interactions)
            return false;
        var contacts = interactions.contacts;
        for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
            var c = _a[_i];
            var idx = contacts.getEdgeIndex(c.indexA, c.unitA, c.indexB, c.unitB);
            if (idx !== -1) {
                if (apply(mol_data_int["Interval"].ofSingleton(idx)))
                    changed = true;
            }
        }
    }
    return changed;
}
function interactions_inter_unit_cylinder_createInteractionsIterator(structure) {
    var interactions = computed_interactions["a" /* InteractionsProvider */].get(structure).value;
    var contacts = interactions.contacts;
    var groupCount = contacts.edgeCount;
    var instanceCount = 1;
    var location = interactions_interactions["a" /* Interactions */].Location(interactions, structure);
    var element = location.element;
    var getLocation = function (groupIndex) {
        var c = contacts.edges[groupIndex];
        element.unitA = c.unitA;
        element.indexA = c.indexA;
        element.unitB = c.unitB;
        element.indexB = c.indexB;
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
}
//# sourceMappingURL=interactions-inter-unit-cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/params.js
var params = __webpack_require__(94);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/computed/representations/interactions.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var InteractionsVisuals = {
    'intra-unit': function (ctx, getParams) { return Object(structure_representation["d" /* UnitsRepresentation */])('Intra-unit interactions cylinder', ctx, getParams, InteractionsIntraUnitVisual); },
    'inter-unit': function (ctx, getParams) { return Object(structure_representation["a" /* ComplexRepresentation */])('Inter-unit interactions cylinder', ctx, getParams, InteractionsInterUnitVisual); },
};
var InteractionsParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, InteractionsIntraUnitParams), InteractionsInterUnitParams), { unitKinds: Object(params["i" /* getUnitKindsParam */])(['atomic']), sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0.01, max: 1, step: 0.01 }), visuals: param_definition["ParamDefinition"].MultiSelect(['intra-unit', 'inter-unit'], param_definition["ParamDefinition"].objectToOptions(InteractionsVisuals)) });
function getInteractionParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(InteractionsParams);
}
function InteractionRepresentation(ctx, getParams) {
    return representation["a" /* Representation */].createMulti('Interactions', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], InteractionsVisuals);
}
var InteractionsRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'interactions',
    label: 'Non-covalent Interactions',
    description: 'Displays non-covalent interactions as dashed cylinders.',
    factory: InteractionRepresentation,
    getParams: getInteractionParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(InteractionsParams),
    defaultColorTheme: { name: 'interaction-type' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; },
    ensureCustomProperties: {
        attach: function (ctx, structure) { return computed_interactions["a" /* InteractionsProvider */].attach(ctx, structure, void 0, true); },
        detach: function (data) { return computed_interactions["a" /* InteractionsProvider */].ref(data, false); }
    }
});
//# sourceMappingURL=interactions.js.map

/***/ }),
/* 335 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* reexport */ sequence_Sequence; });

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence/constants.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
// from NGL
var ProteinOneLetterCodes = {
    'HIS': 'H',
    'ARG': 'R',
    'LYS': 'K',
    'ILE': 'I',
    'PHE': 'F',
    'LEU': 'L',
    'TRP': 'W',
    'ALA': 'A',
    'MET': 'M',
    'PRO': 'P',
    'CYS': 'C',
    'ASN': 'N',
    'VAL': 'V',
    'GLY': 'G',
    'SER': 'S',
    'GLN': 'Q',
    'TYR': 'Y',
    'ASP': 'D',
    'GLU': 'E',
    'THR': 'T',
    'SEC': 'U',
    'PYL': 'O',
};
var DnaOneLetterCodes = {
    'DA': 'A',
    'DC': 'C',
    'DG': 'G',
    'DT': 'T',
    'DU': 'U'
};
var RnaOneLetterCodes = {
    'A': 'A',
    'C': 'C',
    'G': 'G',
    'T': 'T',
    'U': 'U'
};
function getProteinOneLetterCode(residueName) {
    var code = ProteinOneLetterCodes[residueName];
    return code || 'X';
}
function getRnaOneLetterCode(residueName) {
    var code = RnaOneLetterCodes[residueName];
    return code || 'X';
}
function getDnaOneLetterCode(residueName) {
    var code = DnaOneLetterCodes[residueName];
    return code || 'X';
}
//# sourceMappingURL=constants.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var db = __webpack_require__(7);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence/sequence.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var sequence_Sequence;
(function (Sequence) {
    function getSequenceString(seq) {
        var array = seq.code.toArray();
        return (array instanceof Array ? array : Array.from(array)).join('');
    }
    Sequence.getSequenceString = getSequenceString;
    function determineKind(names) {
        for (var i = 0, _i = Math.min(names.rowCount, 10); i < _i; i++) {
            var name_1 = names.value(i) || '';
            if (getProteinOneLetterCode(name_1) !== 'X')
                return "protein" /* Protein */;
            if (getRnaOneLetterCode(name_1) !== 'X')
                return "RNA" /* RNA */;
            if (getDnaOneLetterCode(name_1) !== 'X')
                return "DNA" /* DNA */;
        }
        return "generic" /* Generic */;
    }
    function codeProvider(kind, map) {
        var code;
        switch (kind) {
            case "protein" /* Protein */:
                code = getProteinOneLetterCode;
                break;
            case "DNA" /* DNA */:
                code = getDnaOneLetterCode;
                break;
            case "RNA" /* RNA */:
                code = getRnaOneLetterCode;
                break;
            case "generic" /* Generic */:
                code = function () { return 'X'; };
                break;
            default: throw new Error("unknown kind '" + kind + "'");
        }
        if (map && map.size > 0) {
            return function (name) {
                var ret = code(name);
                if (ret !== 'X' || !map.has(name))
                    return ret;
                return code(map.get(name));
            };
        }
        return code;
    }
    function ofResidueNames(compId, seqId) {
        if (seqId.rowCount === 0)
            throw new Error('cannot be empty');
        var kind = determineKind(compId);
        return new ResidueNamesImpl(kind, compId, seqId);
    }
    Sequence.ofResidueNames = ofResidueNames;
    var ResidueNamesImpl = /** @class */ (function () {
        function ResidueNamesImpl(kind, compId, seqId) {
            this.kind = kind;
            this.microHet = new Map();
            var codeFromName = codeProvider(kind);
            var codes = [];
            var compIds = [];
            var seqIds = [];
            var microHet = new Map();
            var idx = 0;
            var indexMap = new Map();
            for (var i = 0, il = seqId.rowCount; i < il; ++i) {
                var seq_id = seqId.value(i);
                if (!indexMap.has(seq_id)) {
                    indexMap.set(seq_id, idx);
                    var comp_id = compId.value(i);
                    compIds[idx] = comp_id;
                    seqIds[idx] = seq_id;
                    codes[idx] = codeFromName(comp_id);
                    idx += 1;
                }
                else {
                    // micro-heterogeneity
                    if (!microHet.has(seq_id)) {
                        microHet.set(seq_id, [compIds[indexMap.get(seq_id)], compId.value(i)]);
                    }
                    else {
                        microHet.get(seq_id).push(compId.value(i));
                    }
                }
            }
            var labels = [];
            for (var i = 0, il = idx; i < il; ++i) {
                var mh = microHet.get(seqIds[i]);
                if (mh) {
                    var l = mh.map(function (id) {
                        var c = codeFromName(id);
                        return c === 'X' ? id : c;
                    });
                    labels[i] = "(" + l.join('|') + ")";
                }
                else {
                    labels[i] = codes[i] === 'X' ? compIds[idx] : codes[i];
                }
            }
            this.length = idx;
            this.code = db["Column"].ofStringArray(codes);
            this.compId = db["Column"].ofStringArray(compIds);
            this.seqId = db["Column"].ofIntArray(seqIds);
            this.label = db["Column"].ofStringArray(labels);
            this.microHet = microHet;
            this.indexMap = indexMap;
        }
        ResidueNamesImpl.prototype.index = function (seqId) {
            return this.indexMap.get(seqId);
        };
        return ResidueNamesImpl;
    }());
    function ofSequenceRanges(seqIdBegin, seqIdEnd) {
        var kind = "generic" /* Generic */;
        return new SequenceRangesImpl(kind, seqIdBegin, seqIdEnd);
    }
    Sequence.ofSequenceRanges = ofSequenceRanges;
    var SequenceRangesImpl = /** @class */ (function () {
        function SequenceRangesImpl(kind, seqIdStart, seqIdEnd) {
            this.kind = kind;
            this.seqIdStart = seqIdStart;
            this.seqIdEnd = seqIdEnd;
            this.microHet = new Map();
            var maxSeqId = 0, minSeqId = Number.MAX_SAFE_INTEGER;
            for (var i = 0, _i = this.seqIdStart.rowCount; i < _i; i++) {
                var idStart = this.seqIdStart.value(i);
                var idEnd = this.seqIdEnd.value(i);
                if (idStart < minSeqId)
                    minSeqId = idStart;
                if (maxSeqId < idEnd)
                    maxSeqId = idEnd;
            }
            var count = maxSeqId - minSeqId + 1;
            this.code = db["Column"].ofConst('X', count, db["Column"].Schema.str);
            this.label = db["Column"].ofConst('', count, db["Column"].Schema.str);
            this.seqId = db["Column"].ofLambda({
                value: function (row) { return row + minSeqId + 1; },
                rowCount: count,
                schema: db["Column"].Schema.int
            });
            this.compId = db["Column"].ofConst('', count, db["Column"].Schema.str);
            this.length = count;
            this.minSeqId = minSeqId;
        }
        SequenceRangesImpl.prototype.index = function (seqId) {
            return seqId - this.minSeqId;
        };
        return SequenceRangesImpl;
    }());
})(sequence_Sequence || (sequence_Sequence = {}));

//# sourceMappingURL=sequence.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/sequence.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

//# sourceMappingURL=sequence.js.map

/***/ }),
/* 336 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return groupBy; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return GroupedObservable; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(70);
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(44);
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(60);
/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */





function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) {
    return function (source) {
        return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));
    };
}
var GroupByOperator = /*@__PURE__*/ (function () {
    function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) {
        this.keySelector = keySelector;
        this.elementSelector = elementSelector;
        this.durationSelector = durationSelector;
        this.subjectSelector = subjectSelector;
    }
    GroupByOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector));
    };
    return GroupByOperator;
}());
var GroupBySubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](GroupBySubscriber, _super);
    function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) {
        var _this = _super.call(this, destination) || this;
        _this.keySelector = keySelector;
        _this.elementSelector = elementSelector;
        _this.durationSelector = durationSelector;
        _this.subjectSelector = subjectSelector;
        _this.groups = null;
        _this.attemptedToUnsubscribe = false;
        _this.count = 0;
        return _this;
    }
    GroupBySubscriber.prototype._next = function (value) {
        var key;
        try {
            key = this.keySelector(value);
        }
        catch (err) {
            this.error(err);
            return;
        }
        this._group(value, key);
    };
    GroupBySubscriber.prototype._group = function (value, key) {
        var groups = this.groups;
        if (!groups) {
            groups = this.groups = new Map();
        }
        var group = groups.get(key);
        var element;
        if (this.elementSelector) {
            try {
                element = this.elementSelector(value);
            }
            catch (err) {
                this.error(err);
            }
        }
        else {
            element = value;
        }
        if (!group) {
            group = (this.subjectSelector ? this.subjectSelector() : new _Subject__WEBPACK_IMPORTED_MODULE_4__[/* Subject */ "a"]());
            groups.set(key, group);
            var groupedObservable = new GroupedObservable(key, group, this);
            this.destination.next(groupedObservable);
            if (this.durationSelector) {
                var duration = void 0;
                try {
                    duration = this.durationSelector(new GroupedObservable(key, group));
                }
                catch (err) {
                    this.error(err);
                    return;
                }
                this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));
            }
        }
        if (!group.closed) {
            group.next(element);
        }
    };
    GroupBySubscriber.prototype._error = function (err) {
        var groups = this.groups;
        if (groups) {
            groups.forEach(function (group, key) {
                group.error(err);
            });
            groups.clear();
        }
        this.destination.error(err);
    };
    GroupBySubscriber.prototype._complete = function () {
        var groups = this.groups;
        if (groups) {
            groups.forEach(function (group, key) {
                group.complete();
            });
            groups.clear();
        }
        this.destination.complete();
    };
    GroupBySubscriber.prototype.removeGroup = function (key) {
        this.groups.delete(key);
    };
    GroupBySubscriber.prototype.unsubscribe = function () {
        if (!this.closed) {
            this.attemptedToUnsubscribe = true;
            if (this.count === 0) {
                _super.prototype.unsubscribe.call(this);
            }
        }
    };
    return GroupBySubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
var GroupDurationSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](GroupDurationSubscriber, _super);
    function GroupDurationSubscriber(key, group, parent) {
        var _this = _super.call(this, group) || this;
        _this.key = key;
        _this.group = group;
        _this.parent = parent;
        return _this;
    }
    GroupDurationSubscriber.prototype._next = function (value) {
        this.complete();
    };
    GroupDurationSubscriber.prototype._unsubscribe = function () {
        var _a = this, parent = _a.parent, key = _a.key;
        this.key = this.parent = null;
        if (parent) {
            parent.removeGroup(key);
        }
    };
    return GroupDurationSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
var GroupedObservable = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](GroupedObservable, _super);
    function GroupedObservable(key, groupSubject, refCountSubscription) {
        var _this = _super.call(this) || this;
        _this.key = key;
        _this.groupSubject = groupSubject;
        _this.refCountSubscription = refCountSubscription;
        return _this;
    }
    GroupedObservable.prototype._subscribe = function (subscriber) {
        var subscription = new _Subscription__WEBPACK_IMPORTED_MODULE_2__[/* Subscription */ "a"]();
        var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject;
        if (refCountSubscription && !refCountSubscription.closed) {
            subscription.add(new InnerRefCountSubscription(refCountSubscription));
        }
        subscription.add(groupSubject.subscribe(subscriber));
        return subscription;
    };
    return GroupedObservable;
}(_Observable__WEBPACK_IMPORTED_MODULE_3__[/* Observable */ "a"]));

var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](InnerRefCountSubscription, _super);
    function InnerRefCountSubscription(parent) {
        var _this = _super.call(this) || this;
        _this.parent = parent;
        parent.count++;
        return _this;
    }
    InnerRefCountSubscription.prototype.unsubscribe = function () {
        var parent = this.parent;
        if (!parent.closed && !this.closed) {
            _super.prototype.unsubscribe.call(this);
            parent.count -= 1;
            if (parent.count === 0 && parent.attemptedToUnsubscribe) {
                parent.unsubscribe();
            }
        }
    };
    return InnerRefCountSubscription;
}(_Subscription__WEBPACK_IMPORTED_MODULE_2__[/* Subscription */ "a"]));
//# sourceMappingURL=groupBy.js.map


/***/ }),
/* 337 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export DefaultColorScaleProps */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ColorScale; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(43);
/* harmony import */ var _lists__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(88);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/* harmony import */ var _legend__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(141);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var DefaultColorScaleProps = {
    domain: [0, 1],
    reverse: false,
    listOrName: 'red-yellow-blue',
    minLabel: '',
    maxLabel: '',
};
var ColorScale;
(function (ColorScale) {
    function create(props) {
        var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, DefaultColorScaleProps), props), domain = _a.domain, reverse = _a.reverse, listOrName = _a.listOrName;
        var list = typeof listOrName === 'string' ? Object(_lists__WEBPACK_IMPORTED_MODULE_2__["getColorListFromName"])(listOrName).list : listOrName;
        var colors = reverse ? list.slice().reverse() : list;
        var count1 = colors.length - 1;
        var diff = 0, min = 0, max = 0;
        function setDomain(_min, _max) {
            min = _min;
            max = _max;
            diff = (max - min) || 1;
        }
        setDomain(domain[0], domain[1]);
        var minLabel = Object(_mol_util__WEBPACK_IMPORTED_MODULE_3__[/* defaults */ "i"])(props.minLabel, min.toString());
        var maxLabel = Object(_mol_util__WEBPACK_IMPORTED_MODULE_3__[/* defaults */ "i"])(props.maxLabel, max.toString());
        function color(value) {
            var t = Math.min(colors.length - 1, Math.max(0, ((value - min) / diff) * count1));
            var tf = Math.floor(t);
            var c1 = colors[tf];
            var c2 = colors[Math.ceil(t)];
            return _color__WEBPACK_IMPORTED_MODULE_1__["Color"].interpolate(c1, c2, t - tf);
        }
        return {
            color: color,
            colorToArray: function (value, array, offset) {
                _color__WEBPACK_IMPORTED_MODULE_1__["Color"].toArray(color(value), array, offset);
            },
            normalizedColorToArray: function (value, array, offset) {
                _color__WEBPACK_IMPORTED_MODULE_1__["Color"].toArrayNormalized(color(value), array, offset);
            },
            setDomain: setDomain,
            get legend() { return Object(_legend__WEBPACK_IMPORTED_MODULE_4__[/* ScaleLegend */ "a"])(minLabel, maxLabel, colors); }
        };
    }
    ColorScale.create = create;
})(ColorScale || (ColorScale = {}));
//# sourceMappingURL=scale.js.map

/***/ }),
/* 338 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return arrayFind; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return iterableToArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return createRangeArray; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return arrayPickIndices; });
/* unused harmony export arrayGetCtor */
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * from https://github.com/dsehnal/CIFTools.js
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function arrayFind(array, f) {
    for (var i = 0, _i = array.length; i < _i; i++) {
        if (f(array[i]))
            return array[i];
    }
    return void 0;
}
function iterableToArray(it) {
    if (Array.from)
        return Array.from(it);
    var ret = [];
    while (true) {
        var _a = it.next(), done = _a.done, value = _a.value;
        if (done)
            break;
        ret[ret.length] = value;
    }
    return ret;
}
/** Fills the array so that array[0] = start and array[array.length - 1] = end */
function createRangeArray(start, end, ctor) {
    var len = end - start + 1;
    var array = ctor ? new ctor(len) : new Int32Array(len);
    for (var i = 0; i < len; i++) {
        array[i] = i + start;
    }
    return array;
}
function arrayPickIndices(array, indices) {
    var ret = new (arrayGetCtor(array))(indices.length);
    for (var i = 0, _i = indices.length; i < _i; i++) {
        ret[i] = array[indices[i]];
    }
    return ret;
}
function arrayGetCtor(data) {
    var ret = data.constructor;
    if (!ret)
        throw new Error('data does not define a constructor and it should');
    return ret;
}
//# sourceMappingURL=array.js.map

/***/ }),
/* 339 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, clearImmediate) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Scheduler; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function createImmediateActions() {
    var global = (function () {
        var _window = typeof window !== 'undefined' && window;
        var _self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope && self;
        var _global = typeof global !== 'undefined' && global;
        return _window || _global || _self;
    })();
    var tasksByHandle = {};
    var doc = typeof document !== 'undefined' ? document : void 0;
    var nextHandle = 1; // Spec says greater than zero
    var registerImmediate;
    function setImmediate(callback) {
        var args = [];
        for (var _i = 1; _i < arguments.length; _i++) {
            args[_i - 1] = arguments[_i];
        }
        // Callback can either be a function or a string
        if (typeof callback !== 'function') {
            callback = new Function('' + callback);
        }
        // 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) {
        var task = tasksByHandle[handle];
        clearImmediate(handle);
        run(task);
    }
    function installNextTickImplementation() {
        registerImmediate = function (handle) {
            process.nextTick(function () { runIfPresent(handle); });
        };
    }
    function canUsePostMessage() {
        if (global && global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous_1 = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function () {
                postMessageIsAsynchronous_1 = false;
            };
            global.postMessage('', '*');
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous_1;
        }
    }
    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 (window.addEventListener) {
            window.addEventListener('message', onGlobalMessage, false);
        }
        else {
            window.attachEvent('onmessage', onGlobalMessage);
        }
        registerImmediate = function (handle) {
            window.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 <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement('script');
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }
    function installSetTimeoutImplementation() {
        registerImmediate = function (handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }
    // Don't get fooled by e.g. browserify environments.
    if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
        // For Node.js before 0.9
        installNextTickImplementation();
    }
    else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();
    }
    else if (typeof MessageChannel !== 'undefined') {
        // For web workers, where supported
        installMessageChannelImplementation();
    }
    else if (doc && 'onreadystatechange' in doc.createElement('script')) {
        // For IE 6–8
        installReadyStateChangeImplementation();
    }
    else {
        // For older browsers
        installSetTimeoutImplementation();
    }
    return {
        setImmediate: setImmediate,
        clearImmediate: clearImmediate
    };
}
var immediateActions = (function () {
    if (typeof setImmediate !== 'undefined') {
        if (typeof window !== 'undefined') {
            return {
                setImmediate: function (handler) {
                    var _a;
                    var args = [];
                    for (var _i = 1; _i < arguments.length; _i++) {
                        args[_i - 1] = arguments[_i];
                    }
                    return (_a = window).setImmediate.apply(_a, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])([handler], args));
                },
                clearImmediate: function (handle) { return window.clearImmediate(handle); }
            };
        }
        else {
            return { setImmediate: setImmediate, clearImmediate: clearImmediate };
        }
    }
    return createImmediateActions();
}());
function resolveImmediate(res) {
    immediateActions.setImmediate(res);
}
var Scheduler = {
    setImmediate: immediateActions.setImmediate,
    clearImmediate: immediateActions.clearImmediate,
    immediatePromise: function () { return new Promise(resolveImmediate); },
    delay: function (timeout, value) {
        if (value === void 0) { value = void 0; }
        return new Promise(function (r) { return setTimeout(r, timeout, value); });
    }
};

//# sourceMappingURL=scheduler.js.map
/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(383), __webpack_require__(384).setImmediate, __webpack_require__(384).clearImmediate))

/***/ }),
/* 340 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StateAction; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(5);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var StateAction;
(function (StateAction) {
    function create(definition) {
        var action = {
            create: function (params) { return { action: action, params: params }; },
            id: _mol_util__WEBPACK_IMPORTED_MODULE_1__[/* UUID */ "c"].create22(),
            definition: definition,
            createDefaultParams: function (a, globalCtx) { return definition.params ? _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(definition.params(a, globalCtx)) : {}; }
        };
        return action;
    }
    StateAction.create = create;
    function fromTransformer(transformer) {
        var def = transformer.definition;
        return create({
            from: def.from,
            display: def.display,
            params: def.params,
            isApplicable: transformer.definition.isApplicable
                ? function (a, t, ctx) { return transformer.definition.isApplicable(a, ctx); }
                : void 0,
            run: function (_a) {
                var cell = _a.cell, state = _a.state, params = _a.params;
                var tree = state.build().to(cell.transform.ref).apply(transformer, params);
                return state.updateTree(tree);
            }
        });
    }
    StateAction.fromTransformer = fromTransformer;
    var Builder;
    (function (Builder) {
        function root(info) {
            return function (def) { return create(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ from: info.from instanceof Array
                    ? info.from
                    : !!info.from ? [info.from] : [], display: typeof info.display === 'string'
                    ? { name: info.display }
                    : !!info.display
                        ? info.display
                        : { name: 'Unnamed State Action' }, params: typeof info.params === 'object'
                    ? function () { return info.params; }
                    : !!info.params
                        ? info.params
                        : void 0, isApplicable: info.isApplicable }, (typeof def === 'function'
                ? { run: def }
                : def))); };
        }
        Builder.build = function (info) { return root(info); };
    })(Builder = StateAction.Builder || (StateAction.Builder = {}));
    StateAction.build = Builder.build;
})(StateAction || (StateAction = {}));
//# sourceMappingURL=action.js.map

/***/ }),
/* 341 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Topology; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var Topology;
(function (Topology) {
    function create(label, basic, bonds, format) {
        return {
            id: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* UUID */ "c"].create22(),
            label: label,
            basic: basic,
            sourceData: format,
            bonds: bonds
        };
    }
    Topology.create = create;
})(Topology || (Topology = {}));
//# sourceMappingURL=topology.js.map

/***/ }),
/* 342 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Bundle; });
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(6);
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(112);
/* harmony import */ var _mol_data_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(9);
/* harmony import */ var _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(79);
/* harmony import */ var _loci__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(275);
/* harmony import */ var _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(10);
/* harmony import */ var _query__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(166);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var Bundle;
(function (Bundle) {
    Bundle.Empty = { hash: -1, elements: [] };
    function fromSubStructure(parent, structure) {
        return fromLoci(_query__WEBPACK_IMPORTED_MODULE_6__[/* StructureSelection */ "d"].toLociWithSourceUnits(_query__WEBPACK_IMPORTED_MODULE_6__[/* StructureSelection */ "d"].Singletons(parent, structure)));
    }
    Bundle.fromSubStructure = fromSubStructure;
    function fromSelection(selection) {
        return fromLoci(_query__WEBPACK_IMPORTED_MODULE_6__[/* StructureSelection */ "d"].toLociWithSourceUnits(selection));
    }
    Bundle.fromSelection = fromSelection;
    function fromLoci(loci) {
        var _elements = [];
        for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
            var e = _a[_i];
            var unit = e.unit, indices = e.indices;
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].size(indices) === 0)
                continue;
            var ranges = [];
            var set = [];
            if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].isInterval(indices)) {
                if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["OrderedSet"].size(indices) === 1) {
                    set.push(_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].min(indices));
                }
                else {
                    ranges.push(_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].min(indices), _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].max(indices));
                }
            }
            else {
                var i = 0, len = indices.length;
                while (i < len) {
                    var start = i;
                    i++;
                    while (i < len && indices[i - 1] + 1 === indices[i])
                        i++;
                    var end = i;
                    if (end - start > 2) {
                        ranges.push(indices[start], indices[end - 1]);
                    }
                    else {
                        for (var j = start; j < end; j++) {
                            set[set.length] = indices[j];
                        }
                    }
                }
            }
            _elements.push({
                unit: unit,
                set: _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(set),
                ranges: _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].ofSortedRanges(ranges)
            });
        }
        var elementGroups = new Map();
        for (var i = 0, il = _elements.length; i < il; ++i) {
            var e = _elements[i];
            var key = Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* hash2 */ "i"])(Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* hashFnv32a */ "l"])(e.ranges), Object(_mol_data_util__WEBPACK_IMPORTED_MODULE_2__[/* hashFnv32a */ "l"])(e.set));
            if (elementGroups.has(key)) {
                var groupedUnits = elementGroups.get(key).groupedUnits;
                if (groupedUnits.has(e.unit.invariantId)) {
                    groupedUnits.get(e.unit.invariantId).push(e.unit.id);
                }
                else {
                    groupedUnits.set(e.unit.invariantId, [e.unit.id]);
                }
            }
            else {
                var groupedUnits = new Map();
                groupedUnits.set(e.unit.invariantId, [e.unit.id]);
                elementGroups.set(key, { groupedUnits: groupedUnits, set: e.set, ranges: e.ranges });
            }
        }
        var elements = [];
        elementGroups.forEach(function (e) {
            var groupedUnits = [];
            e.groupedUnits.forEach(function (g) { return groupedUnits.push(_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofUnsortedArray(g)); });
            groupedUnits.sort(function (a, b) { return a[0] - b[0]; }); // sort by first unit id of each group
            elements.push({ groupedUnits: groupedUnits, set: e.set, ranges: e.ranges });
        });
        return { hash: loci.structure.hashCode, elements: elements };
    }
    Bundle.fromLoci = fromLoci;
    function getUnitsFromIds(unitIds, structure) {
        var units = [];
        for (var i = 0, il = unitIds.length; i < il; ++i) {
            var unitId = unitIds[i];
            if (structure.unitMap.has(unitId))
                units.push(structure.unitMap.get(unitId));
        }
        return units;
    }
    function toLoci(bundle, structure) {
        if (bundle.hash !== -1 && bundle.hash !== structure.hashCode) {
            new Error('Bundle not compatible with given structure');
        }
        var elements = [];
        for (var _i = 0, _a = bundle.elements; _i < _a.length; _i++) {
            var e = _a[_i];
            var _loop_1 = function (g) {
                var units = getUnitsFromIds(g, structure);
                if (units.length === 0)
                    return "continue";
                var indices = void 0;
                if (e.ranges.length === 0) {
                    indices = e.set;
                }
                else if (e.set.length === 0) {
                    if (e.ranges.length === 2) {
                        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["Interval"].ofRange(e.ranges[0], e.ranges[1]);
                    }
                    else {
                        var _indices_1 = new Int32Array(_mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].size(e.ranges));
                        _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices_1[i] = v; });
                        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(_indices_1);
                    }
                }
                else {
                    var rangesSize = _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].size(e.ranges);
                    var _indices_2 = new Int32Array(e.set.length + rangesSize);
                    _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices_2[i] = v; });
                    _indices_2.set(e.set, rangesSize);
                    indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofUnsortedArray(_indices_2); // requires sort
                }
                for (var _i = 0, units_1 = units; _i < units_1.length; _i++) {
                    var unit = units_1[_i];
                    elements.push({ unit: unit, indices: indices });
                }
            };
            for (var _b = 0, _c = e.groupedUnits; _b < _c.length; _b++) {
                var g = _c[_b];
                _loop_1(g);
            }
        }
        return Object(_loci__WEBPACK_IMPORTED_MODULE_4__[/* Loci */ "a"])(structure, elements);
    }
    Bundle.toLoci = toLoci;
    function toStructure(bundle, parent) {
        if (bundle.hash !== -1 && bundle.hash !== parent.hashCode) {
            new Error('Bundle not compatible with given structure');
        }
        var units = [];
        for (var _i = 0, _a = bundle.elements; _i < _a.length; _i++) {
            var e = _a[_i];
            var _loop_2 = function (g) {
                var _units = getUnitsFromIds(g, parent);
                if (_units.length === 0)
                    return "continue";
                var ue = _units[0].elements; // the elements are grouped by unit.invariantId
                var rangesSize = _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].size(e.ranges);
                var setSize = e.set.length;
                var _indices = new Int32Array(setSize + rangesSize);
                var indices = void 0;
                if (rangesSize === 0) {
                    for (var i = 0, il = setSize; i < il; ++i) {
                        _indices[i] = ue[e.set[i]];
                    }
                    indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(_indices);
                }
                else if (setSize === 0) {
                    _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices[i] = ue[v]; });
                    indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(_indices);
                }
                else {
                    if (_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].min(e.set) > _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].max(e.ranges)) {
                        _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices[i] = ue[v]; });
                        for (var i = 0, il = setSize; i < il; ++i) {
                            _indices[i + rangesSize] = ue[e.set[i]];
                        }
                        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(_indices);
                    }
                    else if (_mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].min(e.ranges) > _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].max(e.set)) {
                        for (var i = 0, il = setSize; i < il; ++i) {
                            _indices[i] = ue[e.set[i]];
                        }
                        _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices[i + setSize] = ue[v]; });
                        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofSortedArray(_indices);
                    }
                    else {
                        _mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].forEach(e.ranges, function (v, i) { return _indices[i] = ue[v]; });
                        for (var i = 0, il = setSize; i < il; ++i) {
                            _indices[i + rangesSize] = ue[e.set[i]];
                        }
                        indices = _mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].ofUnsortedArray(_indices); // requires sort
                    }
                }
                for (var _i = 0, _units_1 = _units; _i < _units_1.length; _i++) {
                    var unit = _units_1[_i];
                    units.push(unit.getChild(indices));
                }
            };
            for (var _b = 0, _c = e.groupedUnits; _b < _c.length; _b++) {
                var g = _c[_b];
                _loop_2(g);
            }
        }
        return _structure__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(units, { parent: parent });
    }
    Bundle.toStructure = toStructure;
    function elementToExpression(e) {
        return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].internal.generator.bundleElement({
            groupedUnits: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].core.type.list(e.groupedUnits.map(function (u) { return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].core.type.list(u); })),
            ranges: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].core.type.list(e.ranges),
            set: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].core.type.list(e.set),
        });
    }
    function toExpression(bundle) {
        return _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].internal.generator.bundle({
            elements: _mol_script_language_builder__WEBPACK_IMPORTED_MODULE_5__["MolScriptBuilder"].core.type.list(bundle.elements.map(elementToExpression))
        });
    }
    Bundle.toExpression = toExpression;
    function areEqual(a, b) {
        if (a.elements.length !== b.elements.length)
            return false;
        for (var i = 0, il = a.elements.length; i < il; ++i) {
            var elementA = a.elements[i], elementB = b.elements[i];
            if (elementA.groupedUnits.length !== elementB.groupedUnits.length)
                return false;
            for (var j = 0, jl = elementB.groupedUnits.length; j < jl; ++j) {
                if (!_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].areEqual(elementA.groupedUnits[j], elementB.groupedUnits[j]))
                    return false;
            }
            if (!_mol_data_int__WEBPACK_IMPORTED_MODULE_0__["SortedArray"].areEqual(elementA.set, elementB.set))
                return false;
            if (!_mol_data_int_sorted_ranges__WEBPACK_IMPORTED_MODULE_3__[/* default */ "a"].areEqual(elementA.ranges, elementB.ranges))
                return false;
        }
        return true;
    }
    Bundle.areEqual = areEqual;
})(Bundle || (Bundle = {}));
//# sourceMappingURL=bundle.js.map

/***/ }),
/* 343 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(7);
/* harmony import */ var _sequence__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(335);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var StructureSequence;
(function (StructureSequence) {
    var Empty = { byEntityKey: {}, sequences: [] };
    function merge() {
        var entitySeqs = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            entitySeqs[_i] = arguments[_i];
        }
        var sequences = [];
        var byEntityKey = {};
        for (var i = 0, il = entitySeqs.length; i < il; ++i) {
            sequences.push.apply(sequences, entitySeqs[i].sequences);
            Object.assign(byEntityKey, entitySeqs[i].byEntityKey);
        }
        return { sequences: sequences, byEntityKey: byEntityKey };
    }
    function fromHierarchy(entities, atomicHierarchy, coarseHierarchy) {
        var atomic = fromAtomicHierarchy(entities, atomicHierarchy);
        var coarse = coarseHierarchy.isDefined ? fromCoarseHierarchy(entities, coarseHierarchy) : Empty;
        return merge(atomic, coarse);
    }
    StructureSequence.fromHierarchy = fromHierarchy;
    function fromAtomicHierarchy(entities, hierarchy) {
        var label_comp_id = hierarchy.atoms.label_comp_id;
        var label_seq_id = hierarchy.residues.label_seq_id;
        var chainAtomSegments = hierarchy.chainAtomSegments, residueAtomSegments = hierarchy.residueAtomSegments;
        var count = chainAtomSegments.count, offsets = chainAtomSegments.offsets;
        var byEntityKey = {};
        var sequences = [];
        // check if chain segments are empty
        if (count === 1 && offsets[0] === 0 && offsets[1] === 0) {
            return { byEntityKey: byEntityKey, sequences: sequences };
        }
        for (var cI = 0, _cI = hierarchy.chains._rowCount; cI < _cI; cI++) {
            var entityKey = hierarchy.index.getEntityFromChain(cI);
            // Only for polymers, trying to mirror _entity_poly_seq
            if (byEntityKey[entityKey] !== void 0 || entities.data.type.value(entityKey) !== 'polymer')
                continue;
            var start = cI;
            cI++;
            while (cI < _cI && entityKey === hierarchy.index.getEntityFromChain(cI) && entities.data.type.value(entityKey) !== 'polymer') {
                cI++;
            }
            cI--;
            var rStart = residueAtomSegments.index[offsets[start]];
            var rEnd = residueAtomSegments.index[offsets[cI + 1] - 1] + 1;
            var seqId = _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].window(label_seq_id, rStart, rEnd);
            var _compId = [];
            for (var rI = rStart; rI < rEnd; ++rI) {
                _compId.push(label_comp_id.value(residueAtomSegments.offsets[rI]));
            }
            var compId = _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].ofStringArray(_compId);
            byEntityKey[entityKey] = {
                entityId: entities.data.id.value(entityKey),
                sequence: _sequence__WEBPACK_IMPORTED_MODULE_1__[/* Sequence */ "a"].ofResidueNames(compId, seqId)
            };
            sequences.push(byEntityKey[entityKey]);
        }
        return { byEntityKey: byEntityKey, sequences: sequences };
    }
    StructureSequence.fromAtomicHierarchy = fromAtomicHierarchy;
    function fromCoarseHierarchy(entities, hierarchy) {
        var spheres = fromCoarseElements(entities, hierarchy.spheres);
        var gaussians = fromCoarseElements(entities, hierarchy.gaussians);
        return merge(spheres, gaussians);
    }
    StructureSequence.fromCoarseHierarchy = fromCoarseHierarchy;
    function fromCoarseElements(entities, elements) {
        var chainElementSegments = elements.chainElementSegments, seq_id_begin = elements.seq_id_begin, seq_id_end = elements.seq_id_end;
        var count = chainElementSegments.count, offsets = chainElementSegments.offsets;
        var byEntityKey = {};
        var sequences = [];
        // check if chain segments are empty
        if (count === 1 && offsets[0] === 0 && offsets[1] === 0) {
            return { byEntityKey: byEntityKey, sequences: sequences };
        }
        for (var cI = 0, _cI = count; cI < _cI; cI++) {
            var eK = elements.getEntityFromChain(cI);
            if (byEntityKey[eK] !== void 0)
                continue;
            var start = cI;
            cI++;
            while (cI < _cI && eK === elements.getEntityFromChain(cI)) {
                cI++;
            }
            cI--;
            var eStart = offsets[start];
            var eEnd = offsets[cI + 1] - 1;
            var seqIdBegin = _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].window(seq_id_begin, eStart, eEnd);
            var seqIdEnd = _mol_data_db__WEBPACK_IMPORTED_MODULE_0__["Column"].window(seq_id_end, eStart, eEnd);
            byEntityKey[eK] = {
                entityId: entities.data.id.value(eK),
                sequence: _sequence__WEBPACK_IMPORTED_MODULE_1__[/* Sequence */ "a"].ofSequenceRanges(seqIdBegin, seqIdEnd)
            };
            sequences.push(byEntityKey[eK]);
        }
        return { byEntityKey: byEntityKey, sequences: sequences };
    }
    StructureSequence.fromCoarseElements = fromCoarseElements;
})(StructureSequence || (StructureSequence = {}));
/* harmony default export */ __webpack_exports__["a"] = (StructureSequence);
//# sourceMappingURL=sequence.js.map

/***/ }),
/* 344 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return timer; });
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(44);
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(103);
/* harmony import */ var _util_isNumeric__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(231);
/* harmony import */ var _util_isScheduler__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(122);
/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */




function timer(dueTime, periodOrScheduler, scheduler) {
    if (dueTime === void 0) {
        dueTime = 0;
    }
    var period = -1;
    if (Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__[/* isNumeric */ "a"])(periodOrScheduler)) {
        period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler);
    }
    else if (Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__[/* isScheduler */ "a"])(periodOrScheduler)) {
        scheduler = periodOrScheduler;
    }
    if (!Object(_util_isScheduler__WEBPACK_IMPORTED_MODULE_3__[/* isScheduler */ "a"])(scheduler)) {
        scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_1__[/* async */ "a"];
    }
    return new _Observable__WEBPACK_IMPORTED_MODULE_0__[/* Observable */ "a"](function (subscriber) {
        var due = Object(_util_isNumeric__WEBPACK_IMPORTED_MODULE_2__[/* isNumeric */ "a"])(dueTime)
            ? dueTime
            : (+dueTime - scheduler.now());
        return scheduler.schedule(dispatch, due, {
            index: 0, period: period, subscriber: subscriber
        });
    });
}
function dispatch(state) {
    var index = state.index, period = state.period, subscriber = state.subscriber;
    subscriber.next(index);
    if (subscriber.closed) {
        return;
    }
    else if (period === -1) {
        return subscriber.complete();
    }
    state.index = index + 1;
    this.schedule(state, period);
}
//# sourceMappingURL=timer.js.map


/***/ }),
/* 345 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return concatAll; });
/* harmony import */ var _mergeAll__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(292);
/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */

function concatAll() {
    return Object(_mergeAll__WEBPACK_IMPORTED_MODULE_0__[/* mergeAll */ "a"])(1);
}
//# sourceMappingURL=concatAll.js.map


/***/ }),
/* 346 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ConnectableObservable; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return connectableObservableDescriptor; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subject__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(60);
/* harmony import */ var _Observable__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(44);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(35);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(70);
/* harmony import */ var _operators_refCount__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(296);
/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */






var ConnectableObservable = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ConnectableObservable, _super);
    function ConnectableObservable(source, subjectFactory) {
        var _this = _super.call(this) || this;
        _this.source = source;
        _this.subjectFactory = subjectFactory;
        _this._refCount = 0;
        _this._isComplete = false;
        return _this;
    }
    ConnectableObservable.prototype._subscribe = function (subscriber) {
        return this.getSubject().subscribe(subscriber);
    };
    ConnectableObservable.prototype.getSubject = function () {
        var subject = this._subject;
        if (!subject || subject.isStopped) {
            this._subject = this.subjectFactory();
        }
        return this._subject;
    };
    ConnectableObservable.prototype.connect = function () {
        var connection = this._connection;
        if (!connection) {
            this._isComplete = false;
            connection = this._connection = new _Subscription__WEBPACK_IMPORTED_MODULE_4__[/* Subscription */ "a"]();
            connection.add(this.source
                .subscribe(new ConnectableSubscriber(this.getSubject(), this)));
            if (connection.closed) {
                this._connection = null;
                connection = _Subscription__WEBPACK_IMPORTED_MODULE_4__[/* Subscription */ "a"].EMPTY;
            }
        }
        return connection;
    };
    ConnectableObservable.prototype.refCount = function () {
        return Object(_operators_refCount__WEBPACK_IMPORTED_MODULE_5__[/* refCount */ "a"])()(this);
    };
    return ConnectableObservable;
}(_Observable__WEBPACK_IMPORTED_MODULE_2__[/* Observable */ "a"]));

var connectableObservableDescriptor = /*@__PURE__*/ (function () {
    var connectableProto = ConnectableObservable.prototype;
    return {
        operator: { value: null },
        _refCount: { value: 0, writable: true },
        _subject: { value: null, writable: true },
        _connection: { value: null, writable: true },
        _subscribe: { value: connectableProto._subscribe },
        _isComplete: { value: connectableProto._isComplete, writable: true },
        getSubject: { value: connectableProto.getSubject },
        connect: { value: connectableProto.connect },
        refCount: { value: connectableProto.refCount }
    };
})();
var ConnectableSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ConnectableSubscriber, _super);
    function ConnectableSubscriber(destination, connectable) {
        var _this = _super.call(this, destination) || this;
        _this.connectable = connectable;
        return _this;
    }
    ConnectableSubscriber.prototype._error = function (err) {
        this._unsubscribe();
        _super.prototype._error.call(this, err);
    };
    ConnectableSubscriber.prototype._complete = function () {
        this.connectable._isComplete = true;
        this._unsubscribe();
        _super.prototype._complete.call(this);
    };
    ConnectableSubscriber.prototype._unsubscribe = function () {
        var connectable = this.connectable;
        if (connectable) {
            this.connectable = null;
            var connection = connectable._connection;
            connectable._refCount = 0;
            connectable._subject = null;
            connectable._connection = null;
            if (connection) {
                connection.unsubscribe();
            }
        }
    };
    return ConnectableSubscriber;
}(_Subject__WEBPACK_IMPORTED_MODULE_1__[/* SubjectSubscriber */ "b"]));
var RefCountOperator = /*@__PURE__*/ (function () {
    function RefCountOperator(connectable) {
        this.connectable = connectable;
    }
    RefCountOperator.prototype.call = function (subscriber, source) {
        var connectable = this.connectable;
        connectable._refCount++;
        var refCounter = new RefCountSubscriber(subscriber, connectable);
        var subscription = source.subscribe(refCounter);
        if (!refCounter.closed) {
            refCounter.connection = connectable.connect();
        }
        return subscription;
    };
    return RefCountOperator;
}());
var RefCountSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](RefCountSubscriber, _super);
    function RefCountSubscriber(destination, connectable) {
        var _this = _super.call(this, destination) || this;
        _this.connectable = connectable;
        return _this;
    }
    RefCountSubscriber.prototype._unsubscribe = function () {
        var connectable = this.connectable;
        if (!connectable) {
            this.connection = null;
            return;
        }
        this.connectable = null;
        var refCount = connectable._refCount;
        if (refCount <= 0) {
            this.connection = null;
            return;
        }
        connectable._refCount = refCount - 1;
        if (refCount > 1) {
            this.connection = null;
            return;
        }
        var connection = this.connection;
        var sharedConnection = connectable._connection;
        this.connection = null;
        if (sharedConnection && (!connection || sharedConnection === connection)) {
            sharedConnection.unsubscribe();
        }
    };
    return RefCountSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_3__[/* Subscriber */ "a"]));
//# sourceMappingURL=ConnectableObservable.js.map


/***/ }),
/* 347 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return observeOn; });
/* unused harmony export ObserveOnOperator */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ObserveOnSubscriber; });
/* unused harmony export ObserveOnMessage */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/* harmony import */ var _Notification__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(190);
/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */



function observeOn(scheduler, delay) {
    if (delay === void 0) {
        delay = 0;
    }
    return function observeOnOperatorFunction(source) {
        return source.lift(new ObserveOnOperator(scheduler, delay));
    };
}
var ObserveOnOperator = /*@__PURE__*/ (function () {
    function ObserveOnOperator(scheduler, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        this.scheduler = scheduler;
        this.delay = delay;
    }
    ObserveOnOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay));
    };
    return ObserveOnOperator;
}());

var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](ObserveOnSubscriber, _super);
    function ObserveOnSubscriber(destination, scheduler, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        var _this = _super.call(this, destination) || this;
        _this.scheduler = scheduler;
        _this.delay = delay;
        return _this;
    }
    ObserveOnSubscriber.dispatch = function (arg) {
        var notification = arg.notification, destination = arg.destination;
        notification.observe(destination);
        this.unsubscribe();
    };
    ObserveOnSubscriber.prototype.scheduleMessage = function (notification) {
        var destination = this.destination;
        destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination)));
    };
    ObserveOnSubscriber.prototype._next = function (value) {
        this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__[/* Notification */ "a"].createNext(value));
    };
    ObserveOnSubscriber.prototype._error = function (err) {
        this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__[/* Notification */ "a"].createError(err));
        this.unsubscribe();
    };
    ObserveOnSubscriber.prototype._complete = function () {
        this.scheduleMessage(_Notification__WEBPACK_IMPORTED_MODULE_2__[/* Notification */ "a"].createComplete());
        this.unsubscribe();
    };
    return ObserveOnSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));

var ObserveOnMessage = /*@__PURE__*/ (function () {
    function ObserveOnMessage(notification, destination) {
        this.notification = notification;
        this.destination = destination;
    }
    return ObserveOnMessage;
}());

//# sourceMappingURL=observeOn.js.map


/***/ }),
/* 348 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return race; });
/* unused harmony export RaceOperator */
/* unused harmony export RaceSubscriber */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _util_isArray__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(100);
/* harmony import */ var _fromArray__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(224);
/* harmony import */ var _OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(52);
/* harmony import */ var _util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(50);
/** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */





function race() {
    var observables = [];
    for (var _i = 0; _i < arguments.length; _i++) {
        observables[_i] = arguments[_i];
    }
    if (observables.length === 1) {
        if (Object(_util_isArray__WEBPACK_IMPORTED_MODULE_1__[/* isArray */ "a"])(observables[0])) {
            observables = observables[0];
        }
        else {
            return observables[0];
        }
    }
    return Object(_fromArray__WEBPACK_IMPORTED_MODULE_2__[/* fromArray */ "a"])(observables, undefined).lift(new RaceOperator());
}
var RaceOperator = /*@__PURE__*/ (function () {
    function RaceOperator() {
    }
    RaceOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new RaceSubscriber(subscriber));
    };
    return RaceOperator;
}());

var RaceSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](RaceSubscriber, _super);
    function RaceSubscriber(destination) {
        var _this = _super.call(this, destination) || this;
        _this.hasFirst = false;
        _this.observables = [];
        _this.subscriptions = [];
        return _this;
    }
    RaceSubscriber.prototype._next = function (observable) {
        this.observables.push(observable);
    };
    RaceSubscriber.prototype._complete = function () {
        var observables = this.observables;
        var len = observables.length;
        if (len === 0) {
            this.destination.complete();
        }
        else {
            for (var i = 0; i < len && !this.hasFirst; i++) {
                var observable = observables[i];
                var subscription = Object(_util_subscribeToResult__WEBPACK_IMPORTED_MODULE_4__[/* subscribeToResult */ "a"])(this, observable, observable, i);
                if (this.subscriptions) {
                    this.subscriptions.push(subscription);
                }
                this.add(subscription);
            }
            this.observables = null;
        }
    };
    RaceSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) {
        if (!this.hasFirst) {
            this.hasFirst = true;
            for (var i = 0; i < this.subscriptions.length; i++) {
                if (i !== outerIndex) {
                    var subscription = this.subscriptions[i];
                    subscription.unsubscribe();
                    this.remove(subscription);
                }
            }
            this.subscriptions = null;
        }
        this.destination.next(innerValue);
    };
    return RaceSubscriber;
}(_OuterSubscriber__WEBPACK_IMPORTED_MODULE_3__[/* OuterSubscriber */ "a"]));

//# sourceMappingURL=race.js.map


/***/ }),
/* 349 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TimeoutError; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var TimeoutErrorImpl = /*@__PURE__*/ (function () {
    function TimeoutErrorImpl() {
        Error.call(this);
        this.message = 'Timeout has occurred';
        this.name = 'TimeoutError';
        return this;
    }
    TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype);
    return TimeoutErrorImpl;
})();
var TimeoutError = TimeoutErrorImpl;
//# sourceMappingURL=TimeoutError.js.map


/***/ }),
/* 350 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ scheduled; });

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Observable.js + 1 modules
var Observable = __webpack_require__(44);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subscription.js
var Subscription = __webpack_require__(70);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/observable.js
var symbol_observable = __webpack_require__(203);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/scheduleObservable.js
/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */



function scheduleObservable(input, scheduler) {
    return new Observable["a" /* Observable */](function (subscriber) {
        var sub = new Subscription["a" /* Subscription */]();
        sub.add(scheduler.schedule(function () {
            var observable = input[symbol_observable["a" /* observable */]]();
            sub.add(observable.subscribe({
                next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); },
                error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); },
                complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); },
            }));
        }));
        return sub;
    });
}
//# sourceMappingURL=scheduleObservable.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/schedulePromise.js
/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */


function schedulePromise(input, scheduler) {
    return new Observable["a" /* Observable */](function (subscriber) {
        var sub = new Subscription["a" /* Subscription */]();
        sub.add(scheduler.schedule(function () {
            return input.then(function (value) {
                sub.add(scheduler.schedule(function () {
                    subscriber.next(value);
                    sub.add(scheduler.schedule(function () { return subscriber.complete(); }));
                }));
            }, function (err) {
                sub.add(scheduler.schedule(function () { return subscriber.error(err); }));
            });
        }));
        return sub;
    });
}
//# sourceMappingURL=schedulePromise.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/scheduleArray.js
var scheduleArray = __webpack_require__(311);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/symbol/iterator.js
var symbol_iterator = __webpack_require__(197);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/scheduleIterable.js
/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */



function scheduleIterable(input, scheduler) {
    if (!input) {
        throw new Error('Iterable cannot be null');
    }
    return new Observable["a" /* Observable */](function (subscriber) {
        var sub = new Subscription["a" /* Subscription */]();
        var iterator;
        sub.add(function () {
            if (iterator && typeof iterator.return === 'function') {
                iterator.return();
            }
        });
        sub.add(scheduler.schedule(function () {
            iterator = input[symbol_iterator["a" /* iterator */]]();
            sub.add(scheduler.schedule(function () {
                if (subscriber.closed) {
                    return;
                }
                var value;
                var done;
                try {
                    var result = iterator.next();
                    value = result.value;
                    done = result.done;
                }
                catch (err) {
                    subscriber.error(err);
                    return;
                }
                if (done) {
                    subscriber.complete();
                }
                else {
                    subscriber.next(value);
                    this.schedule();
                }
            }));
        }));
        return sub;
    });
}
//# sourceMappingURL=scheduleIterable.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/isInteropObservable.js
/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */

function isInteropObservable(input) {
    return input && typeof input[symbol_observable["a" /* observable */]] === 'function';
}
//# sourceMappingURL=isInteropObservable.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isPromise.js
var isPromise = __webpack_require__(375);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/util/isArrayLike.js
var isArrayLike = __webpack_require__(373);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/util/isIterable.js
/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */

function isIterable(input) {
    return input && typeof input[symbol_iterator["a" /* iterator */]] === 'function';
}
//# sourceMappingURL=isIterable.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduled/scheduled.js
/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */








function scheduled(input, scheduler) {
    if (input != null) {
        if (isInteropObservable(input)) {
            return scheduleObservable(input, scheduler);
        }
        else if (Object(isPromise["a" /* isPromise */])(input)) {
            return schedulePromise(input, scheduler);
        }
        else if (Object(isArrayLike["a" /* isArrayLike */])(input)) {
            return Object(scheduleArray["a" /* scheduleArray */])(input, scheduler);
        }
        else if (isIterable(input) || typeof input === 'string') {
            return scheduleIterable(input, scheduler);
        }
    }
    throw new TypeError((input !== null && typeof input || input) + ' is not observable');
}
//# sourceMappingURL=scheduled.js.map


/***/ }),
/* 351 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ queue; });

// EXTERNAL MODULE: ./node_modules/rxjs/node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(21);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncAction.js + 1 modules
var AsyncAction = __webpack_require__(229);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/QueueAction.js
/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */


var QueueAction_QueueAction = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](QueueAction, _super);
    function QueueAction(scheduler, work) {
        var _this = _super.call(this, scheduler, work) || this;
        _this.scheduler = scheduler;
        _this.work = work;
        return _this;
    }
    QueueAction.prototype.schedule = function (state, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if (delay > 0) {
            return _super.prototype.schedule.call(this, state, delay);
        }
        this.delay = delay;
        this.state = state;
        this.scheduler.flush(this);
        return this;
    };
    QueueAction.prototype.execute = function (state, delay) {
        return (delay > 0 || this.closed) ?
            _super.prototype.execute.call(this, state, delay) :
            this._execute(state, delay);
    };
    QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) {
        if (delay === void 0) {
            delay = 0;
        }
        if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) {
            return _super.prototype.requestAsyncId.call(this, scheduler, id, delay);
        }
        return scheduler.flush(this);
    };
    return QueueAction;
}(AsyncAction["a" /* AsyncAction */]));

//# sourceMappingURL=QueueAction.js.map

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/AsyncScheduler.js
var AsyncScheduler = __webpack_require__(225);

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/QueueScheduler.js
/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */


var QueueScheduler_QueueScheduler = /*@__PURE__*/ (function (_super) {
    tslib_es6["a" /* __extends */](QueueScheduler, _super);
    function QueueScheduler() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return QueueScheduler;
}(AsyncScheduler["a" /* AsyncScheduler */]));

//# sourceMappingURL=QueueScheduler.js.map

// CONCATENATED MODULE: ./node_modules/rxjs/_esm5/internal/scheduler/queue.js
/** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */


var queue = /*@__PURE__*/ new QueueScheduler_QueueScheduler(QueueAction_QueueAction);
//# sourceMappingURL=queue.js.map


/***/ }),
/* 352 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ model_Model; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/uuid.js
var uuid = __webpack_require__(194);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var array = __webpack_require__(29);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/util.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function calcModelCenter(atomicConformation, coarseConformation) {
    var rangesX = [];
    var rangesY = [];
    var rangesZ = [];
    if (atomicConformation.x.length) {
        rangesX.push.apply(rangesX, Object(array["arrayMinMax"])(atomicConformation.x));
        rangesY.push.apply(rangesY, Object(array["arrayMinMax"])(atomicConformation.y));
        rangesZ.push.apply(rangesZ, Object(array["arrayMinMax"])(atomicConformation.z));
    }
    if (coarseConformation) {
        if (coarseConformation.spheres.x.length) {
            rangesX.push.apply(rangesX, Object(array["arrayMinMax"])(coarseConformation.spheres.x));
            rangesY.push.apply(rangesY, Object(array["arrayMinMax"])(coarseConformation.spheres.y));
            rangesZ.push.apply(rangesZ, Object(array["arrayMinMax"])(coarseConformation.spheres.z));
        }
        if (coarseConformation.gaussians.x.length) {
            rangesX.push.apply(rangesX, Object(array["arrayMinMax"])(coarseConformation.gaussians.x));
            rangesY.push.apply(rangesY, Object(array["arrayMinMax"])(coarseConformation.gaussians.y));
            rangesZ.push.apply(rangesZ, Object(array["arrayMinMax"])(coarseConformation.gaussians.z));
        }
    }
    var _a = Object(array["arrayMinMax"])(rangesX), minX = _a[0], maxX = _a[1];
    var _b = Object(array["arrayMinMax"])(rangesY), minY = _b[0], maxY = _b[1];
    var _c = Object(array["arrayMinMax"])(rangesZ), minZ = _c[0], maxZ = _c[1];
    var x = minX + (maxX - minX) / 2;
    var y = minY + (maxY - minY) / 2;
    var z = minZ + (maxZ - minZ) / 2;
    return linear_algebra["Vec3"].create(x, y, z);
}
function getAsymIdCount(model) {
    var auth = new Set();
    var label = new Set();
    model.properties.structAsymMap.forEach(function (_a, label_id) {
        var auth_id = _a.auth_id;
        auth.add(auth_id);
        label.add(label_id);
    });
    return { auth: auth.size, label: label.size };
}
//# sourceMappingURL=util.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/coordinates.js + 1 modules
var structure_coordinates = __webpack_require__(165);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/bonds/index-pair.js
var index_pair = __webpack_require__(173);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/basic/parser.js + 13 modules
var parser = __webpack_require__(154);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js + 1 modules
var symmetry = __webpack_require__(113);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var mol_data_db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-model-property.js
var custom_model_property = __webpack_require__(276);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model/structure/model/model.js
/**
 * Copyright (c) 2017-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













{ }
var model_Model;
(function (Model) {
    function _trajectoryFromModelAndCoordinates(model, coordinates) {
        var trajectory = [];
        var frames = coordinates.frames;
        var srcIndex = model.atomicHierarchy.atoms.sourceIndex;
        var isIdentity = mol_data_db["Column"].isIdentity(srcIndex);
        var srcIndexArray = isIdentity ? void 0 : srcIndex.toArray({ array: Int32Array });
        for (var i = 0, il = frames.length; i < il; ++i) {
            var f = frames[i];
            var m = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, model), { id: uuid["a" /* default */].create22(), modelNum: i, atomicConformation: isIdentity
                    ? structure_coordinates["a" /* Coordinates */].getAtomicConformation(f, model.atomicConformation.atomId)
                    : structure_coordinates["a" /* Coordinates */].getAtomicConformationReordered(f, model.atomicConformation.atomId, srcIndexArray),
                // TODO: add support for supplying sphere and gaussian coordinates in addition to atomic coordinates?
                // coarseConformation: coarse.conformation,
                customProperties: new custom_property["CustomProperties"](), _staticPropertyData: Object.create(null), _dynamicPropertyData: Object.create(null) });
            trajectory.push(m);
        }
        return { trajectory: trajectory, srcIndexArray: srcIndexArray };
    }
    function trajectoryFromModelAndCoordinates(model, coordinates) {
        return _trajectoryFromModelAndCoordinates(model, coordinates).trajectory;
    }
    Model.trajectoryFromModelAndCoordinates = trajectoryFromModelAndCoordinates;
    function invertIndex(xs) {
        var ret = new Int32Array(xs.length);
        for (var i = 0, _i = xs.length; i < _i; i++) {
            ret[xs[i]] = i;
        }
        return ret;
    }
    function trajectoryFromTopologyAndCoordinates(topology, coordinates) {
        var _this = this;
        return mol_task["b" /* Task */].create('Create Trajectory', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var model, _a, trajectory, srcIndexArray, invertedIndex, pairs, bondData, indexPairBonds, index, _b, trajectory_1, m;
            return Object(tslib_es6["__generator"])(this, function (_c) {
                switch (_c.label) {
                    case 0: return [4 /*yield*/, Object(parser["a" /* createModels */])(topology.basic, topology.sourceData, ctx)];
                    case 1:
                        model = (_c.sent())[0];
                        if (!model)
                            throw new Error('found no model');
                        _a = _trajectoryFromModelAndCoordinates(model, coordinates), trajectory = _a.trajectory, srcIndexArray = _a.srcIndexArray;
                        invertedIndex = srcIndexArray ? invertIndex(srcIndexArray) : void 0;
                        pairs = srcIndexArray
                            ? {
                                indexA: mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(topology.bonds.indexA, function (i) { return invertedIndex[i]; }, Int32Array)),
                                indexB: mol_data_db["Column"].ofIntArray(mol_data_db["Column"].mapToArray(topology.bonds.indexB, function (i) { return invertedIndex[i]; }, Int32Array)),
                                order: topology.bonds.order
                            }
                            : topology.bonds;
                        bondData = { pairs: pairs, count: model.atomicHierarchy.atoms._rowCount };
                        indexPairBonds = index_pair["a" /* IndexPairBonds */].fromData(bondData);
                        index = 0;
                        for (_b = 0, trajectory_1 = trajectory; _b < trajectory_1.length; _b++) {
                            m = trajectory_1[_b];
                            index_pair["a" /* IndexPairBonds */].Provider.set(m, indexPairBonds);
                            Model.TrajectoryInfo.set(m, { index: index++, size: trajectory.length });
                        }
                        return [2 /*return*/, trajectory];
                }
            });
        }); });
    }
    Model.trajectoryFromTopologyAndCoordinates = trajectoryFromTopologyAndCoordinates;
    var CenterProp = '__Center__';
    function getCenter(model) {
        if (model._dynamicPropertyData[CenterProp])
            return model._dynamicPropertyData[CenterProp];
        var center = calcModelCenter(model.atomicConformation, model.coarseConformation);
        model._dynamicPropertyData[CenterProp] = center;
        return center;
    }
    Model.getCenter = getCenter;
    var TrajectoryInfoProp = '__TrajectoryInfo__';
    Model.TrajectoryInfo = {
        get: function (model) {
            return model._staticPropertyData[TrajectoryInfoProp] || { index: 0, size: 1 };
        },
        set: function (model, trajectoryInfo) {
            return model._staticPropertyData[TrajectoryInfoProp] = trajectoryInfo;
        }
    };
    var AsymIdCountProp = '__AsymIdCount__';
    Model.AsymIdCount = {
        get: function (model) {
            if (model._staticPropertyData[AsymIdCountProp])
                return model._staticPropertyData[AsymIdCountProp];
            var asymIdCount = getAsymIdCount(model);
            model._staticPropertyData[AsymIdCountProp] = asymIdCount;
            return asymIdCount;
        },
    };
    Model.AsymIdOffset = custom_model_property["CustomModelProperty"].createSimple('asym_id_offset', 'static');
    Model.Index = custom_model_property["CustomModelProperty"].createSimple('index', 'static');
    //
    function hasCarbohydrate(model) {
        return model.properties.saccharideComponentMap.size > 0;
    }
    Model.hasCarbohydrate = hasCarbohydrate;
    function hasProtein(model) {
        var subtype = model.entities.subtype;
        for (var i = 0, il = subtype.rowCount; i < il; ++i) {
            if (subtype.value(i).startsWith('polypeptide'))
                return true;
        }
        return false;
    }
    Model.hasProtein = hasProtein;
    function hasNucleic(model) {
        var subtype = model.entities.subtype;
        for (var i = 0, il = subtype.rowCount; i < il; ++i) {
            var s = subtype.value(i);
            if (s.endsWith('ribonucleotide hybrid') || s.endsWith('ribonucleotide'))
                return true;
        }
        return false;
    }
    Model.hasNucleic = hasNucleic;
    function isFromPdbArchive(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        return (db.database_2.database_id.isDefined ||
            // 4 character PDB id
            model.entryId.match(/^[1-9][a-z0-9]{3,3}$/i) !== null ||
            // long PDB id
            model.entryId.match(/^pdb_[0-9]{4,4}[1-9][a-z0-9]{3,3}$/i) !== null);
    }
    Model.isFromPdbArchive = isFromPdbArchive;
    function hasSecondaryStructure(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        return (db.struct_conf.id.isDefined ||
            db.struct_sheet_range.id.isDefined);
    }
    Model.hasSecondaryStructure = hasSecondaryStructure;
    var tmpAngles90 = linear_algebra["Vec3"].create(1.5707963, 1.5707963, 1.5707963); // in radians
    var tmpLengths1 = linear_algebra["Vec3"].create(1, 1, 1);
    function hasCrystalSymmetry(model) {
        var _a;
        var spacegroup = (_a = symmetry["a" /* ModelSymmetry */].Provider.get(model)) === null || _a === void 0 ? void 0 : _a.spacegroup;
        return !!spacegroup && !(spacegroup.num === 1 &&
            linear_algebra["Vec3"].equals(spacegroup.cell.anglesInRadians, tmpAngles90) &&
            linear_algebra["Vec3"].equals(spacegroup.cell.size, tmpLengths1));
    }
    Model.hasCrystalSymmetry = hasCrystalSymmetry;
    function isFromXray(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        for (var i = 0; i < db.exptl.method.rowCount; i++) {
            var v = db.exptl.method.value(i).toUpperCase();
            if (v.indexOf('DIFFRACTION') >= 0)
                return true;
        }
        return false;
    }
    Model.isFromXray = isFromXray;
    function isFromEm(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        for (var i = 0; i < db.exptl.method.rowCount; i++) {
            var v = db.exptl.method.value(i).toUpperCase();
            if (v.indexOf('MICROSCOPY') >= 0)
                return true;
        }
        return false;
    }
    Model.isFromEm = isFromEm;
    function isFromNmr(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        for (var i = 0; i < db.exptl.method.rowCount; i++) {
            var v = db.exptl.method.value(i).toUpperCase();
            if (v.indexOf('NMR') >= 0)
                return true;
        }
        return false;
    }
    Model.isFromNmr = isFromNmr;
    function hasXrayMap(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        // Check exprimental method to exclude models solved with
        // 'ELECTRON CRYSTALLOGRAPHY' which also have structure factors
        if (!isFromXray(model))
            return false;
        var db = model.sourceData.data.db;
        var status_code_sf = db.pdbx_database_status.status_code_sf;
        return status_code_sf.isDefined && status_code_sf.value(0) === 'REL';
    }
    Model.hasXrayMap = hasXrayMap;
    /**
     * Also checks for `content_type` of 'associated EM volume' to exclude cases
     * like 6TEK which are solved with 'X-RAY DIFFRACTION' but have an related
     * EMDB entry of type 'other EM volume'.
     */
    function hasEmMap(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        var _a = db.pdbx_database_related, db_name = _a.db_name, content_type = _a.content_type;
        for (var i = 0, il = db.pdbx_database_related._rowCount; i < il; ++i) {
            if (db_name.value(i).toUpperCase() === 'EMDB' && content_type.value(i) === 'associated EM volume') {
                return true;
            }
        }
        return false;
    }
    Model.hasEmMap = hasEmMap;
    function hasDensityMap(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        return hasXrayMap(model) || hasEmMap(model);
    }
    Model.hasDensityMap = hasDensityMap;
    function probablyHasDensityMap(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return false;
        var db = model.sourceData.data.db;
        return hasDensityMap(model) || (
        // check if from pdb archive but missing relevant meta data
        isFromPdbArchive(model) && (!db.exptl.method.isDefined ||
            (isFromXray(model) && (!db.pdbx_database_status.status_code_sf.isDefined ||
                db.pdbx_database_status.status_code_sf.valueKind(0) === 2 /* Unknown */)) ||
            (isFromEm(model) && (!db.pdbx_database_related.db_name.isDefined))));
    }
    Model.probablyHasDensityMap = probablyHasDensityMap;
})(model_Model || (model_Model = {}));
//# sourceMappingURL=model.js.map

/***/ }),
/* 353 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SubjectSubscription; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscription__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(70);
/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */


var SubjectSubscription = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](SubjectSubscription, _super);
    function SubjectSubscription(subject, subscriber) {
        var _this = _super.call(this) || this;
        _this.subject = subject;
        _this.subscriber = subscriber;
        _this.closed = false;
        return _this;
    }
    SubjectSubscription.prototype.unsubscribe = function () {
        if (this.closed) {
            return;
        }
        this.closed = true;
        var subject = this.subject;
        var observers = subject.observers;
        this.subject = null;
        if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {
            return;
        }
        var subscriberIndex = observers.indexOf(this.subscriber);
        if (subscriberIndex !== -1) {
            observers.splice(subscriberIndex, 1);
        }
    };
    return SubjectSubscription;
}(_Subscription__WEBPACK_IMPORTED_MODULE_1__[/* Subscription */ "a"]));

//# sourceMappingURL=SubjectSubscription.js.map


/***/ }),
/* 354 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return volumeFromCube; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CubeFormat; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(16);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(29);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(65);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function volumeFromCube(source, params) {
    var _this = this;
    return _mol_task__WEBPACK_IMPORTED_MODULE_2__[/* Task */ "b"].create('Create Volume', function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var header, sourceValues, space, values, _a, h, k, l, nth, o, s, u, v, w, data, matrix, basis;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
            header = source.header, sourceValues = source.values;
            space = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].Space(header.dim, [0, 1, 2], Float64Array);
            if (header.dataSetIds.length === 0) {
                values = sourceValues;
            }
            else {
                _a = header.dim, h = _a[0], k = _a[1], l = _a[2];
                nth = ((params === null || params === void 0 ? void 0 : params.dataIndex) || 0) + 1;
                o = 0, s = 0;
                values = new Float64Array(h * k * l);
                for (u = 0; u < h; u++) {
                    for (v = 0; v < k; v++) {
                        for (w = 0; w < l; w++) {
                            values[o++] = sourceValues[s];
                            s += nth;
                        }
                    }
                }
            }
            data = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].create(space, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Tensor"].Data1(values));
            matrix = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].fromTranslation(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])(), header.origin);
            basis = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].fromBasis(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])(), header.basisX, header.basisY, header.basisZ);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mul(matrix, matrix, basis);
            return [2 /*return*/, {
                    label: params === null || params === void 0 ? void 0 : params.label,
                    grid: {
                        transform: { kind: 'matrix', matrix: matrix },
                        cells: data,
                        stats: {
                            min: Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_3__["arrayMin"])(values),
                            max: Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_3__["arrayMax"])(values),
                            mean: Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_3__["arrayMean"])(values),
                            sigma: Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_3__["arrayRms"])(values)
                        },
                    },
                    sourceData: CubeFormat.create(source),
                    customProperties: new _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__["CustomProperties"](),
                    _propertyData: Object.create(null),
                }];
        });
    }); });
}
//

var CubeFormat;
(function (CubeFormat) {
    function is(x) {
        return x.kind === 'cube';
    }
    CubeFormat.is = is;
    function create(cube) {
        return { kind: 'cube', name: cube.name, data: cube };
    }
    CubeFormat.create = create;
})(CubeFormat || (CubeFormat = {}));
//# sourceMappingURL=cube.js.map

/***/ }),
/* 355 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export UniformColorThemeParams */
/* unused harmony export getUniformColorThemeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UniformColorTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UniformColorThemeProvider; });
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _mol_util_legend__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(141);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var DefaultColor = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["Color"])(0xCCCCCC);
var Description = 'Gives everything the same, uniform color.';
var UniformColorThemeParams = {
    value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Color(DefaultColor),
};
function getUniformColorThemeParams(ctx) {
    return UniformColorThemeParams; // TODO return copy
}
function UniformColorTheme(ctx, props) {
    var color = Object(_mol_util__WEBPACK_IMPORTED_MODULE_3__[/* defaults */ "i"])(props.value, DefaultColor);
    return {
        factory: UniformColorTheme,
        granularity: 'uniform',
        color: function () { return color; },
        props: props,
        description: Description,
        legend: Object(_mol_util_legend__WEBPACK_IMPORTED_MODULE_2__[/* TableLegend */ "b"])([['uniform', color]])
    };
}
var UniformColorThemeProvider = {
    name: 'uniform',
    label: 'Uniform',
    category: "Miscellaneous" /* Misc */,
    factory: UniformColorTheme,
    getParams: getUniformColorThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(UniformColorThemeParams),
    isApplicable: function (ctx) { return true; }
};
//# sourceMappingURL=uniform.js.map

/***/ }),
/* 356 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export UniformSizeThemeParams */
/* unused harmony export getUniformSizeThemeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return UniformSizeTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return UniformSizeThemeProvider; });
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var Description = 'Gives everything the same, uniform size.';
var UniformSizeThemeParams = {
    value: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__["ParamDefinition"].Numeric(1, { min: 0, max: 20, step: 0.1 }),
};
function getUniformSizeThemeParams(ctx) {
    return UniformSizeThemeParams; // TODO return copy
}
function UniformSizeTheme(ctx, props) {
    var size = props.value;
    return {
        factory: UniformSizeTheme,
        granularity: 'uniform',
        size: function () { return size; },
        props: props,
        description: Description
    };
}
var UniformSizeThemeProvider = {
    name: 'uniform',
    label: 'Uniform',
    category: '',
    factory: UniformSizeTheme,
    getParams: getUniformSizeThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_0__["ParamDefinition"].getDefaultValues(UniformSizeThemeParams),
    isApplicable: function (ctx) { return true; }
};
//# sourceMappingURL=uniform.js.map

/***/ }),
/* 357 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return decode; });
/* harmony import */ var _utf8__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(157);
/*
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from https://github.com/rcsb/mmtf-javascript
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function decode(buffer) {
    return parse({ buffer: buffer, offset: 0, dataView: new DataView(buffer.buffer) });
}
/**
 * decode all key-value pairs of a map into an object
 */
function map(state, length) {
    var value = {};
    for (var i = 0; i < length; i++) {
        var key = parse(state);
        value[key] = parse(state);
    }
    return value;
}
/**
 * decode binary array
 */
function bin(state, length) {
    // This approach to binary parsing wastes a bit of memory to trade for speed compared to:
    //
    //   let value = buffer.subarray(offset, offset + length); //new Uint8Array(buffer.buffer, offset, length);
    //
    // It turns out that using the view created by subarray probably uses DataView
    // in the background, which causes the element access to be several times slower
    // than creating the new byte array.
    var value = new Uint8Array(length);
    var o = state.offset;
    for (var i = 0; i < length; i++)
        value[i] = state.buffer[i + o];
    state.offset += length;
    return value;
}
/**
 * decode string
 */
function str(state, length) {
    var value = Object(_utf8__WEBPACK_IMPORTED_MODULE_0__[/* utf8Read */ "b"])(state.buffer, state.offset, length);
    state.offset += length;
    return value;
}
/**
 * decode array
 */
function array(state, length) {
    var value = new Array(length);
    for (var i = 0; i < length; i++) {
        value[i] = parse(state);
    }
    return value;
}
/**
 * recursively parse the MessagePack data and return decoded MessagePack data
 */
function parse(state) {
    var type = state.buffer[state.offset];
    var value, length;
    // Positive FixInt
    if ((type & 0x80) === 0x00) {
        state.offset++;
        return type;
    }
    // FixMap
    if ((type & 0xf0) === 0x80) {
        length = type & 0x0f;
        state.offset++;
        return map(state, length);
    }
    // FixArray
    if ((type & 0xf0) === 0x90) {
        length = type & 0x0f;
        state.offset++;
        return array(state, length);
    }
    // FixStr
    if ((type & 0xe0) === 0xa0) {
        length = type & 0x1f;
        state.offset++;
        return str(state, length);
    }
    // Negative FixInt
    if ((type & 0xe0) === 0xe0) {
        value = state.dataView.getInt8(state.offset);
        state.offset++;
        return value;
    }
    switch (type) {
        // nil
        case 0xc0:
            state.offset++;
            return null;
        // false
        case 0xc2:
            state.offset++;
            return false;
        // true
        case 0xc3:
            state.offset++;
            return true;
        // bin 8
        case 0xc4:
            length = state.dataView.getUint8(state.offset + 1);
            state.offset += 2;
            return bin(state, length);
        // bin 16
        case 0xc5:
            length = state.dataView.getUint16(state.offset + 1);
            state.offset += 3;
            return bin(state, length);
        // bin 32
        case 0xc6:
            length = state.dataView.getUint32(state.offset + 1);
            state.offset += 5;
            return bin(state, length);
        // float 32
        case 0xca:
            value = state.dataView.getFloat32(state.offset + 1);
            state.offset += 5;
            return value;
        // float 64
        case 0xcb:
            value = state.dataView.getFloat64(state.offset + 1);
            state.offset += 9;
            return value;
        // uint8
        case 0xcc:
            value = state.buffer[state.offset + 1];
            state.offset += 2;
            return value;
        // uint 16
        case 0xcd:
            value = state.dataView.getUint16(state.offset + 1);
            state.offset += 3;
            return value;
        // uint 32
        case 0xce:
            value = state.dataView.getUint32(state.offset + 1);
            state.offset += 5;
            return value;
        // int 8
        case 0xd0:
            value = state.dataView.getInt8(state.offset + 1);
            state.offset += 2;
            return value;
        // int 16
        case 0xd1:
            value = state.dataView.getInt16(state.offset + 1);
            state.offset += 3;
            return value;
        // int 32
        case 0xd2:
            value = state.dataView.getInt32(state.offset + 1);
            state.offset += 5;
            return value;
        // str 8
        case 0xd9:
            length = state.dataView.getUint8(state.offset + 1);
            state.offset += 2;
            return str(state, length);
        // str 16
        case 0xda:
            length = state.dataView.getUint16(state.offset + 1);
            state.offset += 3;
            return str(state, length);
        // str 32
        case 0xdb:
            length = state.dataView.getUint32(state.offset + 1);
            state.offset += 5;
            return str(state, length);
        // array 16
        case 0xdc:
            length = state.dataView.getUint16(state.offset + 1);
            state.offset += 3;
            return array(state, length);
        // array 32
        case 0xdd:
            length = state.dataView.getUint32(state.offset + 1);
            state.offset += 5;
            return array(state, length);
        // map 16:
        case 0xde:
            length = state.dataView.getUint16(state.offset + 1);
            state.offset += 3;
            return map(state, length);
        // map 32
        case 0xdf:
            length = state.dataView.getUint32(state.offset + 1);
            state.offset += 5;
            return map(state, length);
    }
    throw new Error('Unknown type 0x' + type.toString(16));
}
//# sourceMappingURL=decode.js.map

/***/ }),
/* 358 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return SecondaryStructure; });
/**
 * Copyright (c) 2017-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
function SecondaryStructure(type, key, elements, getIndex) {
    return { type: type, key: key, elements: elements, getIndex: getIndex };
}

//# sourceMappingURL=seconday-structure.js.map

/***/ }),
/* 359 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return mmCIF_residueId_schema; });
/* unused harmony export mmCIF_chemCompBond_schema */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return mmCIF_chemComp_schema; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mmcif__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(57);
/* harmony import */ var _mol_data_db__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(7);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var mmCIF_residueId_schema = {
    label_comp_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_comp_id,
    label_seq_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_seq_id,
    pdbx_PDB_ins_code: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.pdbx_PDB_ins_code,
    label_asym_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_asym_id,
    label_entity_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.label_entity_id,
    auth_comp_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_atom_id,
    auth_seq_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_seq_id,
    auth_asym_id: _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].atom_site.auth_asym_id
};
var mmCIF_chemCompBond_schema = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].chem_comp_bond), {
    /** Indicates if the bond entry was taken from the protonation variant dictionary */
    molstar_protonation_variant: _mol_data_db__WEBPACK_IMPORTED_MODULE_2__["Column"].Schema.Str() });
/** Has `type` extended with 'Ion' and 'Lipid' */
var mmCIF_chemComp_schema = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mmcif__WEBPACK_IMPORTED_MODULE_1__[/* mmCIF_Schema */ "a"].chem_comp), { type: _mol_data_db__WEBPACK_IMPORTED_MODULE_2__["Column"].Schema.Aliased(_mol_data_db__WEBPACK_IMPORTED_MODULE_2__["Column"].Schema.str) });
//# sourceMappingURL=mmcif-extras.js.map

/***/ }),
/* 360 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ShapeGroupSizeThemeParams */
/* unused harmony export getShapeGroupSizeThemeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ShapeGroupSizeTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ShapeGroupSizeThemeProvider; });
/* harmony import */ var _mol_model_shape__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(49);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var DefaultSize = 1;
var Description = 'Assigns sizes as defined by the shape object.';
var ShapeGroupSizeThemeParams = {};
function getShapeGroupSizeThemeParams(ctx) {
    return ShapeGroupSizeThemeParams; // TODO return copy
}
function ShapeGroupSizeTheme(ctx, props) {
    return {
        factory: ShapeGroupSizeTheme,
        granularity: 'groupInstance',
        size: function (location) {
            if (_mol_model_shape__WEBPACK_IMPORTED_MODULE_0__[/* ShapeGroup */ "b"].isLocation(location)) {
                return location.shape.getSize(location.group, location.instance);
            }
            return DefaultSize;
        },
        props: props,
        description: Description
    };
}
var ShapeGroupSizeThemeProvider = {
    name: 'shape-group',
    label: 'Shape Group',
    category: '',
    factory: ShapeGroupSizeTheme,
    getParams: getShapeGroupSizeThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(ShapeGroupSizeThemeParams),
    isApplicable: function (ctx) { return !!ctx.shape; }
};
//# sourceMappingURL=shape-group.js.map

/***/ }),
/* 361 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ShapeGroupColorThemeParams */
/* unused harmony export getShapeGroupColorThemeParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ShapeGroupColorTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return ShapeGroupColorThemeProvider; });
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(24);
/* harmony import */ var _mol_model_shape__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(49);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DefaultColor = Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_0__["Color"])(0xCCCCCC);
var Description = 'Assigns colors as defined by the shape object.';
var ShapeGroupColorThemeParams = {};
function getShapeGroupColorThemeParams(ctx) {
    return ShapeGroupColorThemeParams; // TODO return copy
}
function ShapeGroupColorTheme(ctx, props) {
    return {
        factory: ShapeGroupColorTheme,
        granularity: 'groupInstance',
        color: function (location) {
            if (_mol_model_shape__WEBPACK_IMPORTED_MODULE_1__[/* ShapeGroup */ "b"].isLocation(location)) {
                return location.shape.getColor(location.group, location.instance);
            }
            return DefaultColor;
        },
        props: props,
        description: Description
    };
}
var ShapeGroupColorThemeProvider = {
    name: 'shape-group',
    label: 'Shape Group',
    category: "Miscellaneous" /* Misc */,
    factory: ShapeGroupColorTheme,
    getParams: getShapeGroupColorThemeParams,
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_2__["ParamDefinition"].getDefaultValues(ShapeGroupColorThemeParams),
    isApplicable: function (ctx) { return !!ctx.shape; }
};
//# sourceMappingURL=shape-group.js.map

/***/ }),
/* 362 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export getTarget */
/* unused harmony export getFormat */
/* unused harmony export getInternalFormat */
/* unused harmony export getType */
/* unused harmony export getFilter */
/* unused harmony export getAttachment */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return createTexture; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return createTextures; });
/* harmony import */ var _mol_util_id_factory__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(96);
/* harmony import */ var _compat__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(91);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var getNextTextureId = Object(_mol_util_id_factory__WEBPACK_IMPORTED_MODULE_0__[/* idFactory */ "a"])();
function getTarget(gl, kind) {
    switch (kind) {
        case 'image-uint8': return gl.TEXTURE_2D;
        case 'image-float32': return gl.TEXTURE_2D;
        case 'image-depth': return gl.TEXTURE_2D;
    }
    if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl)) {
        switch (kind) {
            case 'volume-uint8': return gl.TEXTURE_3D;
            case 'volume-float32': return gl.TEXTURE_3D;
        }
    }
    throw new Error("unknown texture kind '" + kind + "'");
}
function getFormat(gl, format, type) {
    switch (format) {
        case 'alpha':
            if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl) && type === 'float')
                return gl.RED;
            else
                return gl.ALPHA;
        case 'rgb': return gl.RGB;
        case 'rgba': return gl.RGBA;
        case 'depth': return gl.DEPTH_COMPONENT;
    }
}
function getInternalFormat(gl, format, type) {
    if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl)) {
        switch (format) {
            case 'alpha':
                switch (type) {
                    case 'ubyte': return gl.ALPHA;
                    case 'float': return gl.R32F;
                }
            case 'rgb':
                switch (type) {
                    case 'ubyte': return gl.RGB;
                    case 'float': return gl.RGB32F;
                }
            case 'rgba':
                switch (type) {
                    case 'ubyte': return gl.RGBA;
                    case 'float': return gl.RGBA32F;
                }
            case 'depth':
                return gl.DEPTH_COMPONENT16;
        }
    }
    return getFormat(gl, format, type);
}
function getType(gl, type) {
    switch (type) {
        case 'ubyte': return gl.UNSIGNED_BYTE;
        case 'ushort': return gl.UNSIGNED_SHORT;
        case 'float': return gl.FLOAT;
    }
}
function getFilter(gl, type) {
    switch (type) {
        case 'nearest': return gl.NEAREST;
        case 'linear': return gl.LINEAR;
    }
}
function getAttachment(gl, extensions, attachment) {
    switch (attachment) {
        case 'depth': return gl.DEPTH_ATTACHMENT;
        case 'stencil': return gl.STENCIL_ATTACHMENT;
        case 'color0':
        case 0: return gl.COLOR_ATTACHMENT0;
    }
    if (extensions.drawBuffers) {
        switch (attachment) {
            case 'color1':
            case 1: return extensions.drawBuffers.COLOR_ATTACHMENT1;
            case 'color2':
            case 2: return extensions.drawBuffers.COLOR_ATTACHMENT2;
            case 'color3':
            case 3: return extensions.drawBuffers.COLOR_ATTACHMENT3;
            case 'color4':
            case 4: return extensions.drawBuffers.COLOR_ATTACHMENT4;
            case 'color5':
            case 5: return extensions.drawBuffers.COLOR_ATTACHMENT5;
            case 'color6':
            case 6: return extensions.drawBuffers.COLOR_ATTACHMENT6;
            case 'color7':
            case 7: return extensions.drawBuffers.COLOR_ATTACHMENT7;
        }
    }
    throw new Error('unknown texture attachment');
}
function isTexture2d(x, target, gl) {
    return target === gl.TEXTURE_2D;
}
function isTexture3d(x, target, gl) {
    return target === gl.TEXTURE_3D;
}
function getTexture(gl) {
    var texture = gl.createTexture();
    if (texture === null) {
        throw new Error('Could not create WebGL texture');
    }
    return texture;
}
// export type TextureProps = { kind: TextureKind, format: TextureFormat, type: TextureType, filter: TextureFilter }
function createTexture(gl, extensions, kind, _format, _type, _filter) {
    var id = getNextTextureId();
    var texture = getTexture(gl);
    // check texture kind and type compatability
    if ((kind.endsWith('float32') && _type !== 'float') ||
        (kind.endsWith('uint8') && _type !== 'ubyte') ||
        (kind.endsWith('depth') && _type !== 'ushort')) {
        throw new Error("texture kind '" + kind + "' and type '" + _type + "' are incompatible");
    }
    var target = getTarget(gl, kind);
    var filter = getFilter(gl, _filter);
    var format = getFormat(gl, _format, _type);
    var internalFormat = getInternalFormat(gl, _format, _type);
    var type = getType(gl, _type);
    function init() {
        gl.bindTexture(target, texture);
        gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, filter);
        gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, filter);
        // clamp-to-edge needed for non-power-of-two textures in webgl
        gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
        gl.bindTexture(target, null);
    }
    init();
    var fba = undefined;
    var width = 0, height = 0, depth = 0;
    var loadedData;
    var destroyed = false;
    function define(_width, _height, _depth) {
        width = _width, height = _height, depth = _depth || 0;
        gl.bindTexture(target, texture);
        if (target === gl.TEXTURE_2D) {
            gl.texImage2D(target, 0, internalFormat, width, height, 0, format, type, null);
        }
        else if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl) && target === gl.TEXTURE_3D && depth !== undefined) {
            gl.texImage3D(target, 0, internalFormat, width, height, depth, 0, format, type, null);
        }
        else {
            throw new Error('unknown texture target');
        }
    }
    function load(data) {
        gl.bindTexture(target, texture);
        // unpack alignment of 1 since we use textures only for data
        gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
        gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
        gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
        if (isTexture2d(data, target, gl)) {
            gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
            width = data.width, height = data.height;
            gl.texImage2D(target, 0, internalFormat, width, height, 0, format, type, data.array);
        }
        else if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl) && isTexture3d(data, target, gl)) {
            width = data.width, height = data.height, depth = data.depth;
            gl.texImage3D(target, 0, internalFormat, width, height, depth, 0, format, type, data.array);
        }
        else {
            throw new Error('unknown texture target');
        }
        gl.bindTexture(target, null);
        loadedData = data;
    }
    function attachFramebuffer(framebuffer, attachment, layer) {
        if (fba && fba.framebuffer === framebuffer && fba.attachment === attachment && fba.layer === layer) {
            return;
        }
        framebuffer.bind();
        if (target === gl.TEXTURE_2D) {
            gl.framebufferTexture2D(gl.FRAMEBUFFER, getAttachment(gl, extensions, attachment), gl.TEXTURE_2D, texture, 0);
        }
        else if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl) && target === gl.TEXTURE_3D) {
            if (layer === undefined)
                throw new Error('need `layer` to attach 3D texture');
            gl.framebufferTextureLayer(gl.FRAMEBUFFER, getAttachment(gl, extensions, attachment), texture, 0, layer);
        }
        else {
            throw new Error('unknown texture target');
        }
        fba = { framebuffer: framebuffer, attachment: attachment, layer: layer };
    }
    return {
        id: id,
        target: target,
        format: format,
        internalFormat: internalFormat,
        type: type,
        getWidth: function () { return width; },
        getHeight: function () { return height; },
        getDepth: function () { return depth; },
        define: define,
        load: load,
        bind: function (id) {
            gl.activeTexture(gl.TEXTURE0 + id);
            gl.bindTexture(target, texture);
        },
        unbind: function (id) {
            gl.activeTexture(gl.TEXTURE0 + id);
            gl.bindTexture(target, null);
        },
        attachFramebuffer: attachFramebuffer,
        detachFramebuffer: function (framebuffer, attachment) {
            framebuffer.bind();
            if (target === gl.TEXTURE_2D) {
                gl.framebufferTexture2D(gl.FRAMEBUFFER, getAttachment(gl, extensions, attachment), gl.TEXTURE_2D, null, 0);
            }
            else if (Object(_compat__WEBPACK_IMPORTED_MODULE_1__[/* isWebGL2 */ "m"])(gl) && target === gl.TEXTURE_3D) {
                gl.framebufferTextureLayer(gl.FRAMEBUFFER, getAttachment(gl, extensions, attachment), null, 0, 0);
            }
            else {
                throw new Error('unknown texture target');
            }
            fba = undefined;
        },
        reset: function () {
            texture = getTexture(gl);
            init();
            if (loadedData) {
                load(loadedData);
            }
            else {
                define(width, height, depth);
            }
            if (fba) {
                // TODO unclear why calling `attachFramebuffer` here does not work reliably after context loss
                // e.g. it still needs to be called in `DrawPass` to work
                fba = undefined;
            }
        },
        destroy: function () {
            if (destroyed)
                return;
            gl.deleteTexture(texture);
            destroyed = true;
        }
    };
}
function createTextures(ctx, schema, values) {
    var resources = ctx.resources;
    var textures = [];
    Object.keys(schema).forEach(function (k) {
        var spec = schema[k];
        if (spec.type === 'texture') {
            if (spec.kind === 'texture') {
                textures[textures.length] = [k, values[k].ref.value];
            }
            else {
                var texture = resources.texture(spec.kind, spec.format, spec.dataType, spec.filter);
                texture.load(values[k].ref.value);
                textures[textures.length] = [k, texture];
            }
        }
    });
    return textures;
}
//# sourceMappingURL=texture.js.map

/***/ }),
/* 363 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return volumeFromDensityServerData; });
/* unused harmony export DscifFormat */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(11);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(65);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





function volumeFromDensityServerData(source) {
    var _this = this;
    return _mol_task__WEBPACK_IMPORTED_MODULE_1__[/* Task */ "b"].create('Create Volume', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var info, values, cell, axis_order_fast_to_slow, normalizeOrder, sample_count, tensorSpace, data, origin, dimensions;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            info = source.volume_data_3d_info, values = source.volume_data_3d;
            cell = _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* SpacegroupCell */ "f"].create(info.spacegroup_number.value(0), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].ofArray(info.spacegroup_cell_size.value(0)), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].scale(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].zero(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].ofArray(info.spacegroup_cell_angles.value(0)), Math.PI / 180));
            axis_order_fast_to_slow = info.axis_order.value(0);
            normalizeOrder = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Tensor"].convertToCanonicalAxisIndicesFastToSlow(axis_order_fast_to_slow);
            sample_count = normalizeOrder(info.sample_count.value(0));
            tensorSpace = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Tensor"].Space(sample_count, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Tensor"].invertAxisOrder(axis_order_fast_to_slow), Float32Array);
            data = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Tensor"].create(tensorSpace, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Tensor"].Data1(values.values.toArray({ array: Float32Array })));
            origin = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].ofArray(normalizeOrder(info.origin.value(0)));
            dimensions = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].ofArray(normalizeOrder(info.dimensions.value(0)));
            return [2 /*return*/, {
                    grid: {
                        transform: { kind: 'spacegroup', cell: cell, fractionalBox: _mol_math_geometry__WEBPACK_IMPORTED_MODULE_2__[/* Box3D */ "b"].create(origin, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].add(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].zero(), origin, dimensions)) },
                        cells: data,
                        stats: {
                            min: info.min_sampled.value(0),
                            max: info.max_sampled.value(0),
                            mean: info.mean_sampled.value(0),
                            sigma: info.sigma_sampled.value(0)
                        },
                    },
                    sourceData: DscifFormat.create(source),
                    customProperties: new _mol_model_custom_property__WEBPACK_IMPORTED_MODULE_4__["CustomProperties"](),
                    _propertyData: Object.create(null),
                }];
        });
    }); });
}
//

var DscifFormat;
(function (DscifFormat) {
    function is(x) {
        return x.kind === 'dscif';
    }
    DscifFormat.is = is;
    function create(dscif) {
        return { kind: 'dscif', name: dscif._name, data: dscif };
    }
    DscifFormat.create = create;
})(DscifFormat || (DscifFormat = {}));
//# sourceMappingURL=density-server.js.map

/***/ }),
/* 364 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PluginStateSnapshotManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(102);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(immutable__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _component__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(118);
/* harmony import */ var _mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(157);
/* harmony import */ var _mol_util_zip_zip__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(317);
/* harmony import */ var _mol_util_data_source__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(177);
/* harmony import */ var _mol_util_object__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(85);
/* harmony import */ var _mol_plugin_version__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(314);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var PluginStateSnapshotManager = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PluginStateSnapshotManager, _super);
    function PluginStateSnapshotManager(plugin) {
        var _this = _super.call(this, {
            current: void 0,
            entries: Object(immutable__WEBPACK_IMPORTED_MODULE_1__["List"])(),
            isPlaying: false,
            nextSnapshotDelayInMs: PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
        }) || this;
        _this.plugin = plugin;
        _this.entryMap = new Map();
        _this.events = {
            changed: _this.ev()
        };
        _this.timeoutHandle = void 0;
        _this.next = function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
            var next, snapshot, delay;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.timeoutHandle = void 0;
                        next = this.getNextId(this.state.current, 1);
                        if (!next || next === this.state.current) {
                            this.stop();
                            return [2 /*return*/];
                        }
                        snapshot = this.setCurrent(next);
                        return [4 /*yield*/, this.plugin.state.setSnapshot(snapshot)];
                    case 1:
                        _a.sent();
                        delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
                        if (this.state.isPlaying)
                            this.timeoutHandle = setTimeout(this.next, delay);
                        return [2 /*return*/];
                }
            });
        }); };
        return _this;
        // TODO make nextSnapshotDelayInMs editable
    }
    PluginStateSnapshotManager.prototype.getIndex = function (e) {
        return this.state.entries.indexOf(e);
    };
    PluginStateSnapshotManager.prototype.getEntry = function (id) {
        if (!id)
            return;
        return this.entryMap.get(id);
    };
    PluginStateSnapshotManager.prototype.remove = function (id) {
        var e = this.entryMap.get(id);
        if (!e)
            return;
        this.entryMap.delete(id);
        this.updateState({
            current: this.state.current === id ? void 0 : this.state.current,
            entries: this.state.entries.delete(this.getIndex(e))
        });
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.add = function (e) {
        this.entryMap.set(e.snapshot.id, e);
        this.updateState({ current: e.snapshot.id, entries: this.state.entries.push(e) });
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.replace = function (id, snapshot) {
        var old = this.getEntry(id);
        if (!old)
            return;
        var idx = this.getIndex(old);
        // The id changes here!
        var e = PluginStateSnapshotManager.Entry(snapshot, {
            name: old.name,
            description: old.description
        });
        this.entryMap.set(snapshot.id, e);
        this.updateState({ current: e.snapshot.id, entries: this.state.entries.set(idx, e) });
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.move = function (id, dir) {
        var len = this.state.entries.size;
        if (len < 2)
            return;
        var e = this.getEntry(id);
        if (!e)
            return;
        var from = this.getIndex(e);
        var to = (from + dir) % len;
        if (to < 0)
            to += len;
        var f = this.state.entries.get(to);
        var entries = this.state.entries.asMutable();
        entries.set(to, e);
        entries.set(from, f);
        this.updateState({ current: e.snapshot.id, entries: entries.asImmutable() });
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.clear = function () {
        if (this.state.entries.size === 0)
            return;
        this.entryMap.clear();
        this.updateState({ current: void 0, entries: Object(immutable__WEBPACK_IMPORTED_MODULE_1__["List"])() });
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.setCurrent = function (id) {
        var e = this.getEntry(id);
        if (e) {
            this.updateState({ current: id });
            this.events.changed.next();
        }
        return e && e.snapshot;
    };
    PluginStateSnapshotManager.prototype.getNextId = function (id, dir) {
        var len = this.state.entries.size;
        if (!id) {
            if (len === 0)
                return void 0;
            var idx_1 = dir === -1 ? len - 1 : 0;
            return this.state.entries.get(idx_1).snapshot.id;
        }
        var e = this.getEntry(id);
        if (!e)
            return;
        var idx = this.getIndex(e);
        if (idx < 0)
            return;
        idx = (idx + dir) % len;
        if (idx < 0)
            idx += len;
        return this.state.entries.get(idx).snapshot.id;
    };
    PluginStateSnapshotManager.prototype.setStateSnapshot = function (snapshot) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var entries, _i, _a, e, current, entry, next;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (snapshot.version !== _mol_plugin_version__WEBPACK_IMPORTED_MODULE_7__[/* PLUGIN_VERSION */ "a"]) {
                            // TODO
                            // console.warn('state snapshot version mismatch');
                        }
                        this.clear();
                        entries = Object(immutable__WEBPACK_IMPORTED_MODULE_1__["List"])().asMutable();
                        for (_i = 0, _a = snapshot.entries; _i < _a.length; _i++) {
                            e = _a[_i];
                            this.entryMap.set(e.snapshot.id, e);
                            entries.push(e);
                        }
                        current = snapshot.current
                            ? snapshot.current
                            : snapshot.entries.length > 0
                                ? snapshot.entries[0].snapshot.id
                                : void 0;
                        this.updateState({
                            current: current,
                            entries: entries.asImmutable(),
                            isPlaying: false,
                            nextSnapshotDelayInMs: snapshot.playback ? snapshot.playback.nextSnapshotDelayInMs : PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs
                        });
                        this.events.changed.next();
                        if (!current)
                            return [2 /*return*/];
                        entry = this.getEntry(current);
                        next = entry && entry.snapshot;
                        if (!next)
                            return [2 /*return*/];
                        return [4 /*yield*/, this.plugin.state.setSnapshot(next)];
                    case 1:
                        _b.sent();
                        if (snapshot.playback && snapshot.playback.isPlaying)
                            this.play(true);
                        return [2 /*return*/, next];
                }
            });
        });
    };
    PluginStateSnapshotManager.prototype.syncCurrent = function (options) {
        var snapshot = this.plugin.state.getSnapshot(options === null || options === void 0 ? void 0 : options.params);
        if (this.state.entries.size === 0 || !this.state.current) {
            this.add(PluginStateSnapshotManager.Entry(snapshot, { name: options === null || options === void 0 ? void 0 : options.name, description: options === null || options === void 0 ? void 0 : options.description }));
        }
        else {
            this.replace(this.state.current, snapshot);
        }
    };
    PluginStateSnapshotManager.prototype.getStateSnapshot = function (options) {
        // TODO: diffing and all that fancy stuff
        this.syncCurrent(options);
        return {
            timestamp: +new Date(),
            version: _mol_plugin_version__WEBPACK_IMPORTED_MODULE_7__[/* PLUGIN_VERSION */ "a"],
            name: options && options.name,
            description: options && options.description,
            current: this.state.current,
            playback: {
                isPlaying: !!(options && options.playOnLoad),
                nextSnapshotDelayInMs: this.state.nextSnapshotDelayInMs
            },
            entries: this.state.entries.valueSeq().toArray()
        };
    };
    PluginStateSnapshotManager.prototype.serialize = function (options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var json, state, zipDataObj, assets, _i, _a, _b, asset, file, _c, _d, _e, index, data, zipFile;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        json = JSON.stringify(this.getStateSnapshot({ params: options === null || options === void 0 ? void 0 : options.params }), null, 2);
                        if (!(!(options === null || options === void 0 ? void 0 : options.type) || options.type === 'json' || options.type === 'molj')) return [3 /*break*/, 1];
                        return [2 /*return*/, new Blob([json], { type: 'application/json;charset=utf-8' })];
                    case 1:
                        state = new Uint8Array(Object(_mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__[/* utf8ByteCount */ "a"])(json));
                        Object(_mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__[/* utf8Write */ "c"])(state, 0, json);
                        zipDataObj = {
                            'state.json': state
                        };
                        assets = [];
                        _i = 0, _a = this.plugin.managers.asset.assets;
                        _f.label = 2;
                    case 2:
                        if (!(_i < _a.length)) return [3 /*break*/, 5];
                        _b = _a[_i], asset = _b.asset, file = _b.file;
                        assets.push([asset.id, asset]);
                        _c = zipDataObj;
                        _d = "assets/" + asset.id;
                        _e = Uint8Array.bind;
                        return [4 /*yield*/, file.arrayBuffer()];
                    case 3:
                        _c[_d] = new (_e.apply(Uint8Array, [void 0, _f.sent()]))();
                        _f.label = 4;
                    case 4:
                        _i++;
                        return [3 /*break*/, 2];
                    case 5:
                        if (assets.length > 0) {
                            index = JSON.stringify(assets, null, 2);
                            data = new Uint8Array(Object(_mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__[/* utf8ByteCount */ "a"])(index));
                            Object(_mol_io_common_utf8__WEBPACK_IMPORTED_MODULE_3__[/* utf8Write */ "c"])(data, 0, index);
                            zipDataObj['assets.json'] = data;
                        }
                        zipFile = Object(_mol_util_zip_zip__WEBPACK_IMPORTED_MODULE_4__[/* zip */ "c"])(zipDataObj);
                        return [2 /*return*/, new Blob([zipFile], { type: 'application/zip' })];
                }
            });
        });
    };
    PluginStateSnapshotManager.prototype.open = function (file) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var fn, data, snapshot, data, assets_1, stateFile, stateData, file_1, json, _a, _b, _i, json_1, _c, id, asset, snapshot, e_1;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        _d.trys.push([0, 8, , 9]);
                        fn = file.name.toLowerCase();
                        if (!(fn.endsWith('json') || fn.endsWith('molj'))) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.plugin.runTask(Object(_mol_util_data_source__WEBPACK_IMPORTED_MODULE_5__[/* readFromFile */ "c"])(file, 'string'))];
                    case 1:
                        data = _d.sent();
                        snapshot = JSON.parse(data);
                        if (PluginStateSnapshotManager.isStateSnapshot(snapshot)) {
                            return [2 /*return*/, this.setStateSnapshot(snapshot)];
                        }
                        else if (PluginStateSnapshotManager.isStateSnapshot(snapshot.data)) {
                            return [2 /*return*/, this.setStateSnapshot(snapshot.data)];
                        }
                        else {
                            this.plugin.state.setSnapshot(snapshot);
                        }
                        return [3 /*break*/, 7];
                    case 2: return [4 /*yield*/, this.plugin.runTask(Object(_mol_util_data_source__WEBPACK_IMPORTED_MODULE_5__[/* readFromFile */ "c"])(file, 'zip'))];
                    case 3:
                        data = _d.sent();
                        assets_1 = Object.create(null);
                        Object(_mol_util_object__WEBPACK_IMPORTED_MODULE_6__[/* objectForEach */ "c"])(data, function (v, k) {
                            if (k === 'state.json' || k === 'assets.json')
                                return;
                            var name = k.substring(k.indexOf('/') + 1);
                            assets_1[name] = new File([v], name);
                        });
                        stateFile = new File([data['state.json']], 'state.json');
                        return [4 /*yield*/, this.plugin.runTask(Object(_mol_util_data_source__WEBPACK_IMPORTED_MODULE_5__[/* readFromFile */ "c"])(stateFile, 'string'))];
                    case 4:
                        stateData = _d.sent();
                        if (!data['assets.json']) return [3 /*break*/, 6];
                        file_1 = new File([data['assets.json']], 'assets.json');
                        _b = (_a = JSON).parse;
                        return [4 /*yield*/, this.plugin.runTask(Object(_mol_util_data_source__WEBPACK_IMPORTED_MODULE_5__[/* readFromFile */ "c"])(file_1, 'string'))];
                    case 5:
                        json = _b.apply(_a, [_d.sent()]);
                        for (_i = 0, json_1 = json; _i < json_1.length; _i++) {
                            _c = json_1[_i], id = _c[0], asset = _c[1];
                            this.plugin.managers.asset.set(asset, assets_1[id]);
                        }
                        _d.label = 6;
                    case 6:
                        snapshot = JSON.parse(stateData);
                        return [2 /*return*/, this.setStateSnapshot(snapshot)];
                    case 7: return [3 /*break*/, 9];
                    case 8:
                        e_1 = _d.sent();
                        this.plugin.log.error("Reading state: " + e_1);
                        return [3 /*break*/, 9];
                    case 9: return [2 /*return*/];
                }
            });
        });
    };
    PluginStateSnapshotManager.prototype.play = function (delayFirst) {
        if (delayFirst === void 0) { delayFirst = false; }
        this.updateState({ isPlaying: true });
        if (delayFirst) {
            var e = this.getEntry(this.state.current);
            if (!e) {
                this.next();
                return;
            }
            this.events.changed.next();
            var snapshot = e.snapshot;
            var delay = typeof snapshot.durationInMs !== 'undefined' ? snapshot.durationInMs : this.state.nextSnapshotDelayInMs;
            this.timeoutHandle = setTimeout(this.next, delay);
        }
        else {
            this.next();
        }
    };
    PluginStateSnapshotManager.prototype.stop = function () {
        this.updateState({ isPlaying: false });
        if (typeof this.timeoutHandle !== 'undefined')
            clearTimeout(this.timeoutHandle);
        this.timeoutHandle = void 0;
        this.events.changed.next();
    };
    PluginStateSnapshotManager.prototype.togglePlay = function () {
        if (this.state.isPlaying) {
            this.stop();
            this.plugin.managers.animation.stop();
        }
        else {
            this.play();
        }
    };
    PluginStateSnapshotManager.DefaultNextSnapshotDelayInMs = 1500;
    return PluginStateSnapshotManager;
}(_component__WEBPACK_IMPORTED_MODULE_2__[/* StatefulPluginComponent */ "b"]));
(function (PluginStateSnapshotManager) {
    function Entry(snapshot, params) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({ timestamp: +new Date(), snapshot: snapshot }, params);
    }
    PluginStateSnapshotManager.Entry = Entry;
    function isStateSnapshot(x) {
        var s = x;
        return !!s && !!s.timestamp && !!s.entries;
    }
    PluginStateSnapshotManager.isStateSnapshot = isStateSnapshot;
})(PluginStateSnapshotManager || (PluginStateSnapshotManager = {}));
//# sourceMappingURL=snapshots.js.map

/***/ }),
/* 365 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export readCcp4Header */
/* unused harmony export readCcp4Slices */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return getCcp4ValueType; });
/* unused harmony export getCcp4DataOffset */
/* unused harmony export parseFile */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return parse; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_task__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(16);
/* harmony import */ var _result__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(67);
/* harmony import */ var _common_file_handle__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(366);
/* harmony import */ var _mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(192);
/* harmony import */ var _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(193);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






function readCcp4Header(file) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var headerSize, buffer, MAP, MACHST, littleEndian, modeLE, readInt, readFloat, header;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    headerSize = 1024;
                    return [4 /*yield*/, file.readBuffer(0, headerSize)];
                case 1:
                    buffer = (_a.sent()).buffer;
                    MAP = String.fromCharCode(buffer.readUInt8(52 * 4), buffer.readUInt8(52 * 4 + 1), buffer.readUInt8(52 * 4 + 2), buffer.readUInt8(52 * 4 + 3));
                    if (MAP !== 'MAP ') {
                        throw new Error('ccp4 format error, missing "MAP " string');
                    }
                    MACHST = [buffer.readUInt8(53 * 4), buffer.readUInt8(53 * 4 + 1)];
                    littleEndian = false;
                    if (MACHST[0] === 68 && MACHST[1] === 65) {
                        littleEndian = true;
                    }
                    else if (MACHST[0] === 17 && MACHST[1] === 17) {
                        littleEndian = false;
                    }
                    else {
                        modeLE = buffer.readInt32LE(3 * 4);
                        if (modeLE <= 16)
                            littleEndian = true;
                    }
                    readInt = littleEndian ? function (o) { return buffer.readInt32LE(o * 4); } : function (o) { return buffer.readInt32BE(o * 4); };
                    readFloat = littleEndian ? function (o) { return buffer.readFloatLE(o * 4); } : function (o) { return buffer.readFloatBE(o * 4); };
                    header = {
                        NC: readInt(0),
                        NR: readInt(1),
                        NS: readInt(2),
                        MODE: readInt(3),
                        NCSTART: readInt(4),
                        NRSTART: readInt(5),
                        NSSTART: readInt(6),
                        NX: readInt(7),
                        NY: readInt(8),
                        NZ: readInt(9),
                        xLength: readFloat(10),
                        yLength: readFloat(11),
                        zLength: readFloat(12),
                        alpha: readFloat(13),
                        beta: readFloat(14),
                        gamma: readFloat(15),
                        MAPC: readInt(16),
                        MAPR: readInt(17),
                        MAPS: readInt(18),
                        AMIN: readFloat(19),
                        AMAX: readFloat(20),
                        AMEAN: readFloat(21),
                        ISPG: readInt(22),
                        NSYMBT: readInt(23),
                        LSKFLG: readInt(24),
                        SKWMAT: [],
                        SKWTRN: [],
                        userFlag1: readInt(39),
                        userFlag2: readInt(40),
                        // bytes 50-52 origin in X,Y,Z used for transforms
                        originX: readFloat(49),
                        originY: readFloat(50),
                        originZ: readFloat(51),
                        MAP: MAP,
                        MACHST: MACHST,
                        ARMS: readFloat(54),
                    };
                    return [2 /*return*/, { header: header, littleEndian: littleEndian }];
            }
        });
    });
}
function readCcp4Slices(header, buffer, file, byteOffset, length, littleEndian) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var valueByteOffset, int8, b1, b0, j, jl;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!isMapmode2to0(header)) return [3 /*break*/, 2];
                    valueByteOffset = 3 * length;
                    // read int8 data to last quarter of the read buffer
                    return [4 /*yield*/, file.readBuffer(byteOffset, buffer.readBuffer, length, valueByteOffset)];
                case 1:
                    // read int8 data to last quarter of the read buffer
                    _a.sent();
                    int8 = new Int8Array(buffer.valuesBuffer.buffer, valueByteOffset);
                    b1 = (header.AMAX - header.AMIN) / 255.0;
                    b0 = 0.5 * (header.AMIN + header.AMAX + b1);
                    for (j = 0, jl = length; j < jl; ++j) {
                        buffer.values[j] = b1 * int8[j] + b0;
                    }
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, Object(_mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* readTypedArray */ "d"])(buffer, file, byteOffset, length, 0, littleEndian)];
                case 3:
                    _a.sent();
                    _a.label = 4;
                case 4: return [2 /*return*/];
            }
        });
    });
}
function getCcp4DataType(mode) {
    switch (mode) {
        case 0: return _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* TypedArrayValueType */ "a"].Int8;
        case 1: return _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* TypedArrayValueType */ "a"].Int16;
        case 2: return _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* TypedArrayValueType */ "a"].Float32;
        case 3: throw new Error('mode 3 unsupported, complex 16-bit integers');
        case 4: throw new Error('mode 4 unsupported, complex 32-bit reals');
        case 6: _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* TypedArrayValueType */ "a"].Uint16;
        case 16: throw new Error('mode 16 unsupported, unsigned char * 3 (for rgb data, non-standard)');
    }
    throw new Error("unknown mode '" + mode + "'");
}
/** check if the file was converted by mapmode2to0, see https://github.com/uglymol/uglymol */
function isMapmode2to0(header) {
    return header.userFlag1 === -128 && header.userFlag2 === 127;
}
function getCcp4ValueType(header) {
    return isMapmode2to0(header) ? _mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* TypedArrayValueType */ "a"].Float32 : getCcp4DataType(header.MODE);
}
function getCcp4DataOffset(header) {
    return 256 * 4 + header.NSYMBT;
}
function parseInternal(file, size, ctx) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var _a, header, littleEndian, offset, dataType, valueType, count, elementByteSize, byteCount, buffer, result;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, ctx.update({ message: 'Parsing CCP4/MRC/MAP file...' })];
                case 1:
                    _b.sent();
                    return [4 /*yield*/, readCcp4Header(file)];
                case 2:
                    _a = _b.sent(), header = _a.header, littleEndian = _a.littleEndian;
                    offset = getCcp4DataOffset(header);
                    dataType = getCcp4DataType(header.MODE);
                    valueType = getCcp4ValueType(header);
                    count = header.NC * header.NR * header.NS;
                    elementByteSize = Object(_mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* getElementByteSize */ "c"])(dataType);
                    byteCount = count * elementByteSize;
                    buffer = Object(_mol_io_common_typed_array__WEBPACK_IMPORTED_MODULE_5__[/* createTypedArrayBufferContext */ "b"])(count, valueType);
                    readCcp4Slices(header, buffer, file, offset, byteCount, littleEndian);
                    result = { header: header, values: buffer.values, name: file.name };
                    return [2 /*return*/, result];
            }
        });
    });
}
function parseFile(file, size) {
    var _this = this;
    return _mol_task__WEBPACK_IMPORTED_MODULE_1__[/* Task */ "b"].create('Parse CCP4/MRC/MAP', function (ctx) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var _a, _b, e_1;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    _c.trys.push([0, 2, , 3]);
                    _b = (_a = _result__WEBPACK_IMPORTED_MODULE_2__[/* ReaderResult */ "a"]).success;
                    return [4 /*yield*/, parseInternal(file, size, ctx)];
                case 1: return [2 /*return*/, _b.apply(_a, [_c.sent()])];
                case 2:
                    e_1 = _c.sent();
                    return [2 /*return*/, _result__WEBPACK_IMPORTED_MODULE_2__[/* ReaderResult */ "a"].error(e_1)];
                case 3: return [2 /*return*/];
            }
        });
    }); });
}
function parse(buffer, name) {
    return parseFile(_common_file_handle__WEBPACK_IMPORTED_MODULE_3__[/* FileHandle */ "a"].fromBuffer(_mol_io_common_simple_buffer__WEBPACK_IMPORTED_MODULE_4__[/* SimpleBuffer */ "a"].fromUint8Array(buffer), name), buffer.length);
}
//# sourceMappingURL=parser.js.map

/***/ }),
/* 366 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return FileHandle; });
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(5);
/* harmony import */ var _simple_buffer__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(192);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


// only import 'fs' in node.js
var fs = typeof document === 'undefined' ? __webpack_require__(432) : void 0;
var FileHandle;
(function (FileHandle) {
    function fromBuffer(buffer, name) {
        return {
            name: name,
            readBuffer: function (position, sizeOrBuffer, size, byteOffset) {
                var bytesRead;
                var outBuffer;
                if (typeof sizeOrBuffer === 'number') {
                    size = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(size, sizeOrBuffer);
                    var start = position;
                    var end = Math.min(buffer.length, start + size);
                    bytesRead = end - start;
                    outBuffer = _simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].fromUint8Array(new Uint8Array(buffer.buffer, start, end - start));
                }
                else {
                    size = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(size, sizeOrBuffer.length);
                    var start = position;
                    var end = Math.min(buffer.length, start + size);
                    sizeOrBuffer.set(buffer.subarray(start, end), byteOffset);
                    bytesRead = end - start;
                    outBuffer = sizeOrBuffer;
                }
                if (size !== bytesRead) {
                    console.warn("byteCount " + size + " and bytesRead " + bytesRead + " differ");
                }
                return Promise.resolve({ bytesRead: bytesRead, buffer: outBuffer });
            },
            writeBuffer: function (position, buffer, length) {
                length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, buffer.length);
                console.error('.writeBuffer not implemented for FileHandle.fromBuffer');
                return Promise.resolve(0);
            },
            writeBufferSync: function (position, buffer, length) {
                length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, buffer.length);
                console.error('.writeSync not implemented for FileHandle.fromBuffer');
                return 0;
            },
            close: _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* noop */ "k"]
        };
    }
    FileHandle.fromBuffer = fromBuffer;
    function fromDescriptor(file, name) {
        if (fs === undefined)
            throw new Error('fs module not available');
        return {
            name: name,
            readBuffer: function (position, sizeOrBuffer, length, byteOffset) {
                return new Promise(function (res, rej) {
                    var outBuffer;
                    if (typeof sizeOrBuffer === 'number') {
                        byteOffset = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(byteOffset, 0);
                        length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, sizeOrBuffer);
                        outBuffer = _simple_buffer__WEBPACK_IMPORTED_MODULE_1__[/* SimpleBuffer */ "a"].fromArrayBuffer(new ArrayBuffer(sizeOrBuffer));
                    }
                    else {
                        byteOffset = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(byteOffset, 0);
                        length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, sizeOrBuffer.length);
                        outBuffer = sizeOrBuffer;
                    }
                    fs.read(file, outBuffer, byteOffset, length, position, function (err, bytesRead, buffer) {
                        if (err) {
                            rej(err);
                            return;
                        }
                        if (length !== bytesRead) {
                            console.warn("byteCount " + length + " and bytesRead " + bytesRead + " differ");
                        }
                        res({ bytesRead: bytesRead, buffer: buffer });
                    });
                });
            },
            writeBuffer: function (position, buffer, length) {
                length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, buffer.length);
                return new Promise(function (res, rej) {
                    fs.write(file, buffer, 0, length, position, function (err, written) {
                        if (err)
                            rej(err);
                        else
                            res(written);
                    });
                });
            },
            writeBufferSync: function (position, buffer, length) {
                length = Object(_mol_util__WEBPACK_IMPORTED_MODULE_0__[/* defaults */ "i"])(length, buffer.length);
                return fs.writeSync(file, buffer, 0, length, position);
            },
            close: function () {
                try {
                    if (file !== void 0)
                        fs.close(file, _mol_util__WEBPACK_IMPORTED_MODULE_0__[/* noop */ "k"]);
                }
                catch (e) {
                }
            }
        };
    }
    FileHandle.fromDescriptor = fromDescriptor;
})(FileHandle || (FileHandle = {}));
//# sourceMappingURL=file-handle.js.map

/***/ }),
/* 367 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export MmcifProvider */
/* unused harmony export CifCoreProvider */
/* unused harmony export PdbProvider */
/* unused harmony export GroProvider */
/* unused harmony export Provider3dg */
/* unused harmony export MolProvider */
/* unused harmony export Mol2Provider */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BuiltInTrajectoryFormats; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _transforms__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(28);
/* harmony import */ var _provider__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(179);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var Category = 'Trajectory';
function defaultVisuals(plugin, data) {
    return plugin.builders.structure.hierarchy.applyPreset(data.trajectory, 'default');
}
var MmcifProvider = {
    label: 'mmCIF',
    description: 'mmCIF',
    category: Category,
    stringExtensions: ['cif', 'mmcif', 'mcif'],
    binaryExtensions: ['bcif'],
    isApplicable: function (info, data) {
        if (info.ext === 'mmcif' || info.ext === 'mcif')
            return true;
        // assume undetermined cif/bcif files are mmCIF
        if (info.ext === 'cif' || info.ext === 'bcif')
            return Object(_provider__WEBPACK_IMPORTED_MODULE_2__[/* guessCifVariant */ "b"])(info, data) === -1;
        return false;
    },
    parse: function (plugin, data, params) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(void 0, void 0, void 0, function () {
        var state, cif, trajectory;
        var _a, _b;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    state = plugin.state.data;
                    cif = state.build().to(data)
                        .apply(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Data.ParseCif, void 0, { state: { isGhost: true } });
                    return [4 /*yield*/, cif
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromMmCif, void 0, { tags: params === null || params === void 0 ? void 0 : params.trajectoryTags })
                            .commit({ revertOnError: true })];
                case 1:
                    trajectory = _c.sent();
                    if ((((_b = (_a = cif.selector.cell) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data.blocks.length) || 0) > 1) {
                        plugin.state.data.updateCellState(cif.ref, { isGhost: false });
                    }
                    return [2 /*return*/, { trajectory: trajectory }];
            }
        });
    }); },
    visuals: defaultVisuals
};
var CifCoreProvider = {
    label: 'cifCore',
    description: 'CIF Core',
    category: Category,
    stringExtensions: ['cif'],
    isApplicable: function (info, data) {
        if (info.ext === 'cif')
            return Object(_provider__WEBPACK_IMPORTED_MODULE_2__[/* guessCifVariant */ "b"])(info, data) === 'coreCif';
        return false;
    },
    parse: function (plugin, data, params) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(void 0, void 0, void 0, function () {
        var state, cif, trajectory;
        var _a, _b;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    state = plugin.state.data;
                    cif = state.build().to(data)
                        .apply(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Data.ParseCif, void 0, { state: { isGhost: true } });
                    return [4 /*yield*/, cif
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromCifCore, void 0, { tags: params === null || params === void 0 ? void 0 : params.trajectoryTags })
                            .commit({ revertOnError: true })];
                case 1:
                    trajectory = _c.sent();
                    if ((((_b = (_a = cif.selector.cell) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data.blocks.length) || 0) > 1) {
                        plugin.state.data.updateCellState(cif.ref, { isGhost: false });
                    }
                    return [2 /*return*/, { trajectory: trajectory }];
            }
        });
    }); },
    visuals: defaultVisuals
};
function directTrajectory(transformer) {
    var _this = this;
    return function (plugin, data, params) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
        var state, trajectory;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    state = plugin.state.data;
                    return [4 /*yield*/, state.build().to(data)
                            .apply(transformer, void 0, { tags: params === null || params === void 0 ? void 0 : params.trajectoryTags })
                            .commit({ revertOnError: true })];
                case 1:
                    trajectory = _a.sent();
                    return [2 /*return*/, { trajectory: trajectory }];
            }
        });
    }); };
}
var PdbProvider = {
    label: 'PDB',
    description: 'PDB',
    category: Category,
    stringExtensions: ['pdb', 'ent'],
    parse: directTrajectory(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromPDB),
    visuals: defaultVisuals
};
var GroProvider = {
    label: 'GRO',
    description: 'GRO',
    category: Category,
    stringExtensions: ['gro'],
    binaryExtensions: [],
    parse: directTrajectory(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromGRO),
    visuals: defaultVisuals
};
var Provider3dg = {
    label: '3DG',
    description: '3DG',
    category: Category,
    stringExtensions: ['3dg'],
    parse: directTrajectory(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFrom3DG),
    visuals: defaultVisuals
};
var MolProvider = {
    label: 'MOL/SDF',
    description: 'MOL/SDF',
    category: Category,
    stringExtensions: ['mol', 'sdf', 'sd'],
    parse: directTrajectory(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromMOL),
    visuals: defaultVisuals
};
var Mol2Provider = {
    label: 'MOL2',
    description: 'MOL2',
    category: Category,
    stringExtensions: ['mol2'],
    parse: directTrajectory(_transforms__WEBPACK_IMPORTED_MODULE_1__["StateTransforms"].Model.TrajectoryFromMOL2),
    visuals: defaultVisuals
};
var BuiltInTrajectoryFormats = [
    ['mmcif', MmcifProvider],
    ['cifCore', CifCoreProvider],
    ['pdb', PdbProvider],
    ['gro', GroProvider],
    ['3dg', Provider3dg],
    ['mol', MolProvider],
    ['mol2', Mol2Provider],
];
//# sourceMappingURL=trajectory.js.map

/***/ }),
/* 368 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "setStructureOverpaint", function() { return setStructureOverpaint; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "clearStructureOverpaint", function() { return clearStructureOverpaint; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(28);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(13);
/* harmony import */ var _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(130);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(24);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(23);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var OverpaintManagerTag = 'overpaint-controls';
function setStructureOverpaint(plugin, components, color, lociGetter, types) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var _this = this;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, eachRepr(plugin, components, function (update, repr, overpaintCell) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                        var structure, loci, layer, bundleLayers, filtered, filtered;
                        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (types && types.length > 0 && !types.includes(repr.params.values.type.name))
                                        return [2 /*return*/];
                                    structure = repr.obj.data.source.data;
                                    return [4 /*yield*/, lociGetter(structure.root)];
                                case 1:
                                    loci = _a.sent();
                                    if (_mol_model_loci__WEBPACK_IMPORTED_MODULE_6__["Loci"].isEmpty(loci))
                                        return [2 /*return*/];
                                    layer = {
                                        bundle: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Bundle.fromLoci(loci),
                                        color: color === -1 ? Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_5__["Color"])(0) : color,
                                        clear: color === -1
                                    };
                                    if (overpaintCell) {
                                        bundleLayers = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(overpaintCell.params.values.layers, [layer]);
                                        filtered = getFilteredBundle(bundleLayers, structure);
                                        update.to(overpaintCell).update(_mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__[/* Overpaint */ "a"].toBundle(filtered));
                                    }
                                    else {
                                        filtered = getFilteredBundle([layer], structure);
                                        update.to(repr.transform.ref)
                                            .apply(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_2__["StateTransforms"].Representation.OverpaintStructureRepresentation3DFromBundle, _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__[/* Overpaint */ "a"].toBundle(filtered), { tags: OverpaintManagerTag });
                                    }
                                    return [2 /*return*/];
                            }
                        });
                    }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function clearStructureOverpaint(plugin, components, types) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var _this = this;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, eachRepr(plugin, components, function (update, repr, overpaintCell) { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(_this, void 0, void 0, function () {
                        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                            if (types && types.length > 0 && !types.includes(repr.params.values.type.name))
                                return [2 /*return*/];
                            if (overpaintCell) {
                                update.delete(overpaintCell.transform.ref);
                            }
                            return [2 /*return*/];
                        });
                    }); })];
                case 1:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
function eachRepr(plugin, components, callback) {
    return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
        var state, update, _i, components_1, c, _a, _b, r, overpaint;
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    state = plugin.state.data;
                    update = state.build();
                    _i = 0, components_1 = components;
                    _c.label = 1;
                case 1:
                    if (!(_i < components_1.length)) return [3 /*break*/, 6];
                    c = components_1[_i];
                    _a = 0, _b = c.representations;
                    _c.label = 2;
                case 2:
                    if (!(_a < _b.length)) return [3 /*break*/, 5];
                    r = _b[_a];
                    overpaint = state.select(_mol_state__WEBPACK_IMPORTED_MODULE_3__["StateSelection"].Generators.ofTransformer(_mol_plugin_state_transforms__WEBPACK_IMPORTED_MODULE_2__["StateTransforms"].Representation.OverpaintStructureRepresentation3DFromBundle, r.cell.transform.ref).withTag(OverpaintManagerTag));
                    return [4 /*yield*/, callback(update, r.cell, overpaint[0])];
                case 3:
                    _c.sent();
                    _c.label = 4;
                case 4:
                    _a++;
                    return [3 /*break*/, 2];
                case 5:
                    _i++;
                    return [3 /*break*/, 1];
                case 6: return [2 /*return*/, update.commit({ doNotUpdateCurrent: true })];
            }
        });
    });
}
/** filter overpaint layers for given structure */
function getFilteredBundle(layers, structure) {
    var overpaint = _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__[/* Overpaint */ "a"].ofBundle(layers, structure.root);
    var merged = _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__[/* Overpaint */ "a"].merge(overpaint);
    return _mol_theme_overpaint__WEBPACK_IMPORTED_MODULE_4__[/* Overpaint */ "a"].filter(merged, structure);
}
//# sourceMappingURL=structure-overpaint.js.map

/***/ }),
/* 369 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return StructureMeasurementManager; });
/* unused harmony export MeasurementGroupTag */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return StructureMeasurementParams; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(13);
/* harmony import */ var _transforms__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(28);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
/* harmony import */ var _mol_util_array__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(29);
/* harmony import */ var _component__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(118);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(2);
/* harmony import */ var _mol_repr_shape_loci_common__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(221);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */










var MeasurementGroupTag = 'measurement-group';
var StructureMeasurementParams = {
    distanceUnitLabel: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].Text('\u212B', { isEssential: true }),
    textColor: _mol_repr_shape_loci_common__WEBPACK_IMPORTED_MODULE_8__[/* MeasurementRepresentationCommonTextParams */ "a"].textColor
};
var DefaultStructureMeasurementOptions = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_7__["ParamDefinition"].getDefaultValues(StructureMeasurementParams);
var StructureMeasurementManager = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StructureMeasurementManager, _super);
    function StructureMeasurementManager(plugin) {
        var _this = _super.call(this, { labels: [], distances: [], angles: [], dihedrals: [], orientations: [], options: DefaultStructureMeasurementOptions }) || this;
        _this.plugin = plugin;
        _this.behaviors = {
            state: _this.ev.behavior(_this.state)
        };
        _this._empty = [];
        plugin.state.data.events.changed.subscribe(function (e) {
            if (e.inTransaction || plugin.behaviors.state.isAnimating.value)
                return;
            _this.sync();
        });
        plugin.behaviors.state.isAnimating.subscribe(function (isAnimating) {
            if (!isAnimating && !plugin.behaviors.state.isUpdating.value)
                _this.sync();
        });
        return _this;
    }
    StructureMeasurementManager.prototype.stateUpdated = function () {
        this.behaviors.state.next(this.state);
    };
    StructureMeasurementManager.prototype.getGroup = function () {
        var state = this.plugin.state.data;
        var groupRef = _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateSelection"].findTagInSubtree(state.tree, _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateTransform"].RootRef, MeasurementGroupTag);
        var builder = this.plugin.state.data.build();
        if (groupRef)
            return builder.to(groupRef);
        return builder.toRoot().group(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Misc.CreateGroup, { label: "Measurements" }, { tags: MeasurementGroupTag });
    };
    StructureMeasurementManager.prototype.setOptions = function (options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var update, _i, _a, cell, _b, _c, cell, _d, _e, cell, _f, _g, cell;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_h) {
                switch (_h.label) {
                    case 0:
                        if (this.updateState({ options: options }))
                            this.stateUpdated();
                        update = this.plugin.state.data.build();
                        for (_i = 0, _a = this.state.distances; _i < _a.length; _i++) {
                            cell = _a[_i];
                            update.to(cell).update(function (old) {
                                old.unitLabel = options.distanceUnitLabel;
                                old.textColor = options.textColor;
                            });
                        }
                        for (_b = 0, _c = this.state.labels; _b < _c.length; _b++) {
                            cell = _c[_b];
                            update.to(cell).update(function (old) { old.textColor = options.textColor; });
                        }
                        for (_d = 0, _e = this.state.angles; _d < _e.length; _d++) {
                            cell = _e[_d];
                            update.to(cell).update(function (old) { old.textColor = options.textColor; });
                        }
                        for (_f = 0, _g = this.state.dihedrals; _f < _g.length; _f++) {
                            cell = _g[_f];
                            update.to(cell).update(function (old) { old.textColor = options.textColor; });
                        }
                        if (update.editInfo.count === 0)
                            return [2 /*return*/];
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: this.plugin.state.data, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _h.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.addDistance = function (a, b, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cellA, cellB, dependsOn, update, state;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cellA = this.plugin.helpers.substructureParent.get(a.structure);
                        cellB = this.plugin.helpers.substructureParent.get(b.structure);
                        if (!cellA || !cellB)
                            return [2 /*return*/];
                        dependsOn = [cellA.transform.ref];
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellB.transform.ref);
                        update = this.getGroup();
                        update
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Model.MultiStructureSelectionFromExpression, {
                            selections: [
                                { key: 'a', groupId: 'a', ref: cellA.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(a) },
                                { key: 'b', groupId: 'b', ref: cellB.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(b) }
                            ],
                            isTransitive: true,
                            label: 'Distance'
                        }, { dependsOn: dependsOn, tags: options === null || options === void 0 ? void 0 : options.selectionTags })
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsDistance3D, {
                            customText: (options === null || options === void 0 ? void 0 : options.customText) || '',
                            unitLabel: this.state.options.distanceUnitLabel,
                            textColor: this.state.options.textColor
                        }, { tags: options === null || options === void 0 ? void 0 : options.reprTags });
                        state = this.plugin.state.data;
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.addAngle = function (a, b, c, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cellA, cellB, cellC, dependsOn, update, state;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cellA = this.plugin.helpers.substructureParent.get(a.structure);
                        cellB = this.plugin.helpers.substructureParent.get(b.structure);
                        cellC = this.plugin.helpers.substructureParent.get(c.structure);
                        if (!cellA || !cellB || !cellC)
                            return [2 /*return*/];
                        dependsOn = [cellA.transform.ref];
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellB.transform.ref);
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellC.transform.ref);
                        update = this.getGroup();
                        update
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Model.MultiStructureSelectionFromExpression, {
                            selections: [
                                { key: 'a', ref: cellA.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(a) },
                                { key: 'b', ref: cellB.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(b) },
                                { key: 'c', ref: cellC.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(c) }
                            ],
                            isTransitive: true,
                            label: 'Angle'
                        }, { dependsOn: dependsOn, tags: options === null || options === void 0 ? void 0 : options.selectionTags })
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsAngle3D, {
                            customText: (options === null || options === void 0 ? void 0 : options.customText) || '',
                            textColor: this.state.options.textColor
                        }, { tags: options === null || options === void 0 ? void 0 : options.reprTags });
                        state = this.plugin.state.data;
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.addDihedral = function (a, b, c, d, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cellA, cellB, cellC, cellD, dependsOn, update, state;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cellA = this.plugin.helpers.substructureParent.get(a.structure);
                        cellB = this.plugin.helpers.substructureParent.get(b.structure);
                        cellC = this.plugin.helpers.substructureParent.get(c.structure);
                        cellD = this.plugin.helpers.substructureParent.get(d.structure);
                        if (!cellA || !cellB || !cellC || !cellD)
                            return [2 /*return*/];
                        dependsOn = [cellA.transform.ref];
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellB.transform.ref);
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellC.transform.ref);
                        Object(_mol_util_array__WEBPACK_IMPORTED_MODULE_5__["arraySetAdd"])(dependsOn, cellD.transform.ref);
                        update = this.getGroup();
                        update
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Model.MultiStructureSelectionFromExpression, {
                            selections: [
                                { key: 'a', ref: cellA.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(a) },
                                { key: 'b', ref: cellB.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(b) },
                                { key: 'c', ref: cellC.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(c) },
                                { key: 'd', ref: cellD.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(d) }
                            ],
                            isTransitive: true,
                            label: 'Dihedral'
                        }, { dependsOn: dependsOn, tags: options === null || options === void 0 ? void 0 : options.selectionTags })
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsDihedral3D, {
                            customText: (options === null || options === void 0 ? void 0 : options.customText) || '',
                            textColor: this.state.options.textColor
                        }, { tags: options === null || options === void 0 ? void 0 : options.reprTags });
                        state = this.plugin.state.data;
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.addLabel = function (a, options) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cellA, dependsOn, update, state;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cellA = this.plugin.helpers.substructureParent.get(a.structure);
                        if (!cellA)
                            return [2 /*return*/];
                        dependsOn = [cellA.transform.ref];
                        update = this.getGroup();
                        update
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Model.MultiStructureSelectionFromExpression, {
                            selections: [
                                { key: 'a', ref: cellA.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(a) },
                            ],
                            isTransitive: true,
                            label: 'Label'
                        }, { dependsOn: dependsOn, tags: options === null || options === void 0 ? void 0 : options.selectionTags })
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsLabel3D, {
                            textColor: this.state.options.textColor
                        }, { tags: options === null || options === void 0 ? void 0 : options.reprTags });
                        state = this.plugin.state.data;
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.addOrientation = function (a) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            var cellA, dependsOn, update, state;
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        cellA = this.plugin.helpers.substructureParent.get(a.structure);
                        if (!cellA)
                            return [2 /*return*/];
                        dependsOn = [cellA.transform.ref];
                        update = this.getGroup();
                        update
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Model.MultiStructureSelectionFromExpression, {
                            selections: [
                                { key: 'a', ref: cellA.transform.ref, expression: _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Loci.toExpression(a) },
                            ],
                            isTransitive: true,
                            label: 'Orientation'
                        }, { dependsOn: dependsOn })
                            .apply(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsOrientation3D);
                        state = this.plugin.state.data;
                        return [4 /*yield*/, _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    StructureMeasurementManager.prototype.getTransforms = function (transformer) {
        var state = this.plugin.state.data;
        var groupRef = _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateSelection"].findTagInSubtree(state.tree, _mol_state__WEBPACK_IMPORTED_MODULE_2__["StateTransform"].RootRef, MeasurementGroupTag);
        var ret = groupRef ? state.select(_mol_state__WEBPACK_IMPORTED_MODULE_2__["StateSelection"].Generators.ofTransformer(transformer, groupRef)) : this._empty;
        if (ret.length === 0)
            return this._empty;
        return ret;
    };
    StructureMeasurementManager.prototype.sync = function () {
        var updated = this.updateState({
            labels: this.getTransforms(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsLabel3D),
            distances: this.getTransforms(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsDistance3D),
            angles: this.getTransforms(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsAngle3D),
            dihedrals: this.getTransforms(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsDihedral3D),
            orientations: this.getTransforms(_transforms__WEBPACK_IMPORTED_MODULE_3__["StateTransforms"].Representation.StructureSelectionsOrientation3D)
        });
        if (updated)
            this.stateUpdated();
    };
    return StructureMeasurementManager;
}(_component__WEBPACK_IMPORTED_MODULE_6__[/* StatefulPluginComponent */ "b"]));
//# sourceMappingURL=measurement.js.map

/***/ }),
/* 370 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return InteractivityManager; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(23);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(4);
/* harmony import */ var _mol_repr_representation__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(40);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(45);
/* harmony import */ var _mol_util_object__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(85);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(2);
/* harmony import */ var _component__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(118);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */









// TODO: make this customizable somewhere?
var DefaultInteractivityFocusOptions = {
    minRadius: 6,
    extraRadius: 6,
    durationMs: 250,
};
var InteractivityManager = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InteractivityManager, _super);
    function InteractivityManager(plugin, props) {
        if (props === void 0) { props = {}; }
        var _this = _super.call(this, { props: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].getDefaultValues(InteractivityManager.Params)), props) }) || this;
        _this.plugin = plugin;
        _this._props = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].getDefaultValues(InteractivityManager.Params);
        _this.events = {
            propsUpdated: _this.ev()
        };
        _this.lociSelects = new InteractivityManager.LociSelectManager(plugin, _this._props);
        _this.lociHighlights = new InteractivityManager.LociHighlightManager(plugin, _this._props);
        return _this;
    }
    Object.defineProperty(InteractivityManager.prototype, "props", {
        get: function () { return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.state.props); },
        enumerable: false,
        configurable: true
    });
    InteractivityManager.prototype.setProps = function (props) {
        var old = this.props;
        var _new = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.state.props), props);
        if (Object(_mol_util_object__WEBPACK_IMPORTED_MODULE_5__[/* shallowEqual */ "d"])(old, _new))
            return;
        this.updateState({ props: _new });
        this.lociSelects.setProps(_new);
        this.lociHighlights.setProps(_new);
        this.events.propsUpdated.next();
    };
    return InteractivityManager;
}(_component__WEBPACK_IMPORTED_MODULE_7__[/* StatefulPluginComponent */ "b"]));
(function (InteractivityManager) {
    InteractivityManager.Params = {
        granularity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].Select('residue', _mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["Loci"].GranularityOptions, { label: 'Picking Level', description: 'Controls if selections are expanded upon picking to whole residues, chains, structures, instances, or left as atoms and coarse elements' }),
    };
    var LociMarkManager = /** @class */ (function () {
        function LociMarkManager(ctx, props) {
            if (props === void 0) { props = {}; }
            this.ctx = ctx;
            this.providers = [];
            this.props = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_6__["ParamDefinition"].getDefaultValues(InteractivityManager.Params);
            this.sel = ctx.managers.structure.selection;
            this.setProps(props);
        }
        LociMarkManager.prototype.setProps = function (props) {
            Object.assign(this.props, props);
        };
        LociMarkManager.prototype.addProvider = function (provider) {
            this.providers.push(provider);
        };
        LociMarkManager.prototype.removeProvider = function (provider) {
            this.providers = this.providers.filter(function (p) { return p !== provider; });
            // TODO clear, then re-apply remaining providers
        };
        LociMarkManager.prototype.normalizedLoci = function (reprLoci, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var loci = reprLoci.loci, repr = reprLoci.repr;
            var granularity = applyGranularity ? this.props.granularity : undefined;
            return { loci: _mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["Loci"].normalize(loci, granularity), repr: repr };
        };
        LociMarkManager.prototype.mark = function (current, action) {
            for (var _i = 0, _a = this.providers; _i < _a.length; _i++) {
                var p = _a[_i];
                p(current, action);
            }
        };
        return LociMarkManager;
    }());
    InteractivityManager.LociMarkManager = LociMarkManager;
    //
    var LociHighlightManager = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LociHighlightManager, _super);
        function LociHighlightManager() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.prev = [];
            _this.clearHighlights = function () {
                for (var _i = 0, _a = _this.prev; _i < _a.length; _i++) {
                    var p = _a[_i];
                    _this.mark(p, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].RemoveHighlight);
                }
                _this.prev.length = 0;
            };
            return _this;
        }
        LociHighlightManager.prototype.isHighlighted = function (loci) {
            for (var _i = 0, _a = this.prev; _i < _a.length; _i++) {
                var p = _a[_i];
                if (_mol_repr_representation__WEBPACK_IMPORTED_MODULE_3__[/* Representation */ "a"].Loci.areEqual(p, loci))
                    return true;
            }
            return false;
        };
        LociHighlightManager.prototype.addHighlight = function (loci) {
            this.mark(loci, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Highlight);
            this.prev.push(loci);
        };
        LociHighlightManager.prototype.highlight = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (!this.isHighlighted(normalized)) {
                this.addHighlight(normalized);
            }
        };
        LociHighlightManager.prototype.highlightOnly = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (!this.isHighlighted(normalized)) {
                this.clearHighlights();
                this.addHighlight(normalized);
            }
        };
        LociHighlightManager.prototype.highlightOnlyExtend = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                var loci = {
                    loci: this.sel.tryGetRange(normalized.loci) || normalized.loci,
                    repr: normalized.repr
                };
                if (!this.isHighlighted(loci)) {
                    this.clearHighlights();
                    this.addHighlight(loci);
                }
            }
        };
        return LociHighlightManager;
    }(LociMarkManager));
    InteractivityManager.LociHighlightManager = LociHighlightManager;
    //
    var LociSelectManager = /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LociSelectManager, _super);
        function LociSelectManager() {
            return _super !== null && _super.apply(this, arguments) || this;
        }
        LociSelectManager.prototype.toggle = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            if (_mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["Loci"].isEmpty(current.loci))
                return;
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                this.toggleSel(normalized);
            }
            else {
                _super.prototype.mark.call(this, normalized, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Toggle);
            }
        };
        LociSelectManager.prototype.toggleExtend = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            if (_mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["Loci"].isEmpty(current.loci))
                return;
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                var loci = this.sel.tryGetRange(normalized.loci) || normalized.loci;
                this.toggleSel({ loci: loci, repr: normalized.repr });
            }
        };
        LociSelectManager.prototype.select = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                this.sel.modify('add', normalized.loci);
            }
            this.mark(normalized, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Select);
        };
        LociSelectManager.prototype.selectJoin = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                this.sel.modify('intersect', normalized.loci);
            }
            this.mark(normalized, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Select);
        };
        LociSelectManager.prototype.selectOnly = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                // only deselect for the structure of the given loci
                this.deselect({ loci: _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].toStructureElementLoci(normalized.loci.structure), repr: normalized.repr }, false);
                this.sel.modify('set', normalized.loci);
            }
            this.mark(normalized, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Select);
        };
        LociSelectManager.prototype.deselect = function (current, applyGranularity) {
            if (applyGranularity === void 0) { applyGranularity = true; }
            var normalized = this.normalizedLoci(current, applyGranularity);
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(normalized.loci)) {
                this.sel.modify('remove', normalized.loci);
            }
            this.mark(normalized, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Deselect);
        };
        LociSelectManager.prototype.deselectAll = function () {
            this.sel.clear();
            this.mark({ loci: _mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["EveryLoci"] }, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Deselect);
        };
        LociSelectManager.prototype.deselectAllOnEmpty = function (current) {
            if (Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_1__["isEmptyLoci"])(current.loci))
                this.deselectAll();
        };
        LociSelectManager.prototype.mark = function (current, action) {
            var loci = current.loci;
            if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["StructureElement"].Loci.is(loci)) {
                // do a full deselect/select for the current structure so visuals that are
                // marked with granularity unequal to 'element' and join/intersect operations
                // are handled properly
                _super.prototype.mark.call(this, { loci: _mol_model_structure__WEBPACK_IMPORTED_MODULE_2__["Structure"].Loci(loci.structure) }, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Deselect);
                _super.prototype.mark.call(this, { loci: this.sel.getLoci(loci.structure) }, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Select);
            }
            else {
                _super.prototype.mark.call(this, current, action);
            }
        };
        LociSelectManager.prototype.toggleSel = function (current) {
            if (this.sel.has(current.loci)) {
                this.sel.modify('remove', current.loci);
                this.mark(current, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Deselect);
            }
            else {
                this.sel.modify('add', current.loci);
                this.mark(current, _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_4__[/* MarkerAction */ "a"].Select);
            }
        };
        return LociSelectManager;
    }(LociMarkManager));
    InteractivityManager.LociSelectManager = LociSelectManager;
})(InteractivityManager || (InteractivityManager = {}));
//# sourceMappingURL=interactivity.js.map

/***/ }),
/* 371 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeStreamingControls", function() { return VolumeStreamingControls; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeSourceControls", function() { return VolumeSourceControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mol_plugin_state_manager_structure_hierarchy__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(255);
/* harmony import */ var _mol_plugin_state_manager_volume_hierarchy__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(380);
/* harmony import */ var _mol_plugin_behavior_dynamic_representation__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(223);
/* harmony import */ var _mol_plugin_behavior_dynamic_volume_streaming_behavior__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(160);
/* harmony import */ var _mol_plugin_behavior_dynamic_volume_streaming_transformers__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(300);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(13);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(32);
/* harmony import */ var _controls_action_menu__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(56);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(19);
/* harmony import */ var _state_apply_action__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(310);
/* harmony import */ var _state_update_transform__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(183);
/* harmony import */ var _viewport_help__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(189);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(26);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(14);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var VolumeStreamingControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VolumeStreamingControls, _super);
    function VolumeStreamingControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    VolumeStreamingControls.prototype.defaultState = function () {
        return {
            header: 'Volume Streaming',
            isCollapsed: false,
            isBusy: false,
            isHidden: true,
            brand: { accent: 'cyan', svg: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["BlurOnSvg"] }
        };
    };
    VolumeStreamingControls.prototype.componentDidMount = function () {
        var _this = this;
        // TODO: do not hide this but instead show some help text??
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () {
            _this.setState({
                isHidden: !_this.canEnable(),
                description: _mol_plugin_state_manager_structure_hierarchy__WEBPACK_IMPORTED_MODULE_2__["StructureHierarchyManager"].getSelectedStructuresDescription(_this.plugin)
            });
        });
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (_mol_state__WEBPACK_IMPORTED_MODULE_7__["StateTransform"].hasTag(e.cell.transform, _mol_plugin_behavior_dynamic_volume_streaming_behavior__WEBPACK_IMPORTED_MODULE_5__[/* VolumeStreaming */ "a"].RootTag))
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(VolumeStreamingControls.prototype, "pivot", {
        get: function () {
            return this.plugin.managers.structure.hierarchy.selection.structures[0];
        },
        enumerable: false,
        configurable: true
    });
    VolumeStreamingControls.prototype.canEnable = function () {
        var _a, _b;
        var selection = this.plugin.managers.structure.hierarchy.selection;
        if (selection.structures.length !== 1)
            return false;
        var pivot = this.pivot.cell;
        if (!pivot.obj)
            return false;
        return !!((_b = (_a = _mol_plugin_behavior_dynamic_volume_streaming_transformers__WEBPACK_IMPORTED_MODULE_6__["InitVolumeStreaming"].definition).isApplicable) === null || _b === void 0 ? void 0 : _b.call(_a, pivot.obj, pivot.transform, this.plugin));
    };
    VolumeStreamingControls.prototype.renderEnable = function () {
        var _a;
        var pivot = this.pivot;
        if (!pivot.cell.parent)
            return null;
        var root = _mol_state__WEBPACK_IMPORTED_MODULE_7__["StateSelection"].findTagInSubtree(pivot.cell.parent.tree, this.pivot.cell.transform.ref, _mol_plugin_behavior_dynamic_volume_streaming_behavior__WEBPACK_IMPORTED_MODULE_5__[/* VolumeStreaming */ "a"].RootTag);
        var rootCell = root && pivot.cell.parent.cells.get(root);
        var simpleApply = rootCell && rootCell.status === 'error'
            ? { header: 'Error enabling', icon: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["ErrorSvg"], title: rootCell.errorText }
            : rootCell && ((_a = rootCell.obj) === null || _a === void 0 ? void 0 : _a.data.entries.length) === 0
                ? { header: 'Error enabling', icon: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["ErrorSvg"], title: 'No entry for streaming found' }
                : { header: 'Enable', icon: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["CheckSvg"], title: 'Enable' };
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_state_apply_action__WEBPACK_IMPORTED_MODULE_11__[/* ApplyActionControl */ "a"], { state: pivot.cell.parent, action: _mol_plugin_behavior_dynamic_volume_streaming_transformers__WEBPACK_IMPORTED_MODULE_6__["InitVolumeStreaming"], initiallyCollapsed: true, nodeRef: pivot.cell.transform.ref, simpleApply: simpleApply });
    };
    VolumeStreamingControls.prototype.renderParams = function () {
        var _a, _b, _c, _d, _e;
        var pivot = this.pivot;
        if (!pivot.cell.parent)
            return null;
        var bindings = ((_b = (_a = pivot.volumeStreaming) === null || _a === void 0 ? void 0 : _a.cell.transform.params) === null || _b === void 0 ? void 0 : _b.entry.params.view.name) === 'selection-box' && ((_e = (_d = (_c = this.plugin.state.behaviors.cells.get(_mol_plugin_behavior_dynamic_representation__WEBPACK_IMPORTED_MODULE_4__["FocusLoci"].id)) === null || _c === void 0 ? void 0 : _c.params) === null || _d === void 0 ? void 0 : _d.values) === null || _e === void 0 ? void 0 : _e.bindings);
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_state_update_transform__WEBPACK_IMPORTED_MODULE_12__["UpdateTransformControl"], { state: pivot.cell.parent, transform: pivot.volumeStreaming.cell.transform, customHeader: 'none', noMargin: true }),
            bindings && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["ExpandGroup"], { header: 'Controls Help' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_viewport_help__WEBPACK_IMPORTED_MODULE_13__["BindingsHelp"], { bindings: bindings })));
    };
    VolumeStreamingControls.prototype.renderControls = function () {
        var pivot = this.pivot;
        if (!pivot)
            return null;
        if (!pivot.volumeStreaming)
            return this.renderEnable();
        return this.renderParams();
    };
    return VolumeStreamingControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["CollapsableControls"]));

var VolumeSourceControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VolumeSourceControls, _super);
    function VolumeSourceControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.item = function (ref) {
            var _a;
            var selected = _this.plugin.managers.volume.hierarchy.selection;
            var label = ((_a = ref.cell.obj) === null || _a === void 0 ? void 0 : _a.label) || 'Volume';
            var item = { kind: 'item', label: label || ref.kind, selected: selected === ref, value: ref };
            return item;
        };
        _this.selectCurrent = function (item) {
            _this.toggleHierarchy();
            if (!item)
                return;
            _this.plugin.managers.volume.hierarchy.setCurrent(item.value);
        };
        _this.selectAdd = function (item) {
            if (!item)
                return;
            _this.setState({ show: void 0 });
            item.value();
        };
        _this.toggleHierarchy = function () { return _this.setState({ show: _this.state.show !== 'hierarchy' ? 'hierarchy' : void 0 }); };
        _this.toggleAddRepr = function () { return _this.setState({ show: _this.state.show !== 'add-repr' ? 'add-repr' : void 0 }); };
        return _this;
    }
    VolumeSourceControls.prototype.defaultState = function () {
        return {
            header: 'Volume',
            isCollapsed: false,
            isBusy: false,
            isHidden: true,
            brand: { accent: 'purple', svg: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["BlurOnSvg"] }
        };
    };
    VolumeSourceControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.volume.hierarchy.behaviors.selection, function (sel) {
            _this.setState({ isHidden: sel.hierarchy.volumes.length === 0 });
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(VolumeSourceControls.prototype, "hierarchyItems", {
        get: function () {
            var mng = this.plugin.managers.volume.hierarchy;
            var current = mng.current;
            var ret = [];
            for (var _i = 0, _a = current.volumes; _i < _a.length; _i++) {
                var ref = _a[_i];
                ret.push(this.item(ref));
            }
            return ret;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VolumeSourceControls.prototype, "addActions", {
        get: function () {
            var mng = this.plugin.managers.volume.hierarchy;
            var current = mng.selection;
            var ret = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(_mol_plugin_state_manager_volume_hierarchy__WEBPACK_IMPORTED_MODULE_3__[/* VolumeHierarchyManager */ "a"].getRepresentationTypes(this.plugin, current)
                .map(function (t) { return _controls_action_menu__WEBPACK_IMPORTED_MODULE_9__[/* ActionMenu */ "a"].Item(t[1], function () { return mng.addRepresentation(current, t[0]); }); }));
            return ret;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VolumeSourceControls.prototype, "isEmpty", {
        get: function () {
            var volumes = this.plugin.managers.volume.hierarchy.current.volumes;
            return volumes.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VolumeSourceControls.prototype, "label", {
        get: function () {
            var _a;
            var selected = this.plugin.managers.volume.hierarchy.selection;
            if (!selected)
                return 'Nothing Selected';
            return ((_a = selected === null || selected === void 0 ? void 0 : selected.cell.obj) === null || _a === void 0 ? void 0 : _a.label) || 'Volume';
        },
        enumerable: false,
        configurable: true
    });
    VolumeSourceControls.prototype.renderControls = function () {
        var disabled = this.state.isBusy || this.isEmpty;
        var label = this.label;
        var selected = this.plugin.managers.volume.hierarchy.selection;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row', style: { marginTop: '1px' } },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["Button"], { noOverflow: true, flex: true, onClick: this.toggleHierarchy, disabled: disabled, title: label }, label),
                !this.isEmpty && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["AddSvg"], onClick: this.toggleAddRepr, title: 'Apply a structure presets to the current hierarchy.', toggleState: this.state.show === 'add-repr', disabled: disabled })),
            this.state.show === 'hierarchy' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_9__[/* ActionMenu */ "a"], { items: this.hierarchyItems, onSelect: this.selectCurrent }),
            this.state.show === 'add-repr' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_9__[/* ActionMenu */ "a"], { items: this.addActions, onSelect: this.selectAdd }),
            selected && selected.representations.length > 0 && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginTop: '6px' } }, selected.representations.map(function (r) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](VolumeRepresentationControls, { key: r.cell.transform.ref, representation: r }); })));
    };
    return VolumeSourceControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["CollapsableControls"]));

var VolumeRepresentationControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VolumeRepresentationControls, _super);
    function VolumeRepresentationControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { action: void 0 };
        _this.remove = function () { return _this.plugin.managers.volume.hierarchy.remove([_this.props.representation], true); };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            _this.plugin.managers.volume.hierarchy.toggleVisibility([_this.props.representation]);
        };
        _this.toggleUpdate = function () { return _this.setState({ action: _this.state.action === 'update' ? void 0 : 'update' }); };
        _this.highlight = function (e) {
            e.preventDefault();
            if (!_this.props.representation.cell.parent)
                return;
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_14__["PluginCommands"].Interactivity.Object.Highlight(_this.plugin, { state: _this.props.representation.cell.parent, ref: _this.props.representation.cell.transform.ref });
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_14__["PluginCommands"].Interactivity.ClearHighlights(_this.plugin);
        };
        _this.focus = function () {
            var _a;
            var repr = _this.props.representation;
            var objects = (_a = _this.props.representation.cell.obj) === null || _a === void 0 ? void 0 : _a.data.repr.renderObjects;
            if (repr.cell.state.isHidden)
                _this.plugin.managers.volume.hierarchy.toggleVisibility([_this.props.representation], 'show');
            _this.plugin.managers.camera.focusRenderObjects(objects, { extraRadius: 1 });
        };
        return _this;
    }
    VolumeRepresentationControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (_mol_state__WEBPACK_IMPORTED_MODULE_7__["State"].ObjectEvent.isCell(e, _this.props.representation.cell))
                _this.forceUpdate();
        });
    };
    VolumeRepresentationControls.prototype.render = function () {
        var _a, _b, _c;
        var repr = this.props.representation.cell;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["Button"], { noOverflow: true, className: 'msp-control-button-label', title: ((_a = repr.obj) === null || _a === void 0 ? void 0 : _a.label) + ". Click to focus.", onClick: this.focus, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight, style: { textAlign: 'left' } }, (_b = repr.obj) === null || _b === void 0 ? void 0 :
                    _b.label,
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("small", { className: 'msp-25-lower-contrast-text', style: { float: 'right' } }, (_c = repr.obj) === null || _c === void 0 ? void 0 : _c.description)),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: repr.state.isHidden ? _controls_icons__WEBPACK_IMPORTED_MODULE_15__["VisibilityOffOutlinedSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_15__["VisibilityOutlinedSvg"], toggleState: false, onClick: this.toggleVisible, title: (repr.state.isHidden ? 'Show' : 'Hide') + " component", small: true, className: 'msp-form-control', flex: true }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["DeleteOutlinedSvg"], onClick: this.remove, title: 'Remove', small: true }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_10__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_15__["MoreHorizSvg"], onClick: this.toggleUpdate, title: 'Actions', toggleState: this.state.action === 'update' })),
            this.state.action === 'update' && !!repr.parent && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginBottom: '6px' }, className: 'msp-accent-offset' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_state_update_transform__WEBPACK_IMPORTED_MODULE_12__["UpdateTransformControl"], { state: repr.parent, transform: repr.transform, customHeader: 'none', noMargin: true })));
    };
    return VolumeRepresentationControls;
}(_base__WEBPACK_IMPORTED_MODULE_8__["PurePluginUIComponent"]));
//# sourceMappingURL=volume.js.map

/***/ }),
/* 372 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PluginState; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(13);
/* harmony import */ var _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(8);
/* harmony import */ var _behavior__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(170);
/* harmony import */ var _commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(5);
/* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(151);
/* harmony import */ var rxjs__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(235);
/* harmony import */ var _mol_plugin_state_component__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(118);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */











var PluginState = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(PluginState, _super);
    function PluginState(plugin) {
        var _this = _super.call(this) || this;
        _this.plugin = plugin;
        _this.data = _mol_state__WEBPACK_IMPORTED_MODULE_1__["State"].create(new _mol_plugin_state_objects__WEBPACK_IMPORTED_MODULE_2__[/* PluginStateObject */ "a"].Root({}), { runTask: _this.plugin.runTask, globalContext: _this.plugin });
        _this.behaviors = _mol_state__WEBPACK_IMPORTED_MODULE_1__["State"].create(new _behavior__WEBPACK_IMPORTED_MODULE_3__["PluginBehavior"].Root({}), { runTask: _this.plugin.runTask, globalContext: _this.plugin, rootState: { isLocked: true } });
        _this.events = {
            cell: {
                stateUpdated: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.cell.stateUpdated, _this.behaviors.events.cell.stateUpdated),
                created: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.cell.created, _this.behaviors.events.cell.created),
                removed: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.cell.removed, _this.behaviors.events.cell.removed),
            },
            object: {
                created: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.object.created, _this.behaviors.events.object.created),
                removed: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.object.removed, _this.behaviors.events.object.removed),
                updated: Object(rxjs__WEBPACK_IMPORTED_MODULE_8__[/* merge */ "a"])(_this.data.events.object.updated, _this.behaviors.events.object.updated)
            }
        };
        _this.snapshotParams = _this.ev.behavior(PluginState.DefaultSnapshotParams);
        _this.setSnapshotParams = function (params) {
            _this.snapshotParams.next(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, PluginState.DefaultSnapshotParams), params));
        };
        return _this;
    }
    Object.defineProperty(PluginState.prototype, "animation", {
        get: function () { return this.plugin.managers.animation; },
        enumerable: false,
        configurable: true
    });
    PluginState.prototype.getSnapshot = function (params) {
        var _a, _b;
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, this.snapshotParams.value), params);
        return {
            id: _mol_util__WEBPACK_IMPORTED_MODULE_6__[/* UUID */ "c"].create22(),
            data: p.data ? this.data.getSnapshot() : void 0,
            behaviour: p.behavior ? this.behaviors.getSnapshot() : void 0,
            animation: p.animation ? this.animation.getSnapshot() : void 0,
            startAnimation: p.startAnimation ? !!p.startAnimation : void 0,
            camera: p.camera ? {
                current: this.plugin.canvas3d.camera.getSnapshot(),
                transitionStyle: p.cameraTransition.name,
                transitionDurationInMs: ((_a = p === null || p === void 0 ? void 0 : p.cameraTransition) === null || _a === void 0 ? void 0 : _a.name) === 'animate' ? p.cameraTransition.params.durationInMs : void 0
            } : void 0,
            canvas3d: p.canvas3d ? { props: (_b = this.plugin.canvas3d) === null || _b === void 0 ? void 0 : _b.props } : void 0,
            interactivity: p.interactivity ? { props: this.plugin.managers.interactivity.props } : void 0,
            structureFocus: this.plugin.managers.structure.focus.getSnapshot(),
            durationInMs: p === null || p === void 0 ? void 0 : p.durationInMs
        };
    };
    PluginState.prototype.setSnapshot = function (snapshot) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.animation.stop()];
                    case 1:
                        _a.sent();
                        if (!snapshot.behaviour) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.plugin.runTask(this.behaviors.setSnapshot(snapshot.behaviour))];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        if (!snapshot.data) return [3 /*break*/, 5];
                        return [4 /*yield*/, this.plugin.runTask(this.data.setSnapshot(snapshot.data))];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5:
                        if (!snapshot.canvas3d) return [3 /*break*/, 7];
                        if (!snapshot.canvas3d.props) return [3 /*break*/, 7];
                        return [4 /*yield*/, _commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].Canvas3D.SetSettings(this.plugin, { settings: snapshot.canvas3d.props })];
                    case 6:
                        _a.sent();
                        _a.label = 7;
                    case 7:
                        if (snapshot.interactivity) {
                            if (snapshot.interactivity.props)
                                this.plugin.managers.interactivity.setProps(snapshot.interactivity.props);
                        }
                        if (snapshot.structureFocus) {
                            this.plugin.managers.structure.focus.setSnapshot(snapshot.structureFocus);
                        }
                        if (snapshot.animation) {
                            this.animation.setSnapshot(snapshot.animation);
                        }
                        if (snapshot.camera) {
                            _commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].Camera.Reset(this.plugin, {
                                snapshot: snapshot.camera.current,
                                durationMs: snapshot.camera.transitionStyle === 'animate'
                                    ? snapshot.camera.transitionDurationInMs
                                    : void 0
                            });
                        }
                        if (snapshot.startAnimation) {
                            this.animation.start();
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    PluginState.prototype.updateTransform = function (state, a, params, canUndo) {
        var tree = state.build().to(a).update(params);
        return _commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.Update(this.plugin, { state: state, tree: tree, options: { canUndo: canUndo } });
    };
    PluginState.prototype.updateBehavior = function (behavior, params) {
        var tree = this.behaviors.build();
        if (!this.behaviors.tree.transforms.has(behavior.id)) {
            var defaultParams = behavior.createDefaultParams(void 0, this.plugin);
            tree.to(_behavior__WEBPACK_IMPORTED_MODULE_3__["PluginBehavior"].getCategoryId(behavior)).apply(behavior, Object(immer__WEBPACK_IMPORTED_MODULE_7__[/* produce */ "b"])(defaultParams, params), { ref: behavior.id });
        }
        else {
            tree.to(behavior.id).update(params);
        }
        return this.plugin.runTask(this.behaviors.updateTree(tree));
    };
    PluginState.prototype.dispose = function () {
        this.behaviors.cells.forEach(function (cell) {
            if (_behavior__WEBPACK_IMPORTED_MODULE_3__["PluginBehavior"].Behavior.is(cell.obj)) {
                cell.obj.data.unregister();
            }
        });
        _super.prototype.dispose.call(this);
        this.data.dispose();
        this.behaviors.dispose();
        this.animation.dispose();
    };
    return PluginState;
}(_mol_plugin_state_component__WEBPACK_IMPORTED_MODULE_9__[/* PluginComponent */ "a"]));
(function (PluginState) {
    PluginState.SnapshotParams = {
        durationInMs: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Numeric(1500, { min: 100, max: 15000, step: 100 }, { label: 'Duration in ms' }),
        data: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true),
        behavior: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false),
        animation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true),
        startAnimation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false),
        canvas3d: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true),
        interactivity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true),
        camera: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true),
        cameraTransition: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].MappedStatic('animate', {
            animate: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({
                durationInMs: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Numeric(250, { min: 100, max: 5000, step: 500 }, { label: 'Duration in ms' }),
            }),
            instant: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({})
        }, { options: [['animate', 'Animate'], ['instant', 'Instant']] })
    };
    PluginState.DefaultSnapshotParams = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].getDefaultValues(PluginState.SnapshotParams);
})(PluginState || (PluginState = {}));
//# sourceMappingURL=state.js.map

/***/ }),
/* 373 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isArrayLike; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
//# sourceMappingURL=isArrayLike.js.map


/***/ }),
/* 374 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return subscribeToArray; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
var subscribeToArray = function (array) {
    return function (subscriber) {
        for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) {
            subscriber.next(array[i]);
        }
        subscriber.complete();
    };
};
//# sourceMappingURL=subscribeToArray.js.map


/***/ }),
/* 375 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return isPromise; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function isPromise(value) {
    return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function';
}
//# sourceMappingURL=isPromise.js.map


/***/ }),
/* 376 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateTree", function() { return StateTree; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(169);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(388);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(13);
/* harmony import */ var _mol_state_tree_spine__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(303);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(32);
/* harmony import */ var _controls_action_menu__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(56);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(14);
/* harmony import */ var _apply_action__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(310);
/* harmony import */ var _update_transform__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(183);
/**
 * Copyright (c) 2018 - 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */












var StateTree = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateTree, _super);
    function StateTree() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showActions: true };
        return _this;
    }
    StateTree.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.created, function (e) {
            if (e.cell.transform.parent === _mol_state__WEBPACK_IMPORTED_MODULE_5__["StateTransform"].RootRef)
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.events.cell.removed, function (e) {
            if (e.parent === _mol_state__WEBPACK_IMPORTED_MODULE_5__["StateTransform"].RootRef)
                _this.forceUpdate();
        });
    };
    StateTree.getDerivedStateFromProps = function (props, state) {
        var n = props.state.tree.root.ref;
        var children = props.state.tree.children.get(n);
        var showActions = children.size === 0;
        if (state.showActions === showActions)
            return null;
        return { showActions: showActions };
    };
    StateTree.prototype.render = function () {
        var ref = this.props.state.tree.root.ref;
        if (this.state.showActions) {
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { margin: '10px', cursor: 'default' } },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", null, "Nothing to see here yet."),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("p", null,
                    "Structures and Volumes can be loaded from the ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_10__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_10__["HomeOutlinedSvg"] }),
                    " tab."));
        }
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](StateTreeNode, { cell: this.props.state.cells.get(ref), depth: 0 });
    };
    return StateTree;
}(_base__WEBPACK_IMPORTED_MODULE_7__["PluginUIComponent"]));

var StateTreeNode = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateTreeNode, _super);
    function StateTreeNode() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isCollapsed: !!_this.props.cell.state.isCollapsed,
            isNull: StateTreeNode.isNull(_this.props.cell),
            showLabel: StateTreeNode.showLabel(_this.props.cell)
        };
        return _this;
    }
    StateTreeNode.prototype.is = function (e) {
        return e.ref === this.ref && e.state === this.props.cell.parent;
    };
    Object.defineProperty(StateTreeNode.prototype, "ref", {
        get: function () {
            return this.props.cell.transform.ref;
        },
        enumerable: false,
        configurable: true
    });
    StateTreeNode.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (_this.props.cell === e.cell && _this.is(e) && e.state.cells.has(_this.ref)) {
                if (_this.state.isCollapsed !== !!e.cell.state.isCollapsed
                    || _this.state.isNull !== StateTreeNode.isNull(e.cell)
                    || _this.state.showLabel !== StateTreeNode.showLabel(e.cell)) {
                    _this.forceUpdate();
                }
            }
        });
        this.subscribe(this.plugin.state.events.cell.created, function (e) {
            if (_this.props.cell.parent === e.state && _this.ref === e.cell.transform.parent) {
                _this.forceUpdate();
            }
        });
        this.subscribe(this.plugin.state.events.cell.removed, function (e) {
            if (_this.props.cell.parent === e.state && _this.ref === e.parent) {
                _this.forceUpdate();
            }
        });
    };
    StateTreeNode.getDerivedStateFromProps = function (props, state) {
        var isNull = StateTreeNode.isNull(props.cell);
        var showLabel = StateTreeNode.showLabel(props.cell);
        if (!!props.cell.state.isCollapsed === state.isCollapsed && state.isNull === isNull && state.showLabel === showLabel)
            return null;
        return { isCollapsed: !!props.cell.state.isCollapsed, isNull: isNull, showLabel: showLabel };
    };
    StateTreeNode.hasDecorator = function (cell) {
        var _a;
        var children = cell.parent.tree.children.get(cell.transform.ref);
        if (children.size !== 1)
            return false;
        return !!((_a = cell.parent) === null || _a === void 0 ? void 0 : _a.tree.transforms.get(children.first()).transformer.definition.isDecorator);
    };
    StateTreeNode.isNull = function (cell) {
        return !cell || !cell.parent || cell.obj === _mol_state__WEBPACK_IMPORTED_MODULE_5__["StateObject"].Null || !cell.parent.tree.transforms.has(cell.transform.ref);
    };
    StateTreeNode.showLabel = function (cell) {
        return (cell.transform.ref !== _mol_state__WEBPACK_IMPORTED_MODULE_5__["StateTransform"].RootRef) && (cell.status !== 'ok' || (!cell.state.isGhost && !StateTreeNode.hasDecorator(cell)));
    };
    StateTreeNode.prototype.render = function () {
        var _this = this;
        if (this.state.isNull) {
            return null;
        }
        var cell = this.props.cell;
        var children = cell.parent.tree.children.get(this.ref);
        if (!this.state.showLabel) {
            if (children.size === 0)
                return null;
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null, children.map(function (c) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](StateTreeNode, { cell: cell.parent.cells.get(c), key: c, depth: _this.props.depth }); }));
        }
        var newDepth = this.props.depth + 1;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](StateTreeNodeLabel, { cell: cell, depth: this.props.depth }),
            children.size === 0
                ? void 0
                : react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { display: this.state.isCollapsed ? 'none' : 'block' } }, children.map(function (c) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](StateTreeNode, { cell: cell.parent.cells.get(c), key: c, depth: newDepth }); })));
    };
    return StateTreeNode;
}(_base__WEBPACK_IMPORTED_MODULE_7__["PluginUIComponent"]));
var StateTreeNodeLabel = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateTreeNodeLabel, _super);
    function StateTreeNodeLabel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isCurrent: _this.props.cell.parent.current === _this.ref,
            isCollapsed: !!_this.props.cell.state.isCollapsed,
            action: void 0,
            currentAction: void 0
        };
        _this.setCurrent = function (e) {
            e === null || e === void 0 ? void 0 : e.preventDefault();
            e === null || e === void 0 ? void 0 : e.currentTarget.blur();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.SetCurrentObject(_this.plugin, { state: _this.props.cell.parent, ref: _this.ref });
        };
        _this.setCurrentRoot = function (e) {
            e === null || e === void 0 ? void 0 : e.preventDefault();
            e === null || e === void 0 ? void 0 : e.currentTarget.blur();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.SetCurrentObject(_this.plugin, { state: _this.props.cell.parent, ref: _mol_state__WEBPACK_IMPORTED_MODULE_5__["StateTransform"].RootRef });
        };
        _this.remove = function (e) {
            e === null || e === void 0 ? void 0 : e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.RemoveObject(_this.plugin, { state: _this.props.cell.parent, ref: _this.ref, removeParentGhosts: true });
        };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.ToggleVisibility(_this.plugin, { state: _this.props.cell.parent, ref: _this.ref });
            e.currentTarget.blur();
        };
        _this.toggleExpanded = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.ToggleExpanded(_this.plugin, { state: _this.props.cell.parent, ref: _this.ref });
            e.currentTarget.blur();
        };
        _this.highlight = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].Interactivity.Object.Highlight(_this.plugin, { state: _this.props.cell.parent, ref: _this.ref });
            e.currentTarget.blur();
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].Interactivity.ClearHighlights(_this.plugin);
            e.currentTarget.blur();
        };
        _this.hideApply = function () {
            _this.setCurrentRoot();
        };
        _this.selectAction = function (item) {
            if (!item)
                return;
            (item === null || item === void 0 ? void 0 : item.value)();
        };
        return _this;
    }
    StateTreeNodeLabel.prototype.is = function (e) {
        return e.ref === this.ref && e.state === this.props.cell.parent;
    };
    Object.defineProperty(StateTreeNodeLabel.prototype, "ref", {
        get: function () {
            return this.props.cell.transform.ref;
        },
        enumerable: false,
        configurable: true
    });
    StateTreeNodeLabel.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_2__[/* filter */ "a"])(function (e) { return _this.is(e); }), Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_3__[/* debounceTime */ "a"])(33)), function (e) {
            _this.forceUpdate();
        });
        this.subscribe(this.props.cell.parent.behaviors.currentObject, function (e) {
            if (!_this.is(e)) {
                if (_this.state.isCurrent && e.state.transforms.has(_this.ref)) {
                    _this._setCurrent(_this.props.cell.parent.current === _this.ref, _this.state.isCollapsed);
                }
                return;
            }
            if (e.state.transforms.has(_this.ref)) {
                _this._setCurrent(_this.props.cell.parent.current === _this.ref, !!_this.props.cell.state.isCollapsed);
            }
        });
    };
    StateTreeNodeLabel.prototype._setCurrent = function (isCurrent, isCollapsed) {
        if (isCurrent) {
            this.setState({ isCurrent: isCurrent, action: 'options', currentAction: void 0, isCollapsed: isCollapsed });
        }
        else {
            this.setState({ isCurrent: isCurrent, action: void 0, currentAction: void 0, isCollapsed: isCollapsed });
        }
    };
    StateTreeNodeLabel.getDerivedStateFromProps = function (props, state) {
        var isCurrent = props.cell.parent.current === props.cell.transform.ref;
        var isCollapsed = !!props.cell.state.isCollapsed;
        if (state.isCollapsed === isCollapsed && state.isCurrent === isCurrent)
            return null;
        return { isCurrent: isCurrent, isCollapsed: isCollapsed, action: void 0, currentAction: void 0 };
    };
    Object.defineProperty(StateTreeNodeLabel.prototype, "actions", {
        get: function () {
            var _this = this;
            var cell = this.props.cell;
            var actions = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])(cell.parent.actions.fromCell(cell, this.plugin));
            if (actions.length === 0)
                return;
            actions.sort(function (a, b) { return a.definition.display.name < b.definition.display.name ? -1 : a.definition.display.name === b.definition.display.name ? 0 : 1; });
            return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spreadArrays"])([
                _controls_action_menu__WEBPACK_IMPORTED_MODULE_8__[/* ActionMenu */ "a"].Header('Apply Action')
            ], actions.map(function (a) { return _controls_action_menu__WEBPACK_IMPORTED_MODULE_8__[/* ActionMenu */ "a"].Item(a.definition.display.name, function () { return _this.setState({ action: 'apply', currentAction: a }); }); }));
        },
        enumerable: false,
        configurable: true
    });
    StateTreeNodeLabel.prototype.updates = function (margin) {
        var cell = this.props.cell;
        var decoratorChain = _mol_state_tree_spine__WEBPACK_IMPORTED_MODULE_6__[/* StateTreeSpine */ "a"].getDecoratorChain(cell.parent, cell.transform.ref);
        var decorators = [];
        for (var i = decoratorChain.length - 1; i >= 0; i--) {
            var d = decoratorChain[i];
            decorators.push(react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_update_transform__WEBPACK_IMPORTED_MODULE_12__["UpdateTransformControl"], { key: d.transform.transformer.id + "-" + i, state: cell.parent, transform: d.transform, noMargin: true, wrapInExpander: true, expanderHeaderLeftMargin: margin }));
        }
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-tree-updates-wrapper' }, decorators);
    };
    StateTreeNodeLabel.prototype.render = function () {
        var cell = this.props.cell;
        var n = cell.transform;
        if (!cell)
            return null;
        var isCurrent = this.is(cell.parent.behaviors.currentObject.value);
        var disabled = cell.status !== 'error' && cell.status !== 'ok';
        var label;
        if (cell.status === 'error' || !cell.obj) {
            var name_1 = cell.status === 'error' ? cell.errorText : n.transformer.definition.display.name;
            label = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["Button"], { className: 'msp-btn-tree-label msp-no-hover-outline', noOverflow: true, title: name_1, onClick: this.state.isCurrent ? this.setCurrentRoot : this.setCurrent, disabled: disabled },
                cell.status === 'error' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("b", null,
                    "[",
                    cell.status,
                    "]"),
                " ",
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", null, name_1));
        }
        else {
            var obj = cell.obj;
            var title = obj.label + " " + (obj.description ? obj.description : '');
            label = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["Button"], { className: "msp-btn-tree-label msp-type-class-" + obj.type.typeClass, noOverflow: true, disabled: disabled, title: title, onClick: this.state.isCurrent ? this.setCurrentRoot : this.setCurrent },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", null, obj.label),
                " ",
                obj.description ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("small", null, obj.description) : void 0);
        }
        var children = cell.parent.tree.children.get(this.ref);
        var cellState = cell.state;
        var expand = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["IconButton"], { svg: cellState.isCollapsed ? _controls_icons__WEBPACK_IMPORTED_MODULE_10__["ArrowRightSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_10__["ArrowDropDownSvg"], flex: '20px', disabled: disabled, onClick: this.toggleExpanded, transparent: true, className: 'msp-no-hover-outline', style: { visibility: children.size > 0 ? 'visible' : 'hidden' } });
        var remove = !cell.state.isLocked ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_10__["DeleteOutlinedSvg"], onClick: this.remove, disabled: disabled, small: true, toggleState: false }) : void 0;
        var visibility = react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["IconButton"], { svg: cellState.isHidden ? _controls_icons__WEBPACK_IMPORTED_MODULE_10__["VisibilityOffOutlinedSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_10__["VisibilityOutlinedSvg"], toggleState: false, disabled: disabled, small: true, onClick: this.toggleVisible });
        var marginStyle = {
            marginLeft: this.props.depth * 8 + "px"
        };
        var row = react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: "msp-flex-row msp-tree-row" + (isCurrent ? ' msp-tree-row-current' : ''), onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight, style: marginStyle },
            expand,
            label,
            remove,
            visibility);
        if (!isCurrent)
            return row;
        if (this.state.action === 'apply' && this.state.currentAction) {
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginBottom: '1px' } },
                row,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_9__["ControlGroup"], { header: "Apply " + this.state.currentAction.definition.display.name, initialExpanded: true, hideExpander: true, hideOffset: false, onHeaderClick: this.hideApply, topRightIcon: _controls_icons__WEBPACK_IMPORTED_MODULE_10__["CloseSvg"], headerLeftMargin: this.props.depth * 8 + 21 + "px" },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_apply_action__WEBPACK_IMPORTED_MODULE_11__[/* ApplyActionControl */ "a"], { onApply: this.hideApply, state: this.props.cell.parent, action: this.state.currentAction, nodeRef: this.props.cell.transform.ref, hideHeader: true, noMargin: true })));
        }
        if (this.state.action === 'options') {
            var actions = this.actions;
            var updates = this.updates(this.props.depth * 8 + 21 + "px");
            return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginBottom: '1px' } },
                row,
                updates,
                actions && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginLeft: this.props.depth * 8 + 21 + "px", marginTop: '-1px' } },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_8__[/* ActionMenu */ "a"], { items: actions, onSelect: this.selectAction })));
        }
        return row;
    };
    return StateTreeNodeLabel;
}(_base__WEBPACK_IMPORTED_MODULE_7__["PluginUIComponent"]));
//# sourceMappingURL=tree.js.map

/***/ }),
/* 377 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureQualityReportColorThemeParams", function() { return StructureQualityReportColorThemeParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureQualityReportColorTheme", function() { return StructureQualityReportColorTheme; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureQualityReportColorThemeProvider", function() { return StructureQualityReportColorThemeProvider; });
/* harmony import */ var _prop__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(212);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(4);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _mol_util_legend__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(141);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var ValidationColors = [
    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromRgb(170, 170, 170),
    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromRgb(0, 255, 0),
    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromRgb(255, 255, 0),
    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromRgb(255, 128, 0),
    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromRgb(255, 0, 0),
];
var ValidationColorTable = [
    ['No Issues', ValidationColors[1]],
    ['One Issue', ValidationColors[2]],
    ['Two Issues', ValidationColors[3]],
    ['Three Or More Issues', ValidationColors[4]],
    ['Not Applicable', ValidationColors[9]]
];
var StructureQualityReportColorThemeParams = {
    type: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MappedStatic('issue-count', {
        'issue-count': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
        'specific-issue': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
            kind: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Text()
        })
    })
};
function StructureQualityReportColorTheme(ctx, props) {
    var color;
    if (ctx.structure && !ctx.structure.isEmpty && ctx.structure.models[0].customProperties.has(_prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReportProvider */ "b"].descriptor)) {
        var getIssues_1 = _prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReport */ "a"].getIssues;
        if (props.type.name === 'issue-count') {
            color = function (location) {
                if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.is(location)) {
                    return ValidationColors[Math.min(3, getIssues_1(location).length) + 1];
                }
                return ValidationColors[0];
            };
        }
        else {
            var issue_1 = props.type.params.kind;
            color = function (location) {
                if (_mol_model_structure__WEBPACK_IMPORTED_MODULE_1__["StructureElement"].Location.is(location) && getIssues_1(location).indexOf(issue_1) >= 0) {
                    return ValidationColors[4];
                }
                return ValidationColors[0];
            };
        }
    }
    else {
        color = function () { return ValidationColors[0]; };
    }
    return {
        factory: StructureQualityReportColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: 'Assigns residue colors according to the number of quality issues or a specific quality issue. Data from wwPDB Validation Report, obtained via PDBe.',
        legend: Object(_mol_util_legend__WEBPACK_IMPORTED_MODULE_3__[/* TableLegend */ "b"])(ValidationColorTable)
    };
}
var StructureQualityReportColorThemeProvider = {
    name: 'pdbe-structure-quality-report',
    label: 'Structure Quality Report',
    category: "Validation" /* Validation */,
    factory: StructureQualityReportColorTheme,
    getParams: function (ctx) {
        var issueTypes = _prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReport */ "a"].getIssueTypes(ctx.structure);
        if (issueTypes.length === 0) {
            return {
                type: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MappedStatic('issue-count', {
                    'issue-count': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({})
                })
            };
        }
        return {
            type: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MappedStatic('issue-count', {
                'issue-count': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
                'specific-issue': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                    kind: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select(issueTypes[0], _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].arrayToOptions(issueTypes))
                }, { isFlat: true })
            })
        };
    },
    defaultValues: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(StructureQualityReportColorThemeParams),
    isApplicable: function (ctx) { var _a; return _prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReport */ "a"].isApplicable((_a = ctx.structure) === null || _a === void 0 ? void 0 : _a.models[0]); },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? _prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReportProvider */ "b"].attach(ctx, data.structure.models[0], void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.models[0].customProperties.reference(_prop__WEBPACK_IMPORTED_MODULE_0__[/* StructureQualityReportProvider */ "b"].descriptor, false); }
    }
};
//# sourceMappingURL=color.js.map

/***/ }),
/* 378 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return not; });
/** PURE_IMPORTS_START  PURE_IMPORTS_END */
function not(pred, thisArg) {
    function notPred() {
        return !(notPred.pred.apply(notPred.thisArg, arguments));
    }
    notPred.pred = pred;
    notPred.thisArg = thisArg;
    return notPred;
}
//# sourceMappingURL=not.js.map


/***/ }),
/* 379 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ registry_VolumeRepresentationRegistry; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var representation = __webpack_require__(40);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/isosurface.js
var isosurface = __webpack_require__(241);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/image/image.js
var image_image = __webpack_require__(218);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/volume.js
var mol_model_volume = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/representation.js
var volume_representation = __webpack_require__(237);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/location-iterator.js
var location_iterator = __webpack_require__(86);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/location.js
var mol_model_location = __webpack_require__(144);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util.js
var util = __webpack_require__(124);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/common.js
var common = __webpack_require__(82);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color.js + 17 modules
var mol_theme_color = __webpack_require__(196);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/volume/slice.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














function createImage(ctx, volume, theme, props, image) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var dim, isoValue, _a, space, data, _b, min, max, isoVal, color, _c, r, g, b, _d, width, height, x, y, z, x0, y0, z0, nx, ny, nz, corners, imageArray, groupArray, i, iy, ix, iz, val, normVal, imageTexture, groupTexture, transform;
        return Object(tslib_es6["__generator"])(this, function (_e) {
            dim = props.dimension.name, isoValue = props.isoValue;
            _a = volume.grid.cells, space = _a.space, data = _a.data;
            _b = volume.grid.stats, min = _b.min, max = _b.max;
            isoVal = mol_model_volume["b" /* Volume */].IsoValue.toAbsolute(isoValue, volume.grid.stats).absoluteValue;
            color = theme.color.color(mol_model_location["b" /* NullLocation */], false);
            _c = mol_util_color["Color"].toRgbNormalized(color), r = _c[0], g = _c[1], b = _c[2];
            _d = getSliceInfo(volume.grid, props), width = _d.width, height = _d.height, x = _d.x, y = _d.y, z = _d.z, x0 = _d.x0, y0 = _d.y0, z0 = _d.z0, nx = _d.nx, ny = _d.ny, nz = _d.nz;
            corners = new Float32Array(dim === 'x' ? [x, 0, 0, x, y, 0, x, 0, z, x, y, z] :
                dim === 'y' ? [0, y, 0, x, y, 0, 0, y, z, x, y, z] :
                    [0, 0, z, 0, y, z, x, 0, z, x, y, z]);
            imageArray = new Float32Array(width * height * 4);
            groupArray = getGroupArray(volume.grid, props);
            i = 0;
            for (iy = y0; iy < ny; ++iy) {
                for (ix = x0; ix < nx; ++ix) {
                    for (iz = z0; iz < nz; ++iz) {
                        val = space.get(data, ix, iy, iz);
                        normVal = (val - min) / (max - min);
                        imageArray[i] = r * normVal * 2;
                        imageArray[i + 1] = g * normVal * 2;
                        imageArray[i + 2] = b * normVal * 2;
                        imageArray[i + 3] = val >= isoVal ? 1 : 0;
                        i += 4;
                    }
                }
            }
            imageTexture = { width: width, height: height, array: imageArray, flipY: true };
            groupTexture = { width: width, height: height, array: groupArray, flipY: true };
            transform = mol_model_volume["a" /* Grid */].getGridToCartesianTransform(volume.grid);
            Object(util["e" /* transformPositionArray */])(transform, corners, 0, 4);
            return [2 /*return*/, image_image["a" /* Image */].create(imageTexture, corners, groupTexture, image)];
        });
    });
}
function getSliceInfo(grid, props) {
    var _a = props.dimension, dim = _a.name, index = _a.params;
    var space = grid.cells.space;
    var width, height;
    var x, y, z;
    var x0 = 0, y0 = 0, z0 = 0;
    var _b = space.dimensions, nx = _b[0], ny = _b[1], nz = _b[2];
    if (dim === 'x') {
        x = index, y = ny - 1, z = nz - 1;
        width = nz, height = ny;
        x0 = x, nx = x0 + 1;
    }
    else if (dim === 'y') {
        x = nx - 1, y = index, z = nz - 1;
        width = nz, height = nx;
        y0 = y, ny = y0 + 1;
    }
    else {
        x = nx - 1, y = ny - 1, z = index;
        width = nx, height = ny;
        z0 = z, nz = z0 + 1;
    }
    return {
        width: width, height: height,
        x: x, y: y, z: z,
        x0: x0, y0: y0, z0: z0,
        nx: nx, ny: ny, nz: nz
    };
}
function getGroupArray(grid, props) {
    var space = grid.cells.space;
    var _a = getSliceInfo(grid, props), width = _a.width, height = _a.height, x0 = _a.x0, y0 = _a.y0, z0 = _a.z0, nx = _a.nx, ny = _a.ny, nz = _a.nz;
    var groupArray = new Float32Array(width * height);
    var j = 0;
    for (var iy = y0; iy < ny; ++iy) {
        for (var ix = x0; ix < nx; ++ix) {
            for (var iz = z0; iz < nz; ++iz) {
                groupArray[j] = space.dataOffset(ix, iy, iz);
                j += 1;
            }
        }
    }
    return groupArray;
}
function getLoci(volume, props) {
    // TODO cache somehow?
    var groupArray = getGroupArray(volume.grid, props);
    return mol_model_volume["b" /* Volume */].Cell.Loci(volume, mol_data_int["SortedArray"].ofUnsortedArray(groupArray));
}
function getSliceLoci(pickingId, volume, props, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        return mol_model_volume["b" /* Volume */].Cell.Loci(volume, mol_data_int["Interval"].ofSingleton(groupId));
    }
    return mol_model_loci["EmptyLoci"];
}
function eachSlice(loci, volume, props, apply) {
    var changed = false;
    if (mol_model_volume["b" /* Volume */].isLoci(loci)) {
        if (!mol_model_volume["b" /* Volume */].areEquivalent(loci.volume, volume))
            return false;
        if (apply(mol_data_int["Interval"].ofLength(volume.grid.cells.data.length)))
            changed = true;
    }
    else if (mol_model_volume["b" /* Volume */].Isosurface.isLoci(loci)) {
        if (!mol_model_volume["b" /* Volume */].areEquivalent(loci.volume, volume))
            return false;
        // TODO find a cheaper way?
        var _a = volume.grid, stats = _a.stats, data = _a.cells.data;
        var eps = stats.sigma;
        var v = mol_model_volume["b" /* Volume */].IsoValue.toAbsolute(loci.isoValue, stats).absoluteValue;
        for (var i = 0, il = data.length; i < il; ++i) {
            if (Object(common["b" /* equalEps */])(v, data[i], eps)) {
                if (apply(mol_data_int["Interval"].ofSingleton(i)))
                    changed = true;
            }
        }
    }
    else if (mol_model_volume["b" /* Volume */].Cell.isLoci(loci)) {
        if (!mol_model_volume["b" /* Volume */].areEquivalent(loci.volume, volume))
            return false;
        if (mol_data_int["Interval"].is(loci.indices)) {
            if (apply(loci.indices))
                changed = true;
        }
        else {
            mol_data_int["OrderedSet"].forEach(loci.indices, function (v) {
                if (apply(mol_data_int["Interval"].ofSingleton(v)))
                    changed = true;
            });
        }
    }
    return changed;
}
//
var SliceParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, image_image["a" /* Image */].Params), { quality: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, image_image["a" /* Image */].Params.quality), { isEssential: false }), dimension: param_definition["ParamDefinition"].MappedStatic('x', {
        x: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 0, step: 1 }),
        y: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 0, step: 1 }),
        z: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 0, step: 1 }),
    }, { isEssential: true }), isoValue: isosurface["a" /* IsoValueParam */] });
function getSliceParams(ctx, volume) {
    var p = param_definition["ParamDefinition"].clone(SliceParams);
    var dim = volume.grid.cells.space.dimensions;
    p.dimension = param_definition["ParamDefinition"].MappedStatic('x', {
        x: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: dim[0] - 1, step: 1 }),
        y: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: dim[1] - 1, step: 1 }),
        z: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: dim[2] - 1, step: 1 }),
    }, { isEssential: true });
    p.isoValue = Object(isosurface["c" /* createIsoValueParam */])(mol_model_volume["b" /* Volume */].IsoValue.absolute(volume.grid.stats.min), volume.grid.stats);
    return p;
}
function SliceVisual(materialId) {
    return Object(volume_representation["c" /* VolumeVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(SliceParams),
        createGeometry: createImage,
        createLocationIterator: function (volume) { return Object(location_iterator["a" /* LocationIterator */])(volume.grid.cells.data.length, 1, function () { return mol_model_location["b" /* NullLocation */]; }); },
        getLoci: getSliceLoci,
        eachLocation: eachSlice,
        setUpdateState: function (state, volume, newProps, currentProps, newTheme, currentTheme) {
            state.createGeometry = (newProps.dimension.name !== currentProps.dimension.name ||
                newProps.dimension.params !== currentProps.dimension.params ||
                !mol_model_volume["b" /* Volume */].IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats) ||
                !mol_theme_color["a" /* ColorTheme */].areEqual(newTheme.color, currentTheme.color));
        },
        geometryUtils: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, image_image["a" /* Image */].Utils), { createRenderableState: function (props) {
                var state = image_image["a" /* Image */].Utils.createRenderableState(props);
                updateRenderableState(state, props);
                return state;
            }, updateRenderableState: updateRenderableState })
    }, materialId);
}
function updateRenderableState(state, props) {
    image_image["a" /* Image */].Utils.updateRenderableState(state, props);
    state.opaque = false;
    state.writeDepth = true;
}
function SliceRepresentation(ctx, getParams) {
    return Object(volume_representation["a" /* VolumeRepresentation */])('Slice', ctx, getParams, SliceVisual, getLoci);
}
var SliceRepresentationProvider = Object(volume_representation["b" /* VolumeRepresentationProvider */])({
    name: 'slice',
    label: 'Slice',
    description: 'Slice of volume rendered as image with interpolation.',
    factory: SliceRepresentation,
    getParams: getSliceParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(SliceParams),
    defaultColorTheme: { name: 'uniform' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (volume) { return !mol_model_volume["b" /* Volume */].isEmpty(volume); }
});
//# sourceMappingURL=slice.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/volume/registry.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var registry_VolumeRepresentationRegistry = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(VolumeRepresentationRegistry, _super);
    function VolumeRepresentationRegistry() {
        var _this = _super.call(this) || this;
        Object(object["c" /* objectForEach */])(VolumeRepresentationRegistry.BuiltIn, function (p, k) {
            if (p.name !== k)
                throw new Error("Fix BuiltInVolumeRepresentations to have matching names. " + p.name + " " + k);
            _this.add(p);
        });
        return _this;
    }
    return VolumeRepresentationRegistry;
}(representation["b" /* RepresentationRegistry */]));

(function (VolumeRepresentationRegistry) {
    VolumeRepresentationRegistry.BuiltIn = {
        'isosurface': isosurface["b" /* IsosurfaceRepresentationProvider */],
        'slice': SliceRepresentationProvider,
    };
})(registry_VolumeRepresentationRegistry || (registry_VolumeRepresentationRegistry = {}));
//# sourceMappingURL=registry.js.map

/***/ }),
/* 380 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ hierarchy_VolumeHierarchyManager; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/static/state.js
var static_state = __webpack_require__(216);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/component.js
var component = __webpack_require__(118);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/volume/hierarchy-state.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


function buildVolumeHierarchy(state, previous) {
    var build = BuildState(state, previous || VolumeHierarchy());
    doPreOrder(state.tree, build);
    if (previous)
        previous.refs.forEach(isRemoved, build);
    return { hierarchy: build.hierarchy, added: build.added, changed: build.changed };
}
function VolumeHierarchy() {
    return { volumes: [], refs: new Map() };
}
function VolumeRef(cell) {
    return { kind: 'volume', cell: cell, version: cell.transform.version, representations: [] };
}
function VolumeRepresentationRef(cell, volume) {
    return { kind: 'volume-representation', cell: cell, version: cell.transform.version, volume: volume };
}
function BuildState(state, oldHierarchy) {
    return { state: state, oldHierarchy: oldHierarchy, hierarchy: VolumeHierarchy(), changed: false, added: new Set() };
}
function createOrUpdateRefList(state, cell, list, ctor) {
    var args = [];
    for (var _i = 4; _i < arguments.length; _i++) {
        args[_i - 4] = arguments[_i];
    }
    var ref = ctor.apply(void 0, args);
    list.push(ref);
    state.hierarchy.refs.set(cell.transform.ref, ref);
    var old = state.oldHierarchy.refs.get(cell.transform.ref);
    if (old) {
        if (old.version !== cell.transform.version)
            state.changed = true;
    }
    else {
        state.added.add(ref.cell.transform.ref);
        state.changed = true;
    }
    return ref;
}
function isTypeRoot(t, target) {
    return function (cell, state) { return !target(state) && t.is(cell.obj); };
}
function noop() { }
var Mapping = [
    [isTypeRoot(objects["a" /* PluginStateObject */].Volume.Data, function (t) { return t.currentVolume; }), function (state, cell) {
            state.currentVolume = createOrUpdateRefList(state, cell, state.hierarchy.volumes, VolumeRef, cell);
        }, function (state) { return state.currentVolume = void 0; }],
    [function (cell, state) {
            return !cell.state.isGhost && !!state.currentVolume && objects["a" /* PluginStateObject */].Volume.Representation3D.is(cell.obj);
        }, function (state, cell) {
            if (state.currentVolume) {
                createOrUpdateRefList(state, cell, state.currentVolume.representations, VolumeRepresentationRef, cell, state.currentVolume);
            }
            return false;
        }, noop]
];
function isValidCell(cell) {
    if (!cell || !(cell === null || cell === void 0 ? void 0 : cell.parent) || !cell.parent.cells.has(cell.transform.ref))
        return false;
    var obj = cell.obj;
    if (!obj || obj === mol_state["StateObject"].Null || (cell.status !== 'ok' && cell.status !== 'error'))
        return false;
    return true;
}
function isRemoved(ref) {
    var cell = ref.cell;
    if (isValidCell(cell))
        return;
    this.changed = true;
}
function _preOrderFunc(c) { _doPreOrder(this, this.tree.transforms.get(c)); }
function _doPreOrder(ctx, root) {
    var state = ctx.state;
    var cell = state.state.cells.get(root.ref);
    if (!isValidCell(cell))
        return;
    var onLeave = void 0;
    var end = false;
    for (var _i = 0, Mapping_1 = Mapping; _i < Mapping_1.length; _i++) {
        var _a = Mapping_1[_i], test_1 = _a[0], f = _a[1], l = _a[2];
        if (test_1(cell, state)) {
            var cont = f(state, cell);
            if (cont === false) {
                end = true;
                break;
            }
            onLeave = l;
            break;
        }
    }
    // TODO: might be needed in the future
    // const { currentComponent, currentModel, currentStructure, currentTrajectory } = ctx.state;
    // const inTrackedSubtree = currentComponent || currentModel || currentStructure || currentTrajectory;
    // if (inTrackedSubtree && cell.transform.transformer.definition.isDecorator) {
    //     const ref = cell.transform.ref;
    //     const old = ctx.state.oldHierarchy.decorators.get(ref);
    //     if (old && old.version !== cell.transform.version) {
    //         ctx.state.changed = true;
    //     }
    //     ctx.state.hierarchy.decorators.set(cell.transform.ref, cell.transform);
    // }
    if (end)
        return;
    var children = ctx.tree.children.get(root.ref);
    if (children && children.size) {
        children.forEach(_preOrderFunc, ctx);
    }
    if (onLeave)
        onLeave(state);
}
function doPreOrder(tree, state) {
    var ctx = { tree: tree, state: state };
    _doPreOrder(ctx, tree.root);
    return ctx.state;
}
//# sourceMappingURL=hierarchy-state.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/volume-representation-params.js
var volume_representation_params = __webpack_require__(315);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/volume/hierarchy.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */






var hierarchy_VolumeHierarchyManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(VolumeHierarchyManager, _super);
    function VolumeHierarchyManager(plugin) {
        var _this = _super.call(this) || this;
        _this.plugin = plugin;
        _this.state = {
            syncedTree: _this.dataState.tree,
            notified: false,
            hierarchy: VolumeHierarchy(),
            selection: void 0
        };
        _this.behaviors = {
            selection: _this.ev.behavior({
                hierarchy: _this.current,
                volume: _this.selection
            })
        };
        _this.subscribe(plugin.state.data.events.changed, function (e) {
            if (e.inTransaction || plugin.behaviors.state.isAnimating.value)
                return;
            _this.sync(true);
        });
        _this.subscribe(plugin.behaviors.state.isAnimating, function (isAnimating) {
            if (!isAnimating && !plugin.behaviors.state.isUpdating.value)
                _this.sync(true);
        });
        return _this;
    }
    Object.defineProperty(VolumeHierarchyManager.prototype, "dataState", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VolumeHierarchyManager.prototype, "current", {
        get: function () {
            this.sync(false);
            return this.state.hierarchy;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(VolumeHierarchyManager.prototype, "selection", {
        get: function () {
            this.sync(false);
            return this.state.selection;
        },
        enumerable: false,
        configurable: true
    });
    VolumeHierarchyManager.prototype.sync = function (notify) {
        if (!notify && this.dataState.inUpdate)
            return;
        if (this.state.syncedTree === this.dataState.tree) {
            if (notify && !this.state.notified) {
                this.state.notified = true;
                this.behaviors.selection.next({ hierarchy: this.state.hierarchy, volume: this.state.selection });
            }
            return;
        }
        this.state.syncedTree = this.dataState.tree;
        var update = buildVolumeHierarchy(this.plugin.state.data, this.current);
        if (!update.changed) {
            return;
        }
        var hierarchy = update.hierarchy;
        this.state.hierarchy = hierarchy;
        if (!this.state.selection) {
            this.state.selection = hierarchy.volumes[0];
        }
        else {
            this.state.selection = hierarchy.refs.has(this.state.selection.cell.transform.ref) ? hierarchy.refs.get(this.state.selection.cell.transform.ref) : hierarchy.volumes[0];
        }
        if (notify) {
            this.state.notified = true;
            this.behaviors.selection.next({ hierarchy: hierarchy, volume: this.state.selection });
        }
        else {
            this.state.notified = false;
        }
    };
    VolumeHierarchyManager.prototype.setCurrent = function (volume) {
        this.state.selection = volume || this.state.hierarchy.volumes[0];
        this.behaviors.selection.next({ hierarchy: this.state.hierarchy, volume: volume || this.state.hierarchy.volumes[0] });
    };
    // TODO: have common util
    VolumeHierarchyManager.prototype.remove = function (refs, canUndo) {
        if (refs.length === 0)
            return;
        var deletes = this.plugin.state.data.build();
        for (var _i = 0, refs_1 = refs; _i < refs_1.length; _i++) {
            var r = refs_1[_i];
            deletes.delete(typeof r === 'string' ? r : r.cell.transform.ref);
        }
        return deletes.commit({ canUndo: canUndo ? 'Remove' : false });
    };
    // TODO: have common util
    VolumeHierarchyManager.prototype.toggleVisibility = function (refs, action) {
        if (refs.length === 0)
            return;
        var isHidden = action !== void 0
            ? (action === 'show' ? false : true)
            : !refs[0].cell.state.isHidden;
        for (var _i = 0, refs_2 = refs; _i < refs_2.length; _i++) {
            var c = refs_2[_i];
            Object(static_state["setSubtreeVisibility"])(this.dataState, c.cell.transform.ref, isHidden);
        }
    };
    VolumeHierarchyManager.prototype.addRepresentation = function (ref, type) {
        var _a;
        var update = this.dataState.build()
            .to(ref.cell)
            .apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, Object(volume_representation_params["a" /* createVolumeRepresentationParams */])(this.plugin, (_a = ref.cell.obj) === null || _a === void 0 ? void 0 : _a.data, {
            type: type,
        }));
        return update.commit({ canUndo: 'Add Representation' });
    };
    return VolumeHierarchyManager;
}(component["a" /* PluginComponent */]));

(function (VolumeHierarchyManager) {
    function getRepresentationTypes(plugin, pivot) {
        var _a, _b;
        return ((_a = pivot === null || pivot === void 0 ? void 0 : pivot.cell.obj) === null || _a === void 0 ? void 0 : _a.data) ? plugin.representation.volume.registry.getApplicableTypes((_b = pivot.cell.obj) === null || _b === void 0 ? void 0 : _b.data)
            : plugin.representation.volume.registry.types;
    }
    VolumeHierarchyManager.getRepresentationTypes = getRepresentationTypes;
})(hierarchy_VolumeHierarchyManager || (hierarchy_VolumeHierarchyManager = {}));
//# sourceMappingURL=hierarchy.js.map

/***/ }),
/* 381 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";

// EXPORTS
__webpack_require__.d(__webpack_exports__, "b", function() { return /* binding */ getFontAtlas; });
__webpack_require__.d(__webpack_exports__, "a", function() { return /* binding */ FontAtlasParams; });

// UNUSED EXPORTS: FontAtlas

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/distance-transform.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/**
 * 2D Euclidean distance transform by Felzenszwalb & Huttenlocher https://cs.brown.edu/~pff/papers/dt-final.pdf
 */
function edt(data, width, height, f, d, v, z) {
    for (var x = 0; x < width; x++) {
        for (var y = 0; y < height; y++) {
            f[y] = data[y * width + x];
        }
        edt1d(f, d, v, z, height);
        for (var y = 0; y < height; y++) {
            data[y * width + x] = d[y];
        }
    }
    for (var y = 0; y < height; y++) {
        for (var x = 0; x < width; x++) {
            f[x] = data[y * width + x];
        }
        edt1d(f, d, v, z, width);
        for (var x = 0; x < width; x++) {
            data[y * width + x] = Math.sqrt(d[x]);
        }
    }
}
/**
 * 1D squared distance transform
 */
function edt1d(f, d, v, z, n) {
    v[0] = 0;
    z[0] = Number.MIN_SAFE_INTEGER;
    z[1] = Number.MAX_SAFE_INTEGER;
    for (var q = 1, k = 0; q < n; q++) {
        var s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
        while (s <= z[k]) {
            k--;
            s = ((f[q] + q * q) - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]);
        }
        k++;
        v[k] = q;
        z[k] = s;
        z[k + 1] = Number.MAX_SAFE_INTEGER;
    }
    for (var q = 0, k = 0; q < n; q++) {
        while (z[k + 1] < q)
            k++;
        d[q] = (q - v[k]) * (q - v[k]) + f[v[k]];
    }
}
//# sourceMappingURL=distance-transform.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/util.js
var util = __webpack_require__(53);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/text/font-atlas.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var TextAtlasCache = {};
function getFontAtlas(props) {
    var hash = JSON.stringify(props);
    if (TextAtlasCache[hash] === undefined) {
        TextAtlasCache[hash] = new font_atlas_FontAtlas(props);
    }
    return TextAtlasCache[hash];
}
var FontAtlasParams = {
    fontFamily: param_definition["ParamDefinition"].Select('sans-serif', [['sans-serif', 'Sans Serif'], ['monospace', 'Monospace'], ['serif', 'Serif'], ['cursive', 'Cursive']]),
    fontQuality: param_definition["ParamDefinition"].Select(3, [[0, 'lower'], [1, 'low'], [2, 'medium'], [3, 'high'], [4, 'higher']]),
    fontStyle: param_definition["ParamDefinition"].Select('normal', [['normal', 'Normal'], ['italic', 'Italic'], ['oblique', 'Oblique']]),
    fontVariant: param_definition["ParamDefinition"].Select('normal', [['normal', 'Normal'], ['small-caps', 'Small Caps']]),
    fontWeight: param_definition["ParamDefinition"].Select('normal', [['normal', 'Normal'], ['bold', 'Bold']]),
};
var font_atlas_FontAtlas = /** @class */ (function () {
    function FontAtlas(props) {
        if (props === void 0) { props = {}; }
        this.mapped = {};
        this.scratchW = 0;
        this.scratchH = 0;
        this.currentX = 0;
        this.currentY = 0;
        this.cutoff = 0.5;
        var p = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(FontAtlasParams)), props);
        this.props = p;
        // create measurements
        var fontSize = 32 * (p.fontQuality + 1);
        this.buffer = fontSize / 8;
        this.radius = fontSize / 3;
        this.lineHeight = Math.round(fontSize + 2 * this.buffer + this.radius);
        this.maxWidth = Math.round(this.lineHeight * 0.75);
        // create texture (for ~350 characters)
        this.texture = Object(util["c" /* createTextureImage */])(350 * this.lineHeight * this.maxWidth, 1, Uint8Array);
        // prepare scratch canvas
        this.scratchCanvas = document.createElement('canvas');
        this.scratchCanvas.width = this.maxWidth;
        this.scratchCanvas.height = this.lineHeight;
        this.scratchContext = this.scratchCanvas.getContext('2d');
        this.scratchContext.font = p.fontStyle + " " + p.fontVariant + " " + p.fontWeight + " " + fontSize + "px " + p.fontFamily;
        this.scratchContext.fillStyle = 'black';
        this.scratchContext.textBaseline = 'middle';
        // SDF scratch values
        this.scratchData = new Uint8Array(this.lineHeight * this.maxWidth);
        // temporary arrays for the distance transform
        this.gridOuter = new Float64Array(this.lineHeight * this.maxWidth);
        this.gridInner = new Float64Array(this.lineHeight * this.maxWidth);
        this.f = new Float64Array(Math.max(this.lineHeight, this.maxWidth));
        this.d = new Float64Array(Math.max(this.lineHeight, this.maxWidth));
        this.z = new Float64Array(Math.max(this.lineHeight, this.maxWidth) + 1);
        this.v = new Int16Array(Math.max(this.lineHeight, this.maxWidth));
        this.middle = Math.ceil(this.lineHeight / 2);
        // replacement Character
        this.placeholder = this.get(String.fromCharCode(0xFFFD));
    }
    FontAtlas.prototype.get = function (char) {
        if (this.mapped[char] === undefined) {
            this.draw(char);
            var _a = this.texture, array = _a.array, width = _a.width, height = _a.height;
            var data = this.scratchData;
            if (this.currentX + this.scratchW > width) {
                this.currentX = 0;
                this.currentY += this.scratchH;
            }
            if (this.currentY + this.scratchH > height) {
                console.warn('canvas to small');
                return this.placeholder;
            }
            this.mapped[char] = {
                x: this.currentX, y: this.currentY,
                w: this.scratchW, h: this.scratchH,
                nw: this.scratchW / this.lineHeight, nh: this.scratchH / this.lineHeight
            };
            for (var y = 0; y < this.scratchH; ++y) {
                for (var x = 0; x < this.scratchW; ++x) {
                    array[width * (this.currentY + y) + this.currentX + x] = data[y * this.scratchW + x];
                }
            }
            this.currentX += this.scratchW;
        }
        return this.mapped[char];
    };
    FontAtlas.prototype.draw = function (char) {
        var h = this.lineHeight;
        var ctx = this.scratchContext;
        var data = this.scratchData;
        // measure text
        var m = ctx.measureText(char);
        var w = Math.min(this.maxWidth, Math.ceil(m.width + 2 * this.buffer));
        var n = w * h;
        ctx.clearRect(0, 0, w, h); // clear scratch area
        ctx.fillText(char, this.buffer, this.middle); // draw text
        var imageData = ctx.getImageData(0, 0, w, h);
        for (var i = 0; i < n; i++) {
            var a = imageData.data[i * 4 + 3] / 255; // alpha value
            this.gridOuter[i] = a === 1 ? 0 : a === 0 ? Number.MAX_SAFE_INTEGER : Math.pow(Math.max(0, 0.5 - a), 2);
            this.gridInner[i] = a === 1 ? Number.MAX_SAFE_INTEGER : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2);
        }
        edt(this.gridOuter, w, h, this.f, this.d, this.v, this.z);
        edt(this.gridInner, w, h, this.f, this.d, this.v, this.z);
        for (var i = 0; i < n; i++) {
            var d = this.gridOuter[i] - this.gridInner[i];
            data[i] = Math.max(0, Math.min(255, Math.round(255 - 255 * (d / this.radius + this.cutoff))));
        }
        this.scratchW = w;
        this.scratchH = h;
    };
    return FontAtlas;
}());

//# sourceMappingURL=font-atlas.js.map

/***/ }),
/* 382 */
/***/ (function(module, exports) {

var g;

// This works in non-strict mode
g = (function() {
	return this;
})();

try {
	// This works if eval is allowed (see CSP)
	g = g || new Function("return this")();
} catch (e) {
	// This works if the window reference is available
	if (typeof window === "object") g = window;
}

// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}

module.exports = g;


/***/ }),
/* 383 */
/***/ (function(module, exports) {

// shim for using process in browser
var process = module.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ())
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop() {}

process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;

process.listeners = function (name) { return [] }

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };


/***/ }),
/* 384 */
/***/ (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__(430);
// 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(this, __webpack_require__(382)))

/***/ }),
/* 385 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PDBeStructureQualityReport", function() { return PDBeStructureQualityReport; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _prop__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(212);
/* harmony import */ var _color__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(377);
/* harmony import */ var _mol_model_structure__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(4);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2);
/* harmony import */ var _mol_plugin_behavior_behavior__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(68);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var PDBeStructureQualityReport = _mol_plugin_behavior_behavior__WEBPACK_IMPORTED_MODULE_6__["PluginBehavior"].create({
    name: 'pdbe-structure-quality-report-prop',
    category: 'custom-props',
    display: {
        name: 'Structure Quality Report',
        description: 'Data from wwPDB Validation Report, obtained via PDBe.'
    },
    ctor: /** @class */ (function (_super) {
        Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = _prop__WEBPACK_IMPORTED_MODULE_2__[/* StructureQualityReportProvider */ "b"];
            _this.labelPDBeValidation = {
                label: function (loci) {
                    if (!_this.params.showTooltip)
                        return void 0;
                    switch (loci.kind) {
                        case 'element-loci':
                            if (loci.elements.length === 0)
                                return void 0;
                            var e = loci.elements[0];
                            var u = e.unit;
                            if (!u.model.customProperties.hasReference(_prop__WEBPACK_IMPORTED_MODULE_2__[/* StructureQualityReportProvider */ "b"].descriptor))
                                return void 0;
                            var se = _mol_model_structure__WEBPACK_IMPORTED_MODULE_4__["StructureElement"].Location.create(loci.structure, u, u.elements[_mol_data_int__WEBPACK_IMPORTED_MODULE_1__["OrderedSet"].getAt(e.indices, 0)]);
                            var issues = _prop__WEBPACK_IMPORTED_MODULE_2__[/* StructureQualityReport */ "a"].getIssues(se);
                            if (issues.length === 0)
                                return 'Validation: No Issues';
                            return "Validation: " + issues.join(', ');
                        default: return void 0;
                    }
                }
            };
            return _this;
        }
        class_1.prototype.register = function () {
            this.ctx.customModelProperties.register(this.provider, this.params.autoAttach);
            this.ctx.managers.lociLabels.addProvider(this.labelPDBeValidation);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(_color__WEBPACK_IMPORTED_MODULE_3__["StructureQualityReportColorThemeProvider"]);
        };
        class_1.prototype.update = function (p) {
            var updated = this.params.autoAttach !== p.autoAttach;
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customModelProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.unregister = function () {
            this.ctx.customModelProperties.unregister(_prop__WEBPACK_IMPORTED_MODULE_2__[/* StructureQualityReportProvider */ "b"].descriptor.name);
            this.ctx.managers.lociLabels.removeProvider(this.labelPDBeValidation);
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(_color__WEBPACK_IMPORTED_MODULE_3__["StructureQualityReportColorThemeProvider"]);
        };
        return class_1;
    }(_mol_plugin_behavior_behavior__WEBPACK_IMPORTED_MODULE_6__["PluginBehavior"].Handler)),
    params: function () { return ({
        autoAttach: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false),
        showTooltip: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(true)
    }); }
});
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 386 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StructureMeasurementsControls", function() { return StructureMeasurementsControls; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeasurementList", function() { return MeasurementList; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "MeasurementControls", function() { return MeasurementControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(23);
/* harmony import */ var _mol_plugin_state_manager_structure_measurement__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(369);
/* harmony import */ var _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(26);
/* harmony import */ var _mol_theme_label__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(72);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(32);
/* harmony import */ var _controls_action_menu__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(56);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(14);
/* harmony import */ var _controls_parameters__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(66);
/* harmony import */ var _state_update_transform__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(183);
/* harmony import */ var _selection__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(206);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */













// TODO details, options (e.g. change text for labels)
var StructureMeasurementsControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StructureMeasurementsControls, _super);
    function StructureMeasurementsControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    StructureMeasurementsControls.prototype.defaultState = function () {
        return {
            isCollapsed: false,
            header: 'Measurements',
            brand: { accent: 'gray', svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["PencilRulerSvg"] }
        };
    };
    StructureMeasurementsControls.prototype.renderControls = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](MeasurementControls, null),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](MeasurementList, null));
    };
    return StructureMeasurementsControls;
}(_base__WEBPACK_IMPORTED_MODULE_6__["CollapsableControls"]));

var MeasurementList = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MeasurementList, _super);
    function MeasurementList() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    MeasurementList.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.measurement.behaviors.state, function () {
            _this.forceUpdate();
        });
    };
    MeasurementList.prototype.renderGroup = function (cells, header) {
        var group = [];
        for (var _a = 0, cells_1 = cells; _a < cells_1.length; _a++) {
            var cell = cells_1[_a];
            if (cell.obj)
                group.push(react__WEBPACK_IMPORTED_MODULE_1__["createElement"](MeasurementEntry, { key: cell.obj.id, cell: cell }));
        }
        return group.length ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["ExpandGroup"], { header: header, initiallyExpanded: true }, group) : null;
    };
    MeasurementList.prototype.render = function () {
        var measurements = this.plugin.managers.structure.measurement.state;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { style: { marginTop: '6px' } },
            this.renderGroup(measurements.labels, 'Labels'),
            this.renderGroup(measurements.distances, 'Distances'),
            this.renderGroup(measurements.angles, 'Angles'),
            this.renderGroup(measurements.dihedrals, 'Dihedrals'));
    };
    return MeasurementList;
}(_base__WEBPACK_IMPORTED_MODULE_6__["PurePluginUIComponent"]));

var MeasurementControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MeasurementControls, _super);
    function MeasurementControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isBusy: false, action: void 0 };
        _this.measureDistance = function () {
            var loci = _this.plugin.managers.structure.selection.additionsHistory;
            _this.plugin.managers.structure.measurement.addDistance(loci[0].loci, loci[1].loci);
        };
        _this.measureAngle = function () {
            var loci = _this.plugin.managers.structure.selection.additionsHistory;
            _this.plugin.managers.structure.measurement.addAngle(loci[0].loci, loci[1].loci, loci[2].loci);
        };
        _this.measureDihedral = function () {
            var loci = _this.plugin.managers.structure.selection.additionsHistory;
            _this.plugin.managers.structure.measurement.addDihedral(loci[0].loci, loci[1].loci, loci[2].loci, loci[3].loci);
        };
        _this.addLabel = function () {
            var loci = _this.plugin.managers.structure.selection.additionsHistory;
            _this.plugin.managers.structure.measurement.addLabel(loci[0].loci);
        };
        _this.selectAction = function (item) {
            _this.toggleAdd();
            if (!item)
                return;
            (item === null || item === void 0 ? void 0 : item.value)();
        };
        _this.toggleAdd = function () { return _this.setState({ action: _this.state.action === 'add' ? void 0 : 'add' }); };
        _this.toggleOptions = function () { return _this.setState({ action: _this.state.action === 'options' ? void 0 : 'options' }); };
        return _this;
    }
    MeasurementControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.selection.events.additionsHistoryUpdated, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(MeasurementControls.prototype, "selection", {
        get: function () {
            return this.plugin.managers.structure.selection;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MeasurementControls.prototype, "actions", {
        get: function () {
            var history = this.selection.additionsHistory;
            var ret = [
                { kind: 'item', label: "Label " + (history.length === 0 ? ' (1 selection required)' : ' (1st selection)'), value: this.addLabel, disabled: history.length === 0 },
                { kind: 'item', label: "Distance " + (history.length < 2 ? ' (2 selections required)' : ' (top 2 selections)'), value: this.measureDistance, disabled: history.length < 2 },
                { kind: 'item', label: "Angle " + (history.length < 3 ? ' (3 selections required)' : ' (top 3 selections)'), value: this.measureAngle, disabled: history.length < 3 },
                { kind: 'item', label: "Dihedral " + (history.length < 4 ? ' (4 selections required)' : ' (top 4 selections)'), value: this.measureDihedral, disabled: history.length < 4 },
            ];
            return ret;
        },
        enumerable: false,
        configurable: true
    });
    MeasurementControls.prototype.highlight = function (loci) {
        this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci: loci }, false);
    };
    MeasurementControls.prototype.moveHistory = function (e, direction) {
        this.plugin.managers.structure.selection.modifyHistory(e, direction, 4);
    };
    MeasurementControls.prototype.focusLoci = function (loci) {
        this.plugin.managers.camera.focusLoci(loci);
    };
    MeasurementControls.prototype.historyEntry = function (e, idx) {
        var _this = this;
        var history = this.plugin.managers.structure.selection.additionsHistory;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row', key: e.id },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["Button"], { noOverflow: true, title: 'Click to focus. Hover to highlight.', onClick: function () { return _this.focusLoci(e.loci); }, style: { width: 'auto', textAlign: 'left' }, onMouseEnter: function () { return _this.highlight(e.loci); }, onMouseLeave: this.plugin.managers.interactivity.lociHighlights.clearHighlights },
                idx,
                ". ",
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { dangerouslySetInnerHTML: { __html: e.label } })),
            history.length > 1 && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["ArrowUpwardSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.moveHistory(e, 'up'); }, flex: '20px', title: 'Move up' }),
            history.length > 1 && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["ArrowDownwardSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.moveHistory(e, 'down'); }, flex: '20px', title: 'Move down' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["DeleteOutlinedSvg"], small: true, className: 'msp-form-control', onClick: function () { return _this.plugin.managers.structure.selection.modifyHistory(e, 'remove'); }, flex: true, title: 'Remove' }));
    };
    MeasurementControls.prototype.add = function () {
        var history = this.plugin.managers.structure.selection.additionsHistory;
        var entries = [];
        for (var i = 0, _i = Math.min(history.length, 4); i < _i; i++) {
            entries.push(this.historyEntry(history[i], i + 1));
        }
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_7__[/* ActionMenu */ "a"], { items: this.actions, onSelect: this.selectAction }),
            entries.length > 0 && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-offset' }, entries),
            entries.length === 0 && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-offset msp-help-text' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-help-description' },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_9__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["HelpOutlineSvg"], inline: true }),
                    "Add one or more selections (toggle ",
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_selection__WEBPACK_IMPORTED_MODULE_12__["ToggleSelectionModeButton"], { inline: true }),
                    " mode)")));
    };
    MeasurementControls.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["AddSvg"], label: 'Add', toggle: this.toggleAdd, isSelected: this.state.action === 'add', disabled: this.state.isBusy, className: 'msp-btn-apply-simple' }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["ToggleButton"], { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["TuneSvg"], label: '', title: 'Options', toggle: this.toggleOptions, isSelected: this.state.action === 'options', disabled: this.state.isBusy, style: { flex: '0 0 40px', padding: 0 } })),
            this.state.action === 'add' && this.add(),
            this.state.action === 'options' && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](MeasurementsOptions, null));
    };
    return MeasurementControls;
}(_base__WEBPACK_IMPORTED_MODULE_6__["PurePluginUIComponent"]));

var MeasurementsOptions = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MeasurementsOptions, _super);
    function MeasurementsOptions() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isDisabled: false };
        _this.changed = function (options) {
            _this.plugin.managers.structure.measurement.setOptions(options);
        };
        return _this;
    }
    MeasurementsOptions.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.measurement.behaviors.state, function () {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isDisabled: v });
        });
    };
    MeasurementsOptions.prototype.render = function () {
        var measurements = this.plugin.managers.structure.measurement.state;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-control-offset' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_10__["ParameterControls"], { params: _mol_plugin_state_manager_structure_measurement__WEBPACK_IMPORTED_MODULE_3__[/* StructureMeasurementParams */ "b"], values: measurements.options, onChangeValues: this.changed, isDisabled: this.state.isDisabled }));
    };
    return MeasurementsOptions;
}(_base__WEBPACK_IMPORTED_MODULE_6__["PurePluginUIComponent"]));
var MeasurementEntry = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MeasurementEntry, _super);
    function MeasurementEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { showUpdate: false };
        _this.delete = function () {
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.RemoveObject(_this.plugin, { state: _this.props.cell.parent, ref: _this.props.cell.transform.parent, removeParentGhosts: true });
        };
        _this.toggleVisibility = function (e) {
            e.preventDefault();
            _mol_plugin_commands__WEBPACK_IMPORTED_MODULE_4__["PluginCommands"].State.ToggleVisibility(_this.plugin, { state: _this.props.cell.parent, ref: _this.props.cell.transform.parent });
            e.currentTarget.blur();
        };
        _this.highlight = function () {
            var _a;
            var selections = _this.selections;
            if (!selections)
                return;
            _this.plugin.managers.interactivity.lociHighlights.clearHighlights();
            for (var _b = 0, _c = selections.data; _b < _c.length; _b++) {
                var d = _c[_b];
                _this.plugin.managers.interactivity.lociHighlights.highlight({ loci: d.loci }, false);
            }
            _this.plugin.managers.interactivity.lociHighlights.highlight({ loci: (_a = _this.props.cell.obj) === null || _a === void 0 ? void 0 : _a.data.repr.getLoci() }, false);
        };
        _this.clearHighlight = function () {
            _this.plugin.managers.interactivity.lociHighlights.clearHighlights();
        };
        _this.toggleUpdate = function () { return _this.setState({ showUpdate: !_this.state.showUpdate }); };
        _this.focus = function () {
            var selections = _this.selections;
            if (!selections)
                return;
            var sphere = _mol_model_loci__WEBPACK_IMPORTED_MODULE_2__["Loci"].getBundleBoundingSphere(toLociBundle(selections.data));
            if (sphere) {
                _this.plugin.managers.camera.focusSphere(sphere);
            }
        };
        _this.selectAction = function (item) {
            if (!item)
                return;
            _this.setState({ showUpdate: false });
            (item === null || item === void 0 ? void 0 : item.value)();
        };
        return _this;
    }
    MeasurementEntry.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            _this.forceUpdate();
        });
    };
    Object.defineProperty(MeasurementEntry.prototype, "selections", {
        get: function () {
            var _a;
            return (_a = this.props.cell.obj) === null || _a === void 0 ? void 0 : _a.data.source;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MeasurementEntry.prototype, "label", {
        get: function () {
            var selections = this.selections;
            switch (selections === null || selections === void 0 ? void 0 : selections.data.length) {
                case 1: return Object(_mol_theme_label__WEBPACK_IMPORTED_MODULE_5__["lociLabel"])(selections.data[0].loci, { condensed: true });
                case 2: return Object(_mol_theme_label__WEBPACK_IMPORTED_MODULE_5__["distanceLabel"])(toLociBundle(selections.data), { condensed: true, unitLabel: this.plugin.managers.structure.measurement.state.options.distanceUnitLabel });
                case 3: return Object(_mol_theme_label__WEBPACK_IMPORTED_MODULE_5__["angleLabel"])(toLociBundle(selections.data), { condensed: true });
                case 4: return Object(_mol_theme_label__WEBPACK_IMPORTED_MODULE_5__["dihedralLabel"])(toLociBundle(selections.data), { condensed: true });
                default: return '';
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(MeasurementEntry.prototype, "actions", {
        get: function () {
            var _this = this;
            this.props.cell.sourceRef;
            return [_controls_action_menu__WEBPACK_IMPORTED_MODULE_7__[/* ActionMenu */ "a"].Item('Select This', function () { return _this.plugin.managers.structure.selection.fromSelections(_this.props.cell.sourceRef); }, { icon: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["SetSvg"] })];
        },
        enumerable: false,
        configurable: true
    });
    MeasurementEntry.prototype.render = function () {
        var cell = this.props.cell;
        var obj = cell.obj;
        if (!obj)
            return null;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-flex-row', key: obj.id, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("button", { className: 'msp-form-control msp-control-button-label msp-no-overflow', title: 'Click to focus. Hover to highlight.', onClick: this.focus, style: { width: 'auto', textAlign: 'left' } },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("span", { dangerouslySetInnerHTML: { __html: this.label } })),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: cell.state.isHidden ? _controls_icons__WEBPACK_IMPORTED_MODULE_9__["VisibilityOffOutlinedSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_9__["VisibilityOutlinedSvg"], toggleState: false, small: true, className: 'msp-form-control', onClick: this.toggleVisibility, flex: true, title: cell.state.isHidden ? 'Show' : 'Hide' }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["DeleteOutlinedSvg"], small: true, className: 'msp-form-control', onClick: this.delete, flex: true, title: 'Delete', toggleState: false }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_9__["MoreHorizSvg"], className: 'msp-form-control', onClick: this.toggleUpdate, flex: true, title: 'Actions', toggleState: this.state.showUpdate })),
            this.state.showUpdate && cell.parent && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-accent-offset' },
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_action_menu__WEBPACK_IMPORTED_MODULE_7__[/* ActionMenu */ "a"], { items: this.actions, onSelect: this.selectAction, noOffset: true }),
                    react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_8__["ExpandGroup"], { header: 'Options', noOffset: true },
                        react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_state_update_transform__WEBPACK_IMPORTED_MODULE_11__["UpdateTransformControl"], { state: cell.parent, transform: cell.transform, customHeader: 'none', autoHideApply: true })))));
    };
    return MeasurementEntry;
}(_base__WEBPACK_IMPORTED_MODULE_6__["PurePluginUIComponent"]));
function toLociBundle(data) {
    return { loci: data.map(function (d) { return d.loci; }) };
}
//# sourceMappingURL=measurements.js.map

/***/ }),
/* 387 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "StateObjectActions", function() { return StateObjectActions; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(14);
/* harmony import */ var _apply_action__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(310);
/**
 * Copyright (c) 2018 - 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var StateObjectActions = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(StateObjectActions, _super);
    function StateObjectActions() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(StateObjectActions.prototype, "current", {
        get: function () {
            return this.props.state.behaviors.currentObject.value;
        },
        enumerable: false,
        configurable: true
    });
    StateObjectActions.prototype.componentDidMount = function () {
        // TODO: handle tree change: some state actions might become invalid
        // this.subscribe(this.props.state.events.changed, o => {
        //     this.setState(createStateObjectActionSelectState(this.props));
        // });
        var _this = this;
        this.subscribe(this.plugin.state.events.object.updated, function (_a) {
            var ref = _a.ref, state = _a.state;
            var current = _this.current;
            if (current.ref !== ref || current.state !== state)
                return;
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.data.actions.events.added, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.state.data.actions.events.removed, function () { return _this.forceUpdate(); });
    };
    StateObjectActions.prototype.render = function () {
        var _this = this;
        var _a = this.props, state = _a.state, ref = _a.nodeRef;
        var cell = state.cells.get(ref);
        var actions = state.actions.fromCell(cell, this.plugin);
        if (actions.length === 0)
            return null;
        var def = cell.transform.transformer.definition;
        var display = cell.obj ? cell.obj.label : (def.display && def.display.name) || def.name;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-state-actions' },
            !this.props.hideHeader && react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-section-header' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_icons__WEBPACK_IMPORTED_MODULE_3__["Icon"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_3__["CodeSvg"] }),
                " ", "Actions (" + display + ")"),
            actions.map(function (act, i) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_apply_action__WEBPACK_IMPORTED_MODULE_4__[/* ApplyActionControl */ "a"], { key: "" + act.id, state: state, action: act, nodeRef: ref, initiallyCollapsed: i === 0 ? !_this.props.alwaysExpandFirst && _this.props.initiallyCollapsed : _this.props.initiallyCollapsed }); }));
    };
    return StateObjectActions;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PluginUIComponent"]));

//# sourceMappingURL=actions.js.map

/***/ }),
/* 388 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return debounceTime; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(21);
/* harmony import */ var _Subscriber__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(35);
/* harmony import */ var _scheduler_async__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(103);
/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */



function debounceTime(dueTime, scheduler) {
    if (scheduler === void 0) {
        scheduler = _scheduler_async__WEBPACK_IMPORTED_MODULE_2__[/* async */ "a"];
    }
    return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); };
}
var DebounceTimeOperator = /*@__PURE__*/ (function () {
    function DebounceTimeOperator(dueTime, scheduler) {
        this.dueTime = dueTime;
        this.scheduler = scheduler;
    }
    DebounceTimeOperator.prototype.call = function (subscriber, source) {
        return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler));
    };
    return DebounceTimeOperator;
}());
var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) {
    tslib__WEBPACK_IMPORTED_MODULE_0__[/* __extends */ "a"](DebounceTimeSubscriber, _super);
    function DebounceTimeSubscriber(destination, dueTime, scheduler) {
        var _this = _super.call(this, destination) || this;
        _this.dueTime = dueTime;
        _this.scheduler = scheduler;
        _this.debouncedSubscription = null;
        _this.lastValue = null;
        _this.hasValue = false;
        return _this;
    }
    DebounceTimeSubscriber.prototype._next = function (value) {
        this.clearDebounce();
        this.lastValue = value;
        this.hasValue = true;
        this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext, this.dueTime, this));
    };
    DebounceTimeSubscriber.prototype._complete = function () {
        this.debouncedNext();
        this.destination.complete();
    };
    DebounceTimeSubscriber.prototype.debouncedNext = function () {
        this.clearDebounce();
        if (this.hasValue) {
            var lastValue = this.lastValue;
            this.lastValue = null;
            this.hasValue = false;
            this.destination.next(lastValue);
        }
    };
    DebounceTimeSubscriber.prototype.clearDebounce = function () {
        var debouncedSubscription = this.debouncedSubscription;
        if (debouncedSubscription !== null) {
            this.remove(debouncedSubscription);
            debouncedSubscription.unsubscribe();
            this.debouncedSubscription = null;
        }
    };
    return DebounceTimeSubscriber;
}(_Subscriber__WEBPACK_IMPORTED_MODULE_1__[/* Subscriber */ "a"]));
function dispatchNext(subscriber) {
    subscriber.debouncedNext();
}
//# sourceMappingURL=debounceTime.js.map


/***/ }),
/* 389 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BackgroundTaskProgress", function() { return BackgroundTaskProgress; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(102);
/* harmony import */ var immutable__WEBPACK_IMPORTED_MODULE_3___default = /*#__PURE__*/__webpack_require__.n(immutable__WEBPACK_IMPORTED_MODULE_3__);
/* harmony import */ var rxjs_operators__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(169);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(14);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var BackgroundTaskProgress = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BackgroundTaskProgress, _super);
    function BackgroundTaskProgress() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { tracked: Object(immutable__WEBPACK_IMPORTED_MODULE_3__["OrderedMap"])() };
        return _this;
    }
    BackgroundTaskProgress.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.task.progress.pipe(Object(rxjs_operators__WEBPACK_IMPORTED_MODULE_4__[/* filter */ "a"])(function (e) { return e.level !== 'none'; })), function (e) {
            _this.setState({ tracked: _this.state.tracked.set(e.id, e) });
        });
        this.subscribe(this.plugin.events.task.finished, function (_a) {
            var id = _a.id;
            _this.setState({ tracked: _this.state.tracked.delete(id) });
        });
    };
    BackgroundTaskProgress.prototype.render = function () {
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-background-tasks' }, this.state.tracked.valueSeq().map(function (e) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ProgressEntry, { key: e.id, event: e }); }));
    };
    return BackgroundTaskProgress;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PluginUIComponent"]));

var ProgressEntry = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ProgressEntry, _super);
    function ProgressEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.abort = function () {
            _this.plugin.requestTaskAbort(_this.props.event.progress, 'User Request');
        };
        return _this;
    }
    ProgressEntry.prototype.render = function () {
        var root = this.props.event.progress.root;
        var subtaskCount = countSubtasks(this.props.event.progress.root) - 1;
        var pr = root.progress.isIndeterminate
            ? void 0
            : react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
                "[",
                root.progress.current,
                "/",
                root.progress.max,
                "]");
        var subtasks = subtaskCount > 0
            ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"](react__WEBPACK_IMPORTED_MODULE_1__["Fragment"], null,
                "[",
                subtaskCount,
                " subtask(s)]")
            : void 0;
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-task-state' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                root.progress.canAbort && react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_5__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_6__["CancelSvg"], onClick: this.abort, title: 'Abort' }),
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                    root.progress.message,
                    " ",
                    pr,
                    " ",
                    subtasks)));
    };
    return ProgressEntry;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PluginUIComponent"]));
function countSubtasks(progress) {
    if (progress.children.length === 0)
        return 1;
    var sum = 0;
    for (var _i = 0, _a = progress.children; _i < _a.length; _i++) {
        var c = _a[_i];
        sum += countSubtasks(c);
    }
    return sum;
}
//# sourceMappingURL=task.js.map

/***/ }),
/* 390 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "Toasts", function() { return Toasts; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_1__);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(32);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(19);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(14);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from LiteMol (c) David Sehnal
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var ToastEntry = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ToastEntry, _super);
    function ToastEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.hide = function () {
            var entry = _this.props.entry;
            (entry.hide || function () { }).call(null);
        };
        return _this;
    }
    ToastEntry.prototype.render = function () {
        var _this = this;
        var entry = this.props.entry;
        var message = typeof entry.message === 'string'
            ? react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { dangerouslySetInnerHTML: { __html: entry.message } })
            : react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", null,
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](entry.message, null));
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-entry' },
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-title', onClick: function () { return _this.hide(); } }, entry.title),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-message' }, message),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-clear' }),
            react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-hide' },
                react__WEBPACK_IMPORTED_MODULE_1__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_3__["IconButton"], { svg: _controls_icons__WEBPACK_IMPORTED_MODULE_4__["CancelSvg"], onClick: this.hide, title: 'Hide', className: 'msp-no-hover-outline' })));
    };
    return ToastEntry;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PluginUIComponent"]));
var Toasts = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Toasts, _super);
    function Toasts() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Toasts.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.toast.events.changed, function () { return _this.forceUpdate(); });
    };
    Toasts.prototype.render = function () {
        var state = this.plugin.managers.toast.state;
        if (!state.entries.count())
            return null;
        var entries = [];
        state.entries.forEach(function (t, k) { return entries.push(t); });
        entries.sort(function (x, y) { return x.serialNumber - y.serialNumber; });
        return react__WEBPACK_IMPORTED_MODULE_1__["createElement"]("div", { className: 'msp-toast-container' }, entries.map(function (e) { return react__WEBPACK_IMPORTED_MODULE_1__["createElement"](ToastEntry, { key: e.serialNumber, entry: e }); }));
    };
    return Toasts;
}(_base__WEBPACK_IMPORTED_MODULE_2__["PluginUIComponent"]));

//# sourceMappingURL=toast.js.map

/***/ }),
/* 391 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "StructureSourceControls", function() { return /* binding */ source_StructureSourceControls; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var mol_plugin_ui_base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/action-menu.js
var action_menu = __webpack_require__(56);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/dynamic/representation.js
var representation = __webpack_require__(223);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/binding.js
var mol_util_binding = __webpack_require__(59);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/memoize.js
var memoize = __webpack_require__(155);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/focus.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function addSymmetryGroupEntries(entries, location, unitSymmetryGroup, granularity) {
    var idx = mol_data_int["SortedArray"].indexOf(location.unit.elements, location.element);
    var base = mol_model_structure["StructureElement"].Loci(location.structure, [
        { unit: location.unit, indices: mol_data_int["OrderedSet"].ofSingleton(idx) }
    ]);
    var extended = granularity === 'residue'
        ? mol_model_structure["StructureElement"].Loci.extendToWholeResidues(base)
        : mol_model_structure["StructureElement"].Loci.extendToWholeChains(base);
    var name = mol_model_structure["StructureProperties"].entity.pdbx_description(location).join(', ');
    for (var _i = 0, _a = unitSymmetryGroup.units; _i < _a.length; _i++) {
        var u = _a[_i];
        var loci = mol_model_structure["StructureElement"].Loci(extended.structure, [
            { unit: u, indices: extended.elements[0].indices }
        ]);
        var label = Object(mol_theme_label["lociLabel"])(loci, { reverse: true, hidePrefix: true, htmlStyling: false, granularity: granularity });
        if (!label)
            label = Object(mol_theme_label["lociLabel"])(loci, { hidePrefix: false, htmlStyling: false });
        if (unitSymmetryGroup.units.length > 1) {
            label += " | " + loci.elements[0].unit.conformation.operator.name;
        }
        var item = { label: label, category: name, loci: loci };
        if (entries.has(name))
            entries.get(name).push(item);
        else
            entries.set(name, [item]);
    }
}
function getFocusEntries(structure) {
    var entityEntries = new Map();
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    for (var _i = 0, _a = structure.unitSymmetryGroups; _i < _a.length; _i++) {
        var ug = _a[_i];
        if (!mol_model_structure["Unit"].isAtomic(ug.units[0]))
            continue;
        l.unit = ug.units[0];
        l.element = ug.elements[0];
        var isMultiChain = mol_model_structure["Unit"].Traits.is(l.unit.traits, 1 /* MultiChain */);
        var entityType = mol_model_structure["StructureProperties"].entity.type(l);
        var isPolymer = entityType === 'non-polymer';
        var isBranched = entityType === 'branched';
        var isBirdMolecule = !!mol_model_structure["StructureProperties"].entity.prd_id(l);
        if (isBirdMolecule) {
            addSymmetryGroupEntries(entityEntries, l, ug, 'chain');
        }
        else if (isPolymer && !isMultiChain) {
            addSymmetryGroupEntries(entityEntries, l, ug, 'residue');
        }
        else if (isBranched || (isPolymer && isMultiChain)) {
            var u = l.unit;
            var residueIndex = u.model.atomicHierarchy.residueAtomSegments.index;
            var prev = -1;
            for (var i = 0, il = u.elements.length; i < il; ++i) {
                var eI = u.elements[i];
                var rI = residueIndex[eI];
                if (rI !== prev) {
                    l.element = eI;
                    addSymmetryGroupEntries(entityEntries, l, ug, 'residue');
                    prev = rI;
                }
            }
        }
    }
    var entries = [];
    entityEntries.forEach(function (e, name) {
        if (e.length === 1) {
            entries.push({ label: name + ": " + e[0].label, loci: e[0].loci });
        }
        else {
            entries.push.apply(entries, e);
        }
    });
    return entries;
}
var focus_StructureFocusControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureFocusControls, _super);
    function StructureFocusControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { isBusy: false, showAction: false };
        _this.getSelectionItems = Object(memoize["b" /* memoizeLatest */])(function (structures) {
            var _a;
            var presetItems = [];
            for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
                var s = structures_1[_i];
                var d = (_a = s.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
                if (d) {
                    var entries = getFocusEntries(d);
                    if (entries.length > 0) {
                        presetItems.push(Object(tslib_es6["__spreadArrays"])([
                            action_menu["a" /* ActionMenu */].Header(d.label, { description: d.label })
                        ], action_menu["a" /* ActionMenu */].createItems(entries, {
                            label: function (f) { return f.label; },
                            category: function (f) { return f.category; },
                            description: function (f) { return f.label; }
                        })));
                    }
                }
            }
            return presetItems;
        });
        _this.selectAction = function (item, e) {
            if (!item || !_this.state.showAction) {
                _this.setState({ showAction: false });
                return;
            }
            var f = item.value;
            if (e === null || e === void 0 ? void 0 : e.shiftKey) {
                _this.plugin.managers.structure.focus.addFromLoci(f.loci);
            }
            else {
                _this.plugin.managers.structure.focus.set(f);
            }
            _this.focusCamera();
        };
        _this.toggleAction = function () { return _this.setState({ showAction: !_this.state.showAction }); };
        _this.focusCamera = function () {
            var current = _this.plugin.managers.structure.focus.current;
            if (current)
                _this.plugin.managers.camera.focusLoci(current.loci);
        };
        _this.clear = function () {
            _this.plugin.managers.structure.focus.clear();
            _this.plugin.managers.camera.reset();
        };
        _this.highlightCurrent = function () {
            var current = _this.plugin.managers.structure.focus.current;
            if (current)
                _this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci: current.loci }, false);
        };
        _this.clearHighlights = function () {
            _this.plugin.managers.interactivity.lociHighlights.clearHighlights();
        };
        return _this;
    }
    StructureFocusControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.focus.behaviors.current, function (c) {
            // clear the memo cache
            _this.getSelectionItems([]);
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.managers.structure.focus.events.historyUpdated, function (c) {
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v, showAction: false });
        });
    };
    Object.defineProperty(StructureFocusControls.prototype, "isDisabled", {
        get: function () {
            return this.state.isBusy || this.actionItems.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureFocusControls.prototype, "actionItems", {
        get: function () {
            var historyItems = [];
            var history = this.plugin.managers.structure.focus.history;
            if (history.length > 0) {
                historyItems.push(Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('History', { description: 'Previously focused on items.' })
                ], action_menu["a" /* ActionMenu */].createItems(history, {
                    label: function (f) { return f.label; },
                    description: function (f) {
                        return f.category && f.label !== f.category
                            ? f.category + " | " + f.label
                            : f.label;
                    }
                })));
            }
            var presetItems = this.getSelectionItems(this.plugin.managers.structure.hierarchy.selection.structures);
            if (presetItems.length === 1) {
                var item = presetItems[0];
                var header = item[0];
                header.initiallyExpanded = true;
            }
            var items = [];
            if (presetItems.length > 0)
                items.push.apply(items, presetItems);
            if (historyItems.length > 0)
                items.push.apply(items, historyItems);
            return items;
        },
        enumerable: false,
        configurable: true
    });
    StructureFocusControls.prototype.getToggleBindingLabel = function () {
        var _a;
        var t = this.plugin.state.behaviors.transforms.get(representation["FocusLoci"].id);
        if (!t)
            return '';
        var binding = (_a = t.params) === null || _a === void 0 ? void 0 : _a.bindings.clickFocus;
        if (!binding || mol_util_binding["a" /* Binding */].isEmpty(binding))
            return '';
        return mol_util_binding["a" /* Binding */].formatTriggers(binding);
    };
    StructureFocusControls.prototype.render = function () {
        var current = this.plugin.managers.structure.focus.current;
        var label = (current === null || current === void 0 ? void 0 : current.label) || 'Nothing Focused';
        var title = 'Click to Center Camera';
        if (!current) {
            title = 'Select focus using the menu';
            var binding = this.getToggleBindingLabel();
            if (binding) {
                title += "\nor use '" + binding + "' on element";
            }
        }
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row' },
                react["createElement"](common["Button"], { noOverflow: true, onClick: this.focusCamera, title: title, onMouseEnter: this.highlightCurrent, onMouseLeave: this.clearHighlights, disabled: this.isDisabled || !current, style: { textAlignLast: current ? 'left' : void 0 } }, label),
                current && react["createElement"](common["IconButton"], { svg: icons["CancelOutlinedSvg"], onClick: this.clear, title: 'Clear', className: 'msp-form-control', flex: true, disabled: this.isDisabled }),
                react["createElement"](common["ToggleButton"], { icon: icons["CenterFocusStrongSvg"], title: 'Select a focus target to center on an show its surroundings. Hold shift to focus on multiple targets.', toggle: this.toggleAction, isSelected: this.state.showAction, disabled: this.isDisabled, style: { flex: '0 0 40px', padding: 0 } })),
            this.state.showAction && react["createElement"](action_menu["a" /* ActionMenu */], { items: this.actionItems, onSelect: this.selectAction }));
    };
    return StructureFocusControls;
}(mol_plugin_ui_base["PluginUIComponent"]));

//# sourceMappingURL=focus.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/update-transform.js
var update_transform = __webpack_require__(183);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/selection.js
var structure_selection = __webpack_require__(206);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/structure/source.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var source_StructureSourceControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureSourceControls, _super);
    function StructureSourceControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.item = function (ref) {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j;
            var selected = _this.plugin.managers.structure.hierarchy.seletionSet;
            var label;
            switch (ref.kind) {
                case 'model': {
                    var model = (_a = ref.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
                    if (model && mol_model_structure["Model"].TrajectoryInfo.get(model).size > 1) {
                        label = ((_b = ref.cell.obj) === null || _b === void 0 ? void 0 : _b.data.entryId) + " | Model " + (mol_model_structure["Model"].TrajectoryInfo.get(model).index + 1) + " of " + mol_model_structure["Model"].TrajectoryInfo.get(model).size;
                    }
                    label = ((_c = ref.cell.obj) === null || _c === void 0 ? void 0 : _c.data.entryId) + " | " + ((_d = ref.cell.obj) === null || _d === void 0 ? void 0 : _d.label);
                    break;
                }
                case 'structure': {
                    var model = (_e = ref.cell.obj) === null || _e === void 0 ? void 0 : _e.data.models[0];
                    if (model && mol_model_structure["Model"].TrajectoryInfo.get(model).size > 1) {
                        label = model.entryId + " | " + ((_f = ref.cell.obj) === null || _f === void 0 ? void 0 : _f.label) + " (Model " + (mol_model_structure["Model"].TrajectoryInfo.get(model).index + 1) + " of " + mol_model_structure["Model"].TrajectoryInfo.get(model).size + ")";
                        break;
                    }
                    else if (model) {
                        label = model.entryId + " | " + ((_g = ref.cell.obj) === null || _g === void 0 ? void 0 : _g.label);
                        break;
                    }
                    else {
                        label = "" + ((_h = ref.cell.obj) === null || _h === void 0 ? void 0 : _h.label);
                        break;
                    }
                }
                default:
                    label = (_j = ref.cell.obj) === null || _j === void 0 ? void 0 : _j.label;
                    break;
            }
            var item = { kind: 'item', label: label || ref.kind, selected: selected.has(ref.cell.transform.ref), value: [ref] };
            return item;
        };
        _this.getTrajectoryItems = function (t) {
            var _a;
            if (t.models.length === 0)
                return _this.item(t);
            return Object(tslib_es6["__spreadArrays"])([action_menu["a" /* ActionMenu */].Header((_a = t.cell.obj) === null || _a === void 0 ? void 0 : _a.label)], t.models.map(_this.getModelItems));
        };
        _this.getModelItems = function (m) {
            var _a, _b, _c;
            if (m.structures.length === 0)
                return _this.item(m);
            if (m.structures.length === 1) {
                var selected = _this.plugin.managers.structure.hierarchy.seletionSet;
                var ref = m.structures[0];
                return { label: ((_a = m.cell.obj) === null || _a === void 0 ? void 0 : _a.label) + " | " + ((_b = ref.cell.obj) === null || _b === void 0 ? void 0 : _b.label), selected: selected.has(ref.cell.transform.ref), value: [m, ref] };
            }
            return Object(tslib_es6["__spreadArrays"])([action_menu["a" /* ActionMenu */].Header((_c = m.cell.obj) === null || _c === void 0 ? void 0 : _c.label)], m.structures.map(_this.item));
        };
        _this.selectHierarchy = function (items) {
            if (!items || items.length === 0)
                return;
            var refs = [];
            for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
                var i = items_1[_i];
                for (var _a = 0, _b = i.value; _a < _b.length; _a++) {
                    var r = _b[_a];
                    refs.push(r);
                }
            }
            _this.plugin.managers.structure.hierarchy.updateCurrent(refs, items[0].selected ? 'remove' : 'add');
        };
        _this.toggleHierarchy = function () { return _this.setState({ show: _this.state.show !== 'hierarchy' ? 'hierarchy' : void 0 }); };
        _this.togglePreset = function () { return _this.setState({ show: _this.state.show !== 'presets' ? 'presets' : void 0 }); };
        _this.applyPreset = function (item) {
            _this.setState({ show: void 0 });
            if (!item)
                return;
            var mng = _this.plugin.managers.structure;
            var trajectories = mng.hierarchy.selection.trajectories;
            mng.hierarchy.applyPreset(trajectories, item.value);
        };
        _this.updateStructureModel = function (params) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var selection, m;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                selection = this.plugin.managers.structure.hierarchy.selection;
                m = selection.structures[0].model;
                this.plugin.state.updateTransform(this.plugin.state.data, m.cell.transform.ref, params, 'Model Index');
                return [2 /*return*/];
            });
        }); };
        _this.updateStructure = function (params) {
            var selection = _this.plugin.managers.structure.hierarchy.selection;
            var s = selection.structures[0];
            return _this.plugin.managers.structure.hierarchy.updateStructure(s, params);
        };
        return _this;
    }
    StructureSourceControls.prototype.defaultState = function () {
        return {
            header: 'Structure',
            isCollapsed: false,
            isBusy: false,
            brand: { accent: 'purple', svg: icons["MoleculeSvg"] }
        };
    };
    StructureSourceControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    Object.defineProperty(StructureSourceControls.prototype, "hierarchyItems", {
        get: function () {
            var mng = this.plugin.managers.structure.hierarchy;
            var current = mng.current;
            var ret = [];
            if (current.trajectories.length > 1) {
                ret.push(Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('Trajectories')
                ], current.trajectories.map(this.item)));
            }
            if (current.models.length > 1 || current.trajectories.length > 1) {
                ret.push(Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('Models')
                ], current.models.map(this.item)));
            }
            if (current.trajectories.length === 1 && current.models.length === 1) {
                ret.push.apply(ret, current.structures.map(this.item));
            }
            else if (current.structures.length > 0) {
                ret.push(Object(tslib_es6["__spreadArrays"])([
                    action_menu["a" /* ActionMenu */].Header('Structures')
                ], current.structures.map(this.item)));
            }
            return ret;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "isEmpty", {
        get: function () {
            var _a = this.plugin.managers.structure.hierarchy.current, structures = _a.structures, models = _a.models, trajectories = _a.trajectories;
            return trajectories.length === 0 && models.length === 0 && structures.length === 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "label", {
        get: function () {
            var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
            var _q = this.plugin.managers.structure.hierarchy.selection, structures = _q.structures, models = _q.models, trajectories = _q.trajectories;
            if (structures.length === 1) {
                var s = structures[0];
                if (((_b = (_a = s.model) === null || _a === void 0 ? void 0 : _a.trajectory) === null || _b === void 0 ? void 0 : _b.models) && s.model.trajectory.models.length === 1)
                    return (_c = s.cell.obj) === null || _c === void 0 ? void 0 : _c.data.label;
                if (s.model)
                    return ((_d = s.model.cell.obj) === null || _d === void 0 ? void 0 : _d.label) + " | " + ((_e = s.cell.obj) === null || _e === void 0 ? void 0 : _e.data.label);
                return (_f = s.cell.obj) === null || _f === void 0 ? void 0 : _f.data.label;
            }
            if (structures.length > 1) {
                var p = structures[0];
                var t = (_g = p === null || p === void 0 ? void 0 : p.model) === null || _g === void 0 ? void 0 : _g.trajectory;
                var sameTraj = true;
                for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
                    var s = structures_1[_i];
                    if (((_h = s === null || s === void 0 ? void 0 : s.model) === null || _h === void 0 ? void 0 : _h.trajectory) !== t) {
                        sameTraj = false;
                        break;
                    }
                }
                return sameTraj && t ? ((_j = t.cell.obj) === null || _j === void 0 ? void 0 : _j.label) + " | " + structures.length + " structures" : structures.length + " structures";
            }
            if (models.length > 0) {
                var t = models[0].trajectory;
                if (models.length === 1) {
                    var model = (_k = models[0].cell.obj) === null || _k === void 0 ? void 0 : _k.data;
                    if (model && mol_model_structure["Model"].TrajectoryInfo.get(model).size > 1) {
                        return ((_l = t === null || t === void 0 ? void 0 : t.cell.obj) === null || _l === void 0 ? void 0 : _l.label) + " | Model " + (mol_model_structure["Model"].TrajectoryInfo.get(model).index + 1) + " of " + mol_model_structure["Model"].TrajectoryInfo.get(model).size;
                    }
                    else {
                        return ((_m = t === null || t === void 0 ? void 0 : t.cell.obj) === null || _m === void 0 ? void 0 : _m.label) + " | Model";
                    }
                }
                var sameTraj = true;
                for (var _r = 0, models_1 = models; _r < models_1.length; _r++) {
                    var m = models_1[_r];
                    if (m.trajectory !== t) {
                        sameTraj = false;
                        break;
                    }
                }
                return sameTraj ? ((_o = t === null || t === void 0 ? void 0 : t.cell.obj) === null || _o === void 0 ? void 0 : _o.label) + " | " + models.length + " models" : models.length + " models";
            }
            if (trajectories.length > 0) {
                return trajectories.length === 1 ? ((_p = trajectories[0].cell.obj) === null || _p === void 0 ? void 0 : _p.label) + " trajectory" : trajectories.length + " trajectories";
            }
            if (trajectories.length === 0 && models.length === 0 && structures.length === 0) {
                return 'Nothing Loaded';
            }
            return 'Nothing Selected';
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "presetActions", {
        get: function () {
            var actions = [];
            var trajectories = this.plugin.managers.structure.hierarchy.selection.trajectories;
            if (trajectories.length !== 1)
                return actions;
            var providers = this.plugin.builders.structure.hierarchy.getPresets(trajectories[0].cell.obj);
            for (var _i = 0, providers_1 = providers; _i < providers_1.length; _i++) {
                var p = providers_1[_i];
                actions.push(action_menu["a" /* ActionMenu */].Item(p.display.name, p, { description: p.display.description }));
            }
            return actions;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "modelIndex", {
        get: function () {
            var _a, _b;
            var selection = this.plugin.managers.structure.hierarchy.selection;
            if (selection.structures.length !== 1)
                return null;
            var m = selection.structures[0].model;
            if (!m || m.cell.transform.transformer !== transforms["StateTransforms"].Model.ModelFromTrajectory)
                return null;
            if (!m.cell.obj || mol_model_structure["Model"].TrajectoryInfo.get(m.cell.obj.data).size <= 1)
                return null;
            var params = (_a = m.cell.params) === null || _a === void 0 ? void 0 : _a.definition;
            if (!params)
                return null;
            return react["createElement"](parameters["ParameterControls"], { params: params, values: (_b = m.cell.params) === null || _b === void 0 ? void 0 : _b.values, onChangeValues: this.updateStructureModel, isDisabled: this.state.isBusy });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "structureType", {
        get: function () {
            var _a;
            var selection = this.plugin.managers.structure.hierarchy.selection;
            if (selection.structures.length !== 1)
                return null;
            var s = selection.structures[0];
            var params = (_a = s.cell.params) === null || _a === void 0 ? void 0 : _a.definition;
            if (!params || !s.cell.parent)
                return null;
            return react["createElement"](update_transform["UpdateTransformControl"], { state: s.cell.parent, transform: s.cell.transform, customHeader: 'none', customUpdate: this.updateStructure, noMargin: true, autoHideApply: true });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSourceControls.prototype, "transform", {
        get: function () {
            var selection = this.plugin.managers.structure.hierarchy.selection;
            if (selection.structures.length !== 1)
                return null;
            var pivot = selection.structures[0];
            if (!pivot.cell.parent)
                return null;
            var t = mol_state["StateSelection"].tryFindDecorator(this.plugin.state.data, pivot.cell.transform.ref, transforms["StateTransforms"].Model.TransformStructureConformation);
            if (!t)
                return;
            return react["createElement"](common["ExpandGroup"], { header: "Conformation Transform" },
                react["createElement"](update_transform["UpdateTransformControl"], { state: t.parent, transform: t.transform, customHeader: 'none', noMargin: true, autoHideApply: true }));
        },
        enumerable: false,
        configurable: true
    });
    StructureSourceControls.prototype.renderControls = function () {
        var disabled = this.state.isBusy || this.isEmpty;
        var presets = this.presetActions;
        var label = this.label;
        return react["createElement"](react["Fragment"], null,
            react["createElement"]("div", { className: 'msp-flex-row', style: { marginTop: '1px' } },
                react["createElement"](common["Button"], { noOverflow: true, flex: true, onClick: this.toggleHierarchy, disabled: disabled, title: label }, label),
                presets.length > 0 && react["createElement"](common["IconButton"], { svg: icons["BookmarksOutlinedSvg"], className: 'msp-form-control', flex: '40px', onClick: this.togglePreset, title: 'Apply a structure presets to the current hierarchy.', toggleState: this.state.show === 'presets', disabled: disabled })),
            this.state.show === 'hierarchy' && react["createElement"](action_menu["a" /* ActionMenu */], { items: this.hierarchyItems, onSelect: this.selectHierarchy, multiselect: true }),
            this.state.show === 'presets' && react["createElement"](action_menu["a" /* ActionMenu */], { items: presets, onSelect: this.applyPreset }),
            this.modelIndex,
            this.structureType,
            this.transform,
            react["createElement"]("div", { style: { marginTop: '6px' } },
                react["createElement"](focus_StructureFocusControls, null),
                react["createElement"](structure_selection["StructureSelectionStatsControls"], { hideOnEmpty: true })));
    };
    return StructureSourceControls;
}(mol_plugin_ui_base["CollapsableControls"]));

//# sourceMappingURL=source.js.map

/***/ }),
/* 392 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "SimpleSettingsControl", function() { return /* binding */ simple_settings_SimpleSettingsControl; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/immer/dist/immer.esm.js
var immer_esm = __webpack_require__(151);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/canvas3d.js
var canvas3d = __webpack_require__(158);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/param-mapping.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

function ParamMapping(def) {
    return function (_a) {
        var values = _a.values, update = _a.update, apply = _a.apply;
        return ({
            params: typeof def.params === 'function' ? def.params : function (ctx) { return def.params; },
            getTarget: def.target,
            getValues: values,
            update: function (s, ctx) {
                var t = def.target(ctx);
                return Object(immer_esm["b" /* produce */])(t, function (t1) { return update(s, t1, ctx); });
            },
            apply: apply ? apply : function () { }
        });
    };
}
//# sourceMappingURL=param-mapping.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport/help.js
var help = __webpack_require__(189);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport/simple-settings.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */












var simple_settings_SimpleSettingsControl = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SimpleSettingsControl, _super);
    function SimpleSettingsControl() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SimpleSettingsControl.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.canvas3d.camera.stateChanged, function (state) {
            if (state.radiusMax !== undefined || state.radius !== undefined) {
                _this.forceUpdate();
            }
        });
    };
    SimpleSettingsControl.prototype.render = function () {
        if (!this.plugin.canvas3d)
            return null;
        return react["createElement"](react["Fragment"], null,
            react["createElement"](parameters["ParameterMappingControl"], { mapping: SimpleSettingsMapping }),
            react["createElement"](help["ViewportHelpContent"], null));
    };
    return SimpleSettingsControl;
}(base["PluginUIComponent"]));

var LayoutOptions = {
    'sequence': 'Sequence',
    'log': 'Log',
    'left': 'Left Panel'
};
var SimpleSettingsParams = {
    spin: param_definition["ParamDefinition"].Group({
        spin: canvas3d["Canvas3DParams"].trackball.params.spin,
        speed: canvas3d["Canvas3DParams"].trackball.params.spinSpeed
    }, { pivot: 'spin' }),
    camera: canvas3d["Canvas3DParams"].camera,
    background: param_definition["ParamDefinition"].Group({
        color: param_definition["ParamDefinition"].Color(Object(color["Color"])(0xFCFBF9), { label: 'Background', description: 'Custom background color' }),
        transparent: param_definition["ParamDefinition"].Boolean(false)
    }, { pivot: 'color' }),
    lighting: param_definition["ParamDefinition"].Group({
        renderStyle: canvas3d["Canvas3DParams"].renderer.params.style,
        occlusion: canvas3d["Canvas3DParams"].postprocessing.params.occlusion,
        outline: canvas3d["Canvas3DParams"].postprocessing.params.outline,
        fog: canvas3d["Canvas3DParams"].cameraFog,
    }, { pivot: 'renderStyle' }),
    clipping: param_definition["ParamDefinition"].Group(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, canvas3d["Canvas3DParams"].cameraClipping.params), canvas3d["Canvas3DParams"].renderer.params.clip.params), { pivot: 'radius' }),
    layout: param_definition["ParamDefinition"].MultiSelect([], param_definition["ParamDefinition"].objectToOptions(LayoutOptions)),
};
var SimpleSettingsMapping = ParamMapping({
    params: function (ctx) {
        var _a;
        var params = param_definition["ParamDefinition"].clone(SimpleSettingsParams);
        var controls = (_a = ctx.spec.layout) === null || _a === void 0 ? void 0 : _a.controls;
        if (controls) {
            var options = [];
            if (controls.top !== 'none')
                options.push(['sequence', LayoutOptions.sequence]);
            if (controls.bottom !== 'none')
                options.push(['log', LayoutOptions.log]);
            if (controls.left !== 'none')
                options.push(['left', LayoutOptions.left]);
            params.layout.options = options;
        }
        return params;
    },
    target: function (ctx) {
        var _a, _b;
        var c = (_a = ctx.spec.layout) === null || _a === void 0 ? void 0 : _a.controls;
        var r = ctx.layout.state.regionState;
        var layout = [];
        if (r.top !== 'hidden' && (!c || c.top !== 'none'))
            layout.push('sequence');
        if (r.bottom !== 'hidden' && (!c || c.bottom !== 'none'))
            layout.push('log');
        if (r.left !== 'hidden' && (!c || c.left !== 'none'))
            layout.push('left');
        return { canvas: (_b = ctx.canvas3d) === null || _b === void 0 ? void 0 : _b.props, layout: layout };
    }
})({
    values: function (props, ctx) {
        var canvas = props.canvas;
        var renderer = canvas.renderer;
        return {
            layout: props.layout,
            spin: { spin: !!canvas.trackball.spin, speed: canvas.trackball.spinSpeed },
            camera: canvas.camera,
            background: {
                color: renderer.backgroundColor,
                transparent: canvas.transparentBackground
            },
            lighting: {
                renderStyle: renderer.style,
                occlusion: canvas.postprocessing.occlusion,
                outline: canvas.postprocessing.outline,
                fog: canvas.cameraFog
            },
            clipping: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, canvas.cameraClipping), canvas.renderer.clip)
        };
    },
    update: function (s, props) {
        var canvas = props.canvas;
        canvas.trackball.spin = s.spin.spin;
        canvas.trackball.spinSpeed = s.spin.speed;
        canvas.camera = s.camera;
        canvas.transparentBackground = s.background.transparent;
        canvas.renderer.backgroundColor = s.background.color;
        canvas.renderer.style = s.lighting.renderStyle;
        canvas.postprocessing.occlusion = s.lighting.occlusion;
        canvas.postprocessing.outline = s.lighting.outline;
        canvas.cameraFog = s.lighting.fog;
        canvas.cameraClipping = {
            radius: s.clipping.radius,
            far: s.clipping.far,
        };
        canvas.renderer.clip = {
            variant: s.clipping.variant,
            objects: s.clipping.objects,
        };
        props.layout = s.layout;
    },
    apply: function (props, ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var hideLeft, state;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, commands["PluginCommands"].Canvas3D.SetSettings(ctx, { settings: props.canvas })];
                    case 1:
                        _a.sent();
                        hideLeft = props.layout.indexOf('left') < 0;
                        state = Object(immer_esm["b" /* produce */])(ctx.layout.state, function (s) {
                            s.regionState.top = props.layout.indexOf('sequence') >= 0 ? 'full' : 'hidden';
                            s.regionState.bottom = props.layout.indexOf('log') >= 0 ? 'full' : 'hidden';
                            s.regionState.left = hideLeft ? 'hidden' : ctx.behaviors.layout.leftPanelTabName.value === 'none' ? 'collapsed' : 'full';
                        });
                        return [4 /*yield*/, commands["PluginCommands"].Layout.Update(ctx, { state: state })];
                    case 2:
                        _a.sent();
                        if (hideLeft) {
                            commands["PluginCommands"].State.SetCurrentObject(ctx, { state: ctx.state.data, ref: mol_state["StateTransform"].RootRef });
                        }
                        return [2 /*return*/];
                }
            });
        });
    }
});
//# sourceMappingURL=simple-settings.js.map

/***/ }),
/* 393 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return RendererParams; });
/* harmony import */ var _mol_canvas3d_camera_util__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(176);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _mol_util_color__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(24);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(5);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/* harmony import */ var _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(77);
/* harmony import */ var _mol_util_string__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(41);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var RendererParams = {
    backgroundColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Color(Object(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"])(0x000000), { description: 'Background color of the 3D canvas' }),
    // the following are general 'material' parameters
    pickingAlphaThreshold: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }, { description: 'The minimum opacity value needed for an object to be pickable.' }),
    transparencyVariant: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select('single', _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].arrayToOptions(['single', 'multi'])),
    interiorDarkening: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }),
    interiorColorFlag: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Boolean(true, { label: 'Use Interior Color' }),
    interiorColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Color(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromNormalizedRgb(0.3, 0.3, 0.3)),
    highlightColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Color(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromNormalizedRgb(1.0, 0.4, 0.6)),
    selectColor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Color(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].fromNormalizedRgb(0.2, 1.0, 0.1)),
    style: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].MappedStatic('matte', {
        custom: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
            lightIntensity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.6, { min: 0.0, max: 1.0, step: 0.01 }),
            ambientIntensity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.4, { min: 0.0, max: 1.0, step: 0.01 }),
            metalness: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.0, { min: 0.0, max: 1.0, step: 0.01 }),
            roughness: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(1.0, { min: 0.0, max: 1.0, step: 0.01 }),
            reflectivity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.5, { min: 0.0, max: 1.0, step: 0.01 }),
        }, { isExpanded: true }),
        flat: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
        matte: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
        glossy: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
        metallic: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
        plastic: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({}),
    }, { label: 'Lighting', description: 'Style in which the 3D scene is rendered/lighted' }),
    clip: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
        variant: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select('instance', _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].arrayToOptions(['instance', 'pixel'])),
        objects: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].ObjectList({
            type: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Select('plane', _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].objectToOptions(_mol_theme_clipping__WEBPACK_IMPORTED_MODULE_5__[/* Clipping */ "a"].Type, function (t) { return Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_6__[/* stringToWords */ "d"])(t); })),
            position: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])()),
            rotation: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Group({
                axis: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].create(1, 0, 0)),
                angle: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0, { min: -180, max: 180, step: 0.1 }),
            }, { isExpanded: true }),
            scale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].create(1, 1, 1)),
        }, function (o) { return Object(_mol_util_string__WEBPACK_IMPORTED_MODULE_6__[/* stringToWords */ "d"])(o.type); })
    })
};
function getStyle(props) {
    switch (props.name) {
        case 'custom':
            return props.params;
        case 'flat':
            return {
                lightIntensity: 0, ambientIntensity: 1,
                metalness: 0, roughness: 0.4, reflectivity: 0.5
            };
        case 'matte':
            return {
                lightIntensity: 0.6, ambientIntensity: 0.4,
                metalness: 0, roughness: 1, reflectivity: 0.5
            };
        case 'glossy':
            return {
                lightIntensity: 0.6, ambientIntensity: 0.4,
                metalness: 0, roughness: 0.4, reflectivity: 0.5
            };
        case 'metallic':
            return {
                lightIntensity: 0.6, ambientIntensity: 0.4,
                metalness: 0.4, roughness: 0.6, reflectivity: 0.5
            };
        case 'plastic':
            return {
                lightIntensity: 0.6, ambientIntensity: 0.4,
                metalness: 0, roughness: 0.2, reflectivity: 0.5
            };
    }
}
var tmpQuat = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"])();
function getClip(props, clip) {
    var _a = (clip === null || clip === void 0 ? void 0 : clip.objects) || {
        type: (new Array(5)).fill(1),
        position: (new Array(5 * 3)).fill(0),
        rotation: (new Array(5 * 4)).fill(0),
        scale: (new Array(5 * 3)).fill(1),
    }, type = _a.type, position = _a.position, rotation = _a.rotation, scale = _a.scale;
    for (var i = 0, il = props.objects.length; i < il; ++i) {
        var p = props.objects[i];
        type[i] = _mol_theme_clipping__WEBPACK_IMPORTED_MODULE_5__[/* Clipping */ "a"].Type[p.type];
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].toArray(p.position, position, i * 3);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].toArray(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].setAxisAngle(tmpQuat, p.rotation.axis, p.rotation.angle), rotation, i * 4);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].toArray(p.scale, scale, i * 3);
    }
    return {
        variant: props.variant,
        objects: { count: props.objects.length, type: type, position: position, rotation: rotation, scale: scale }
    };
}
var Renderer;
(function (Renderer) {
    function create(ctx, props) {
        if (props === void 0) { props = {}; }
        var gl = ctx.gl, state = ctx.state, stats = ctx.stats;
        var p = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].merge(RendererParams, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(RendererParams), props);
        var style = getStyle(p.style);
        var clip = getClip(p.clip);
        var viewport = Object(_mol_canvas3d_camera_util__WEBPACK_IMPORTED_MODULE_0__[/* Viewport */ "a"])();
        var bgColor = _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), p.backgroundColor);
        var view = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var invView = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var modelView = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var invModelView = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var invProjection = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var modelViewProjection = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var invModelViewProjection = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])();
        var viewOffset = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var globalUniforms = {
            uModel: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].identity()),
            uView: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(view),
            uInvView: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(invView),
            uModelView: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(modelView),
            uInvModelView: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(invModelView),
            uInvProjection: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(invProjection),
            uProjection: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"])()),
            uModelViewProjection: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(modelViewProjection),
            uInvModelViewProjection: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(invModelViewProjection),
            uIsOrtho: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(1),
            uViewOffset: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(viewOffset),
            uPixelRatio: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(ctx.pixelRatio),
            uViewportHeight: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(viewport.height),
            uViewport: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(_mol_canvas3d_camera_util__WEBPACK_IMPORTED_MODULE_0__[/* Viewport */ "a"].toVec4(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec4"])(), viewport)),
            uCameraPosition: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])()),
            uNear: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(1),
            uFar: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(10000),
            uFogNear: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(1),
            uFogFar: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(10000),
            uFogColor: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(bgColor),
            uTransparentBackground: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(0),
            uClipObjectType: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(clip.objects.type),
            uClipObjectPosition: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(clip.objects.position),
            uClipObjectRotation: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(clip.objects.rotation),
            uClipObjectScale: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(clip.objects.scale),
            // the following are general 'material' uniforms
            uLightIntensity: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(style.lightIntensity),
            uAmbientIntensity: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(style.ambientIntensity),
            uMetalness: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(style.metalness),
            uRoughness: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(style.roughness),
            uReflectivity: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(style.reflectivity),
            uPickingAlphaThreshold: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(p.pickingAlphaThreshold),
            uInteriorDarkening: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(p.interiorDarkening),
            uInteriorColorFlag: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(p.interiorColorFlag ? 1 : 0),
            uInteriorColor: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), p.interiorColor)),
            uHighlightColor: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), p.highlightColor)),
            uSelectColor: _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].create(_mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])(), p.selectColor)),
        };
        var globalUniformList = Object.entries(globalUniforms);
        var globalUniformsNeedUpdate = true;
        var renderObject = function (r, variant) {
            if (!r.state.visible || (!r.state.pickable && variant[0] === 'p')) {
                return;
            }
            var definesNeedUpdate = false;
            if (r.values.dClipObjectCount.ref.value !== clip.objects.count) {
                _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(r.values.dClipObjectCount, clip.objects.count);
                definesNeedUpdate = true;
            }
            if (r.values.dClipVariant.ref.value !== clip.variant) {
                _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(r.values.dClipVariant, clip.variant);
                definesNeedUpdate = true;
            }
            if (r.values.dTransparencyVariant.ref.value !== p.transparencyVariant) {
                _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(r.values.dTransparencyVariant, p.transparencyVariant);
                definesNeedUpdate = true;
            }
            if (definesNeedUpdate)
                r.update();
            var program = r.getProgram(variant);
            if (state.currentProgramId !== program.id) {
                // console.log('new program')
                globalUniformsNeedUpdate = true;
                program.use();
            }
            if (globalUniformsNeedUpdate) {
                // console.log('globalUniformsNeedUpdate')
                program.setUniforms(globalUniformList);
                globalUniformsNeedUpdate = false;
            }
            if (r.values.dDoubleSided) {
                if (r.values.dDoubleSided.ref.value) {
                    state.disable(gl.CULL_FACE);
                }
                else {
                    state.enable(gl.CULL_FACE);
                }
            }
            else {
                // webgl default
                state.disable(gl.CULL_FACE);
            }
            if (r.values.dFlipSided) {
                if (r.values.dFlipSided.ref.value) {
                    state.frontFace(gl.CW);
                    state.cullFace(gl.FRONT);
                }
                else {
                    state.frontFace(gl.CCW);
                    state.cullFace(gl.BACK);
                }
            }
            else {
                // webgl default
                state.frontFace(gl.CCW);
                state.cullFace(gl.BACK);
            }
            if (variant === 'color') {
                state.depthMask(r.state.writeDepth);
            }
            r.render(variant);
        };
        var render = function (scene, camera, variant, clear, transparentBackground) {
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uModel, scene.view);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uView, camera.view);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInvView, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].invert(invView, camera.view));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uModelView, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mul(modelView, scene.view, camera.view));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInvModelView, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].invert(invModelView, modelView));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uProjection, camera.projection);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInvProjection, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].invert(invProjection, camera.projection));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uModelViewProjection, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].mul(modelViewProjection, modelView, camera.projection));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInvModelViewProjection, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Mat4"].invert(invModelViewProjection, modelViewProjection));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uIsOrtho, camera.state.mode === 'orthographic' ? 1 : 0);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uViewOffset, camera.viewOffset.enabled ? _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].set(viewOffset, camera.viewOffset.offsetX * 16, camera.viewOffset.offsetY * 16) : _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].set(viewOffset, 0, 0));
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uCameraPosition, camera.state.position);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uFar, camera.far);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uNear, camera.near);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uFogFar, camera.fogFar);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uFogNear, camera.fogNear);
            _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uTransparentBackground, transparentBackground ? 1 : 0);
            globalUniformsNeedUpdate = true;
            state.currentRenderItemId = -1;
            var renderables = scene.renderables;
            state.disable(gl.SCISSOR_TEST);
            state.disable(gl.BLEND);
            state.colorMask(true, true, true, true);
            state.enable(gl.DEPTH_TEST);
            if (clear) {
                state.depthMask(true);
                if (variant === 'color') {
                    state.clearColor(bgColor[0], bgColor[1], bgColor[2], transparentBackground ? 0 : 1);
                }
                else {
                    state.clearColor(1, 1, 1, 1);
                }
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            }
            if (variant === 'color') {
                for (var i = 0, il = renderables.length; i < il; ++i) {
                    var r = renderables[i];
                    if (r.state.opaque)
                        renderObject(r, variant);
                }
                state.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE);
                state.enable(gl.BLEND);
                for (var i = 0, il = renderables.length; i < il; ++i) {
                    var r = renderables[i];
                    if (!r.state.opaque && r.state.writeDepth)
                        renderObject(r, variant);
                }
                for (var i = 0, il = renderables.length; i < il; ++i) {
                    var r = renderables[i];
                    if (!r.state.opaque && !r.state.writeDepth)
                        renderObject(r, variant);
                }
            }
            else { // picking & depth
                for (var i = 0, il = renderables.length; i < il; ++i) {
                    renderObject(renderables[i], variant);
                }
            }
            gl.finish();
        };
        return {
            clear: function (transparentBackground) {
                state.depthMask(true);
                state.colorMask(true, true, true, true);
                state.clearColor(bgColor[0], bgColor[1], bgColor[2], transparentBackground ? 0 : 1);
                gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
            },
            render: render,
            setProps: function (props) {
                if (props.backgroundColor !== undefined && props.backgroundColor !== p.backgroundColor) {
                    p.backgroundColor = props.backgroundColor;
                    _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(bgColor, p.backgroundColor);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uFogColor, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(globalUniforms.uFogColor.ref.value, bgColor));
                }
                if (props.pickingAlphaThreshold !== undefined && props.pickingAlphaThreshold !== p.pickingAlphaThreshold) {
                    p.pickingAlphaThreshold = props.pickingAlphaThreshold;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uPickingAlphaThreshold, p.pickingAlphaThreshold);
                }
                if (props.transparencyVariant !== undefined && props.transparencyVariant !== p.transparencyVariant) {
                    p.transparencyVariant = props.transparencyVariant;
                }
                if (props.interiorDarkening !== undefined && props.interiorDarkening !== p.interiorDarkening) {
                    p.interiorDarkening = props.interiorDarkening;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInteriorDarkening, p.interiorDarkening);
                }
                if (props.interiorColorFlag !== undefined && props.interiorColorFlag !== p.interiorColorFlag) {
                    p.interiorColorFlag = props.interiorColorFlag;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInteriorColorFlag, p.interiorColorFlag ? 1 : 0);
                }
                if (props.interiorColor !== undefined && props.interiorColor !== p.interiorColor) {
                    p.interiorColor = props.interiorColor;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uInteriorColor, _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(globalUniforms.uInteriorColor.ref.value, p.interiorColor));
                }
                if (props.highlightColor !== undefined && props.highlightColor !== p.highlightColor) {
                    p.highlightColor = props.highlightColor;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uHighlightColor, _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(globalUniforms.uHighlightColor.ref.value, p.highlightColor));
                }
                if (props.selectColor !== undefined && props.selectColor !== p.selectColor) {
                    p.selectColor = props.selectColor;
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uSelectColor, _mol_util_color__WEBPACK_IMPORTED_MODULE_2__["Color"].toVec3Normalized(globalUniforms.uSelectColor.ref.value, p.selectColor));
                }
                if (props.style !== undefined) {
                    p.style = props.style;
                    Object.assign(style, getStyle(props.style));
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].updateIfChanged(globalUniforms.uLightIntensity, style.lightIntensity);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].updateIfChanged(globalUniforms.uAmbientIntensity, style.ambientIntensity);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].updateIfChanged(globalUniforms.uMetalness, style.metalness);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].updateIfChanged(globalUniforms.uRoughness, style.roughness);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].updateIfChanged(globalUniforms.uReflectivity, style.reflectivity);
                }
                if (props.clip !== undefined && !Object(_mol_util__WEBPACK_IMPORTED_MODULE_3__[/* deepEqual */ "h"])(props.clip, p.clip)) {
                    p.clip = props.clip;
                    Object.assign(clip, getClip(props.clip, clip));
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uClipObjectPosition, clip.objects.position);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uClipObjectRotation, clip.objects.rotation);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uClipObjectScale, clip.objects.scale);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uClipObjectType, clip.objects.type);
                }
            },
            setViewport: function (x, y, width, height) {
                gl.viewport(x, y, width, height);
                if (x !== viewport.x || y !== viewport.y || width !== viewport.width || height !== viewport.height) {
                    _mol_canvas3d_camera_util__WEBPACK_IMPORTED_MODULE_0__[/* Viewport */ "a"].set(viewport, x, y, width, height);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uViewportHeight, height);
                    _mol_util__WEBPACK_IMPORTED_MODULE_3__[/* ValueCell */ "e"].update(globalUniforms.uViewport, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec4"].set(globalUniforms.uViewport.ref.value, x, y, width, height));
                }
            },
            get props() {
                return p;
            },
            get stats() {
                return {
                    programCount: ctx.stats.resourceCounts.program,
                    shaderCount: ctx.stats.resourceCounts.shader,
                    attributeCount: ctx.stats.resourceCounts.attribute,
                    elementsCount: ctx.stats.resourceCounts.elements,
                    framebufferCount: ctx.stats.resourceCounts.framebuffer,
                    renderbufferCount: ctx.stats.resourceCounts.renderbuffer,
                    textureCount: ctx.stats.resourceCounts.texture,
                    vertexArrayCount: ctx.stats.resourceCounts.vertexArray,
                    drawCount: stats.drawCount,
                    instanceCount: stats.instanceCount,
                    instancedDrawCount: stats.instancedDrawCount,
                };
            },
            dispose: function () {
                // TODO
            }
        };
    }
    Renderer.create = create;
})(Renderer || (Renderer = {}));
/* harmony default export */ __webpack_exports__["b"] = (Renderer);
//# sourceMappingURL=renderer.js.map

/***/ }),
/* 394 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export DefaultTrackballBindings */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return TrackballControlsParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return TrackballControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(1);
/* harmony import */ var _camera_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(176);
/* harmony import */ var _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(84);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(2);
/* harmony import */ var _mol_math_misc__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(46);
/* harmony import */ var _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(59);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 *
 * This code has been modified from https://github.com/mrdoob/three.js/,
 * copyright (c) 2010-2018 three.js authors. MIT License
 */







var B = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_3__[/* ButtonsType */ "a"];
var M = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_3__[/* ModifiersKeys */ "b"];
var Trigger = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].Trigger;
var DefaultTrackballBindings = {
    dragRotate: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(1 /* Primary */, M.create())], 'Rotate', 'Drag using ${triggers}'),
    dragRotateZ: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(1 /* Primary */, M.create({ shift: true }))], 'Rotate around z-axis', 'Drag using ${triggers}'),
    dragPan: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(2 /* Secondary */, M.create()), Trigger(1 /* Primary */, M.create({ control: true }))], 'Pan', 'Drag using ${triggers}'),
    dragZoom: _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].Empty,
    dragFocus: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(8 /* Forth */, M.create())], 'Focus', 'Drag using ${triggers}'),
    dragFocusZoom: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(4 /* Auxilary */, M.create())], 'Focus and zoom', 'Drag using ${triggers}'),
    scrollZoom: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(4 /* Auxilary */, M.create())], 'Zoom', 'Scroll using ${triggers}'),
    scrollFocus: Object(_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"])([Trigger(4 /* Auxilary */, M.create({ shift: true }))], 'Clip', 'Scroll using ${triggers}'),
    scrollFocusZoom: _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].Empty,
};
var TrackballControlsParams = {
    noScroll: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Boolean(true, { isHidden: true }),
    rotateSpeed: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(3.0, { min: 0.1, max: 10, step: 0.1 }),
    zoomSpeed: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(6.0, { min: 0.1, max: 10, step: 0.1 }),
    panSpeed: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.8, { min: 0.1, max: 5, step: 0.1 }),
    spin: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Boolean(false, { description: 'Spin the 3D scene around the x-axis in view space' }),
    spinSpeed: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(1, { min: -20, max: 20, step: 1 }),
    staticMoving: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Boolean(true, { isHidden: true }),
    dynamicDampingFactor: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.2, {}, { isHidden: true }),
    minDistance: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(0.01, {}, { isHidden: true }),
    maxDistance: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Numeric(1e150, {}, { isHidden: true }),
    bindings: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].Value(DefaultTrackballBindings, { isHidden: true })
};

var TrackballControls;
(function (TrackballControls) {
    function create(input, camera, props) {
        if (props === void 0) { props = {}; }
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_4__["ParamDefinition"].getDefaultValues(TrackballControlsParams)), props);
        var viewport = Object(_camera_util__WEBPACK_IMPORTED_MODULE_2__[/* Viewport */ "a"])();
        var disposed = false;
        var dragSub = input.drag.subscribe(onDrag);
        var interactionEndSub = input.interactionEnd.subscribe(onInteractionEnd);
        var wheelSub = input.wheel.subscribe(onWheel);
        var pinchSub = input.pinch.subscribe(onPinch);
        var _isInteracting = false;
        // For internal use
        var lastPosition = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var _eye = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var _rotPrev = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _rotCurr = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _rotLastAxis = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var _rotLastAngle = 0;
        var _zRotPrev = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _zRotCurr = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _zRotLastAngle = 0;
        var _zoomStart = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _zoomEnd = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _focusStart = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _focusEnd = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _panStart = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var _panEnd = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        // Initial values for reseting
        var target0 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(camera.target);
        var position0 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(camera.position);
        var up0 = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].clone(camera.up);
        var mouseOnScreenVec2 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        function getMouseOnScreen(pageX, pageY) {
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].set(mouseOnScreenVec2, (pageX - viewport.x) / viewport.width, (pageY - viewport.y) / viewport.height);
        }
        var mouseOnCircleVec2 = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        function getMouseOnCircle(pageX, pageY) {
            return _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].set(mouseOnCircleVec2, (pageX - viewport.width * 0.5 - viewport.x) / (viewport.width * 0.5), (viewport.height + 2 * (viewport.y - pageY)) / viewport.width // screen.width intentional
            );
        }
        var rotAxis = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var rotQuat = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"])();
        var rotEyeDir = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var rotObjUpDir = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var rotObjSideDir = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var rotMoveDir = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        function rotateCamera() {
            var dx = _rotCurr[0] - _rotPrev[0];
            var dy = _rotCurr[1] - _rotPrev[1];
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].set(rotMoveDir, dx, dy, 0);
            var angle = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].magnitude(rotMoveDir) * p.rotateSpeed;
            if (angle) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].normalize(rotEyeDir, _eye);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].normalize(rotObjUpDir, camera.up);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].normalize(rotObjSideDir, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].cross(rotObjSideDir, rotObjUpDir, rotEyeDir));
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(rotObjUpDir, rotObjUpDir, dy);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(rotObjSideDir, rotObjSideDir, dx);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(rotMoveDir, rotObjUpDir, rotObjSideDir);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].normalize(rotAxis, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].cross(rotAxis, rotMoveDir, _eye));
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].setAxisAngle(rotQuat, rotAxis, angle);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(_eye, _eye, rotQuat);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(camera.up, camera.up, rotQuat);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(_rotLastAxis, rotAxis);
                _rotLastAngle = angle;
            }
            else if (!p.staticMoving && _rotLastAngle) {
                _rotLastAngle *= Math.sqrt(1.0 - p.dynamicDampingFactor);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].setAxisAngle(rotQuat, _rotLastAxis, _rotLastAngle);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(_eye, _eye, rotQuat);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(camera.up, camera.up, rotQuat);
            }
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_rotPrev, _rotCurr);
        }
        var zRotQuat = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"])();
        function zRotateCamera() {
            var dx = _zRotCurr[0] - _zRotPrev[0];
            var dy = _zRotCurr[1] - _zRotPrev[1];
            var angle = p.rotateSpeed * (-dx + dy) * -0.05;
            if (angle) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].setAxisAngle(zRotQuat, _eye, angle);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(camera.up, camera.up, zRotQuat);
                _zRotLastAngle = angle;
            }
            else if (!p.staticMoving && _zRotLastAngle) {
                _zRotLastAngle *= Math.sqrt(1.0 - p.dynamicDampingFactor);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Quat"].setAxisAngle(zRotQuat, _eye, _zRotLastAngle);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].transformQuat(camera.up, camera.up, zRotQuat);
            }
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zRotPrev, _zRotCurr);
        }
        function zoomCamera() {
            var factor = 1.0 + (_zoomEnd[1] - _zoomStart[1]) * p.zoomSpeed;
            if (factor !== 1.0 && factor > 0.0) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].scale(_eye, _eye, factor);
            }
            if (p.staticMoving) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomStart, _zoomEnd);
            }
            else {
                _zoomStart[1] += (_zoomEnd[1] - _zoomStart[1]) * p.dynamicDampingFactor;
            }
        }
        function focusCamera() {
            var factor = (_focusEnd[1] - _focusStart[1]) * p.zoomSpeed;
            if (factor !== 0.0) {
                var radius = Math.max(1, camera.state.radius + camera.state.radius * factor);
                camera.setState({ radius: radius });
            }
            if (p.staticMoving) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusStart, _focusEnd);
            }
            else {
                _focusStart[1] += (_focusEnd[1] - _focusStart[1]) * p.dynamicDampingFactor;
            }
        }
        var panMouseChange = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"])();
        var panObjUp = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        var panOffset = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"])();
        function panCamera() {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].sub(panMouseChange, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(panMouseChange, _panEnd), _panStart);
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].squaredMagnitude(panMouseChange)) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].scale(panMouseChange, panMouseChange, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].magnitude(_eye) * p.panSpeed);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].cross(panOffset, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(panOffset, _eye), camera.up);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(panOffset, panOffset, panMouseChange[0]);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(panObjUp, camera.up, panMouseChange[1]);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(panOffset, panOffset, panObjUp);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(camera.position, camera.position, panOffset);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(camera.target, camera.target, panOffset);
                if (p.staticMoving) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_panStart, _panEnd);
                }
                else {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].sub(panMouseChange, _panEnd, _panStart);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].scale(panMouseChange, panMouseChange, p.dynamicDampingFactor);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].add(_panStart, _panStart, panMouseChange);
                }
            }
        }
        /**
         * Ensure the distance between object and target is within the min/max distance
         * and not too large compared to `camera.state.radiusMax`
         */
        function checkDistances() {
            var maxDistance = Math.min(Math.max(camera.state.radiusMax * 1000, 0.01), p.maxDistance);
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].squaredMagnitude(_eye) > maxDistance * maxDistance) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(_eye, _eye, maxDistance);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(camera.position, camera.target, _eye);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomStart, _zoomEnd);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusStart, _focusEnd);
            }
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].squaredMagnitude(_eye) < p.minDistance * p.minDistance) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].setMagnitude(_eye, _eye, p.minDistance);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(camera.position, camera.target, _eye);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomStart, _zoomEnd);
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusStart, _focusEnd);
            }
        }
        var lastUpdated = -1;
        /** Update the object's position, direction and up vectors */
        function update(t) {
            if (lastUpdated === t)
                return;
            if (p.spin)
                spin(t - lastUpdated);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
            rotateCamera();
            zRotateCamera();
            zoomCamera();
            focusCamera();
            panCamera();
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].add(camera.position, camera.target, _eye);
            checkDistances();
            if (_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].squaredDistance(lastPosition, camera.position) > _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["EPSILON"]) {
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(lastPosition, camera.position);
            }
            lastUpdated = t;
        }
        /** Reset object's vectors and the target vector to their initial values */
        function reset() {
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(camera.target, target0);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(camera.position, position0);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(camera.up, up0);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].sub(_eye, camera.position, camera.target);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].copy(lastPosition, camera.position);
        }
        // listeners
        function onDrag(_a) {
            var pageX = _a.pageX, pageY = _a.pageY, buttons = _a.buttons, modifiers = _a.modifiers, isStart = _a.isStart;
            _isInteracting = true;
            var dragRotate = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragRotate, buttons, modifiers);
            var dragRotateZ = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragRotateZ, buttons, modifiers);
            var dragPan = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragPan, buttons, modifiers);
            var dragZoom = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragZoom, buttons, modifiers);
            var dragFocus = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragFocus, buttons, modifiers);
            var dragFocusZoom = _mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.dragFocusZoom, buttons, modifiers);
            getMouseOnCircle(pageX, pageY);
            getMouseOnScreen(pageX, pageY);
            if (isStart) {
                if (dragRotate) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_rotCurr, mouseOnCircleVec2);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_rotPrev, _rotCurr);
                }
                if (dragRotateZ) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zRotCurr, mouseOnCircleVec2);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zRotPrev, _zRotCurr);
                }
                if (dragZoom || dragFocusZoom) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomStart, mouseOnScreenVec2);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomEnd, _zoomStart);
                }
                if (dragFocus) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusStart, mouseOnScreenVec2);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusEnd, _focusStart);
                }
                if (dragPan) {
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_panStart, mouseOnScreenVec2);
                    _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_panEnd, _panStart);
                }
            }
            if (dragRotate)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_rotCurr, mouseOnCircleVec2);
            if (dragRotateZ)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zRotCurr, mouseOnCircleVec2);
            if (dragZoom || dragFocusZoom)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_zoomEnd, mouseOnScreenVec2);
            if (dragFocus)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_focusEnd, mouseOnScreenVec2);
            if (dragFocusZoom) {
                var dist = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec3"].distance(camera.state.position, camera.state.target);
                camera.setState({ radius: dist / 5 });
            }
            if (dragPan)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].copy(_panEnd, mouseOnScreenVec2);
        }
        function onInteractionEnd() {
            _isInteracting = false;
        }
        function onWheel(_a) {
            var dx = _a.dx, dy = _a.dy, dz = _a.dz, buttons = _a.buttons, modifiers = _a.modifiers;
            var delta = Object(_mol_math_misc__WEBPACK_IMPORTED_MODULE_5__[/* absMax */ "a"])(dx, dy, dz);
            if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.scrollZoom, buttons, modifiers)) {
                _zoomEnd[1] += delta * 0.0001;
            }
            if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.scrollFocus, buttons, modifiers)) {
                _focusEnd[1] += delta * 0.0001;
            }
        }
        function onPinch(_a) {
            var fraction = _a.fraction, buttons = _a.buttons, modifiers = _a.modifiers;
            if (_mol_util_binding__WEBPACK_IMPORTED_MODULE_6__[/* Binding */ "a"].match(p.bindings.scrollZoom, buttons, modifiers)) {
                _isInteracting = true;
                _zoomEnd[1] += (fraction - 1) * 0.1;
            }
        }
        function dispose() {
            if (disposed)
                return;
            disposed = true;
            dragSub.unsubscribe();
            wheelSub.unsubscribe();
            pinchSub.unsubscribe();
            interactionEndSub.unsubscribe();
        }
        var _spinSpeed = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].create(0.005, 0);
        function spin(deltaT) {
            var frameSpeed = (p.spinSpeed || 0) / 1000;
            _spinSpeed[0] = 60 * Math.min(Math.abs(deltaT), 1000 / 8) / 1000 * frameSpeed;
            if (!_isInteracting)
                _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_1__["Vec2"].add(_rotCurr, _rotPrev, _spinSpeed);
        }
        // force an update at start
        update(0);
        return {
            viewport: viewport,
            get props() { return p; },
            setProps: function (props) {
                Object.assign(p, props);
            },
            update: update,
            reset: reset,
            dispose: dispose
        };
    }
    TrackballControls.create = create;
})(TrackballControls || (TrackballControls = {}));
//# sourceMappingURL=trackball.js.map

/***/ }),
/* 395 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return DebugHelperParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return BoundingSphereHelper; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(115);
/* harmony import */ var _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34);
/* harmony import */ var _mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(75);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(39);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2);
/* harmony import */ var _mol_gl_scene__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(263);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(11);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(47);
/* harmony import */ var _mol_geo_primitive_sphere__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(264);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(5);
/* harmony import */ var _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(145);
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var DebugHelperParams = {
    sceneBoundingSpheres: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false, { description: 'Show full scene bounding spheres.' }),
    visibleSceneBoundingSpheres: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false, { description: 'Show visible scene bounding spheres.' }),
    objectBoundingSpheres: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false, { description: 'Show bounding spheres of visible render objects.' }),
    instanceBoundingSpheres: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false, { description: 'Show bounding spheres of visible instances.' }),
};
var BoundingSphereHelper = /** @class */ (function () {
    function BoundingSphereHelper(ctx, parent, props) {
        this.objectsData = new Map();
        this.instancesData = new Map();
        this.scene = _mol_gl_scene__WEBPACK_IMPORTED_MODULE_6__[/* default */ "a"].create(ctx);
        this.parent = parent;
        this._props = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].getDefaultValues(DebugHelperParams)), props);
    }
    BoundingSphereHelper.prototype.update = function () {
        var _this = this;
        var newSceneData = updateBoundingSphereData(this.scene, this.parent.boundingSphere, this.sceneData, _mol_util_color_names__WEBPACK_IMPORTED_MODULE_8__[/* ColorNames */ "a"].lightgrey, sceneMaterialId);
        if (newSceneData)
            this.sceneData = newSceneData;
        var newVisibleSceneData = updateBoundingSphereData(this.scene, this.parent.boundingSphereVisible, this.visibleSceneData, _mol_util_color_names__WEBPACK_IMPORTED_MODULE_8__[/* ColorNames */ "a"].black, visibleSceneMaterialId);
        if (newVisibleSceneData)
            this.visibleSceneData = newVisibleSceneData;
        this.parent.forEach(function (r, ro) {
            var objectData = _this.objectsData.get(ro);
            var newObjectData = updateBoundingSphereData(_this.scene, r.values.boundingSphere.ref.value, objectData, _mol_util_color_names__WEBPACK_IMPORTED_MODULE_8__[/* ColorNames */ "a"].tomato, objectMaterialId);
            if (newObjectData)
                _this.objectsData.set(ro, newObjectData);
            var instanceData = _this.instancesData.get(ro);
            var newInstanceData = updateBoundingSphereData(_this.scene, r.values.invariantBoundingSphere.ref.value, instanceData, _mol_util_color_names__WEBPACK_IMPORTED_MODULE_8__[/* ColorNames */ "a"].skyblue, instanceMaterialId, {
                aTransform: ro.values.aTransform,
                matrix: ro.values.matrix,
                transform: ro.values.transform,
                extraTransform: ro.values.extraTransform,
                uInstanceCount: ro.values.uInstanceCount,
                instanceCount: ro.values.instanceCount,
                aInstance: ro.values.aInstance,
            });
            if (newInstanceData)
                _this.instancesData.set(ro, newInstanceData);
        });
        this.objectsData.forEach(function (objectData, ro) {
            if (!_this.parent.has(ro)) {
                _this.scene.remove(objectData.renderObject);
                _this.objectsData.delete(ro);
            }
        });
        this.instancesData.forEach(function (instanceData, ro) {
            if (!_this.parent.has(ro)) {
                _this.scene.remove(instanceData.renderObject);
                _this.instancesData.delete(ro);
            }
        });
        this.scene.update(void 0, false);
        this.scene.commit();
    };
    BoundingSphereHelper.prototype.syncVisibility = function () {
        var _this = this;
        if (this.sceneData) {
            this.sceneData.renderObject.state.visible = this._props.sceneBoundingSpheres;
        }
        if (this.visibleSceneData) {
            this.visibleSceneData.renderObject.state.visible = this._props.visibleSceneBoundingSpheres;
        }
        this.parent.forEach(function (_, ro) {
            var objectData = _this.objectsData.get(ro);
            if (objectData)
                objectData.renderObject.state.visible = ro.state.visible && _this._props.objectBoundingSpheres;
            var instanceData = _this.instancesData.get(ro);
            if (instanceData)
                instanceData.renderObject.state.visible = ro.state.visible && _this._props.instanceBoundingSpheres;
        });
    };
    BoundingSphereHelper.prototype.clear = function () {
        this.sceneData = undefined;
        this.objectsData.clear();
        this.scene.clear();
    };
    Object.defineProperty(BoundingSphereHelper.prototype, "isEnabled", {
        get: function () {
            return (this._props.sceneBoundingSpheres || this._props.visibleSceneBoundingSpheres ||
                this._props.objectBoundingSpheres || this._props.instanceBoundingSpheres);
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(BoundingSphereHelper.prototype, "props", {
        get: function () { return this._props; },
        enumerable: false,
        configurable: true
    });
    BoundingSphereHelper.prototype.setProps = function (props) {
        Object.assign(this._props, props);
        if (this.isEnabled)
            this.update();
    };
    return BoundingSphereHelper;
}());

function updateBoundingSphereData(scene, boundingSphere, data, color, materialId, transform) {
    if (!data || !_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].equals(data.boundingSphere, boundingSphere)) {
        var mesh = createBoundingSphereMesh(boundingSphere, data && data.mesh);
        var renderObject = data ? data.renderObject : createBoundingSphereRenderObject(mesh, color, materialId, transform);
        if (data) {
            _mol_util__WEBPACK_IMPORTED_MODULE_10__[/* ValueCell */ "e"].update(renderObject.values.drawCount, _mol_geo_geometry_geometry__WEBPACK_IMPORTED_MODULE_11__[/* Geometry */ "a"].getDrawCount(mesh));
        }
        else {
            scene.add(renderObject);
        }
        return { boundingSphere: _mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].clone(boundingSphere), renderObject: renderObject, mesh: mesh };
    }
}
function createBoundingSphereMesh(boundingSphere, mesh) {
    var detail = 2;
    var vertexCount = Object(_mol_geo_primitive_sphere__WEBPACK_IMPORTED_MODULE_9__[/* sphereVertexCount */ "b"])(detail);
    var builderState = _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__[/* MeshBuilder */ "a"].createState(vertexCount, vertexCount / 2, mesh);
    if (boundingSphere.radius) {
        Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_3__[/* addSphere */ "a"])(builderState, boundingSphere.center, boundingSphere.radius, detail);
        if (_mol_math_geometry__WEBPACK_IMPORTED_MODULE_7__[/* Sphere3D */ "g"].hasExtrema(boundingSphere)) {
            for (var _i = 0, _a = boundingSphere.extrema; _i < _a.length; _i++) {
                var e = _a[_i];
                Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_3__[/* addSphere */ "a"])(builderState, e, 1.0, 0);
            }
        }
    }
    return _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__[/* MeshBuilder */ "a"].getMesh(builderState);
}
var sceneMaterialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__[/* getNextMaterialId */ "c"])();
var visibleSceneMaterialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__[/* getNextMaterialId */ "c"])();
var objectMaterialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__[/* getNextMaterialId */ "c"])();
var instanceMaterialId = Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__[/* getNextMaterialId */ "c"])();
function createBoundingSphereRenderObject(mesh, color, materialId, transform) {
    var values = _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_4__[/* Mesh */ "a"].Utils.createValuesSimple(mesh, { alpha: 0.1, doubleSided: false }, color, 1, transform);
    return Object(_mol_gl_render_object__WEBPACK_IMPORTED_MODULE_1__[/* createRenderObject */ "a"])('mesh', values, { visible: true, alphaFactor: 1, pickable: false, opaque: false, writeDepth: false }, materialId);
}
//# sourceMappingURL=bounding-sphere-helper.js.map

/***/ }),
/* 396 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return HandleHelperParams; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return HandleHelper; });
/* unused harmony export HandleGroup */
/* unused harmony export isHandleLoci */
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_gl_scene__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(263);
/* harmony import */ var _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(34);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(1);
/* harmony import */ var _mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(75);
/* harmony import */ var _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(39);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(47);
/* harmony import */ var _mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(81);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(5);
/* harmony import */ var _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(11);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(2);
/* harmony import */ var immer__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(151);
/* harmony import */ var _mol_model_shape__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(49);
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(23);
/* harmony import */ var _mol_util_marker_action__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(45);
/* harmony import */ var _mol_repr_visual__WEBPACK_IMPORTED_MODULE_15__ = __webpack_require__(69);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_16__ = __webpack_require__(6);
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

















var HandleParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_5__[/* Mesh */ "a"].Params), { alpha: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_5__[/* Mesh */ "a"].Params.alpha), { defaultValue: 1 }), ignoreLight: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_geo_geometry_mesh_mesh__WEBPACK_IMPORTED_MODULE_5__[/* Mesh */ "a"].Params.ignoreLight), { defaultValue: true }), colorX: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].red, { isEssential: true }), colorY: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].green, { isEssential: true }), colorZ: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].blue, { isEssential: true }), scale: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Numeric(0.33, { min: 0.1, max: 2, step: 0.1 }, { isEssential: true }) });
var HandleHelperParams = {
    handle: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].MappedStatic('off', {
        on: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Group(HandleParams),
        off: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_10__["ParamDefinition"].Group({})
    }, { cycle: true, description: 'Show handle tool' }),
};
var HandleHelper = /** @class */ (function () {
    function HandleHelper(webgl, props) {
        var _this = this;
        if (props === void 0) { props = {}; }
        this.webgl = webgl;
        this.props = {
            handle: { name: 'off', params: {} }
        };
        this._transform = Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Mat4"])();
        this.eachGroup = function (loci, apply) {
            if (!_this.renderObject)
                return false;
            if (!isHandleLoci(loci))
                return false;
            var changed = false;
            var groupCount = _this.renderObject.values.uGroupCount.ref.value;
            var elements = loci.elements;
            for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
                var _a = elements_1[_i], groupId = _a.groupId, instanceId = _a.instanceId;
                var idx = instanceId * groupCount + groupId;
                if (apply(_mol_data_int__WEBPACK_IMPORTED_MODULE_16__["Interval"].ofSingleton(idx)))
                    changed = true;
            }
            return changed;
        };
        this.scene = _mol_gl_scene__WEBPACK_IMPORTED_MODULE_1__[/* default */ "a"].create(webgl);
        this.setProps(props);
    }
    HandleHelper.prototype.getBoundingSphere = function (out, instanceId) {
        if (this.renderObject) {
            _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].copy(out, this.renderObject.values.invariantBoundingSphere.ref.value);
            _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Mat4"].fromArray(this._transform, this.renderObject.values.aTransform.ref.value, instanceId * 16);
            _mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].transform(out, out, this._transform);
        }
        return out;
    };
    HandleHelper.prototype.setProps = function (props) {
        var _this = this;
        this.props = Object(immer__WEBPACK_IMPORTED_MODULE_11__[/* default */ "a"])(this.props, function (p) {
            if (props.handle !== undefined) {
                p.handle.name = props.handle.name;
                if (props.handle.name === 'on') {
                    _this.scene.clear();
                    var params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, props.handle.params), { scale: props.handle.params.scale * _this.webgl.pixelRatio });
                    _this.renderObject = createHandleRenderObject(params);
                    _this.scene.add(_this.renderObject);
                    _this.scene.commit();
                    p.handle.params = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, props.handle.params);
                }
            }
        });
    };
    Object.defineProperty(HandleHelper.prototype, "isEnabled", {
        get: function () {
            return this.props.handle.name === 'on';
        },
        enumerable: false,
        configurable: true
    });
    // TODO could be a lists of position/rotation if we want to show more than one handle tool,
    //      they would be distingishable by their instanceId
    HandleHelper.prototype.update = function (camera, position, rotation) {
        if (!this.renderObject)
            return;
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Mat4"].setTranslation(this.renderObject.values.aTransform.ref.value, position);
        _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Mat4"].fromMat3(this.renderObject.values.aTransform.ref.value, rotation);
        // TODO make invariant to camera scaling by adjusting renderObject transform
        _mol_util__WEBPACK_IMPORTED_MODULE_8__[/* ValueCell */ "e"].update(this.renderObject.values.aTransform, this.renderObject.values.aTransform.ref.value);
        this.scene.update([this.renderObject], true);
    };
    HandleHelper.prototype.getLoci = function (pickingId) {
        var objectId = pickingId.objectId, groupId = pickingId.groupId, instanceId = pickingId.instanceId;
        if (!this.renderObject || objectId !== this.renderObject.id)
            return _mol_model_loci__WEBPACK_IMPORTED_MODULE_13__["EmptyLoci"];
        return HandleLoci(this, groupId, instanceId);
    };
    HandleHelper.prototype.mark = function (loci, action) {
        if (!_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_14__[/* MarkerActions */ "b"].is(_mol_util_marker_action__WEBPACK_IMPORTED_MODULE_14__[/* MarkerActions */ "b"].Highlighting, action))
            return false;
        if (!isHandleLoci(loci))
            return false;
        if (loci.data !== this)
            return false;
        return _mol_repr_visual__WEBPACK_IMPORTED_MODULE_15__[/* Visual */ "a"].mark(this.renderObject, loci, action, this.eachGroup);
    };
    return HandleHelper;
}());

function createHandleMesh(scale, mesh) {
    var state = _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__[/* MeshBuilder */ "a"].createState(512, 256, mesh);
    var radius = 0.05 * scale;
    var x = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].unitX, scale);
    var y = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].unitY, scale);
    var z = _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].scale(Object(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"])(), _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].unitZ, scale);
    var cylinderProps = { radiusTop: radius, radiusBottom: radius, radialSegments: 32 };
    state.currentGroup = HandleGroup.TranslateScreenXY;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_4__[/* addSphere */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].origin, radius * 3, 2);
    state.currentGroup = HandleGroup.TranslateObjectX;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_4__[/* addSphere */ "a"])(state, x, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_7__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].origin, x, 1, cylinderProps);
    state.currentGroup = HandleGroup.TranslateObjectY;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_4__[/* addSphere */ "a"])(state, y, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_7__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].origin, y, 1, cylinderProps);
    state.currentGroup = HandleGroup.TranslateObjectZ;
    Object(_mol_geo_geometry_mesh_builder_sphere__WEBPACK_IMPORTED_MODULE_4__[/* addSphere */ "a"])(state, z, radius, 2);
    Object(_mol_geo_geometry_mesh_builder_cylinder__WEBPACK_IMPORTED_MODULE_7__[/* addCylinder */ "a"])(state, _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].origin, z, 1, cylinderProps);
    // TODO add more helper geometries for the other HandleGroup options
    // TODO add props to create subset of geometries
    return _mol_geo_geometry_mesh_mesh_builder__WEBPACK_IMPORTED_MODULE_2__[/* MeshBuilder */ "a"].getMesh(state);
}
var HandleGroup = {
    None: 0,
    TranslateScreenXY: 1,
    // TranslateScreenZ: 2,
    TranslateObjectX: 3,
    TranslateObjectY: 4,
    TranslateObjectZ: 5,
};
function HandleLoci(handleHelper, groupId, instanceId) {
    return Object(_mol_model_loci__WEBPACK_IMPORTED_MODULE_13__["DataLoci"])('handle', handleHelper, [{ groupId: groupId, instanceId: instanceId }], function (boundingSphere) { return handleHelper.getBoundingSphere(boundingSphere, instanceId); }, function () { return "Handle Helper | Group Id " + groupId + " | Instance Id " + instanceId; });
}
function isHandleLoci(x) {
    return x.kind === 'data-loci' && x.tag === 'handle';
}
function getHandleShape(props, shape) {
    var scale = 10 * props.scale;
    var mesh = createHandleMesh(scale, shape === null || shape === void 0 ? void 0 : shape.geometry);
    mesh.setBoundingSphere(_mol_math_geometry__WEBPACK_IMPORTED_MODULE_9__[/* Sphere3D */ "g"].create(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_3__["Vec3"].create(scale / 2, scale / 2, scale / 2), scale + scale / 4));
    var getColor = function (groupId) {
        switch (groupId) {
            case HandleGroup.TranslateObjectX: return props.colorX;
            case HandleGroup.TranslateObjectY: return props.colorY;
            case HandleGroup.TranslateObjectZ: return props.colorZ;
            default: return _mol_util_color_names__WEBPACK_IMPORTED_MODULE_6__[/* ColorNames */ "a"].grey;
        }
    };
    return _mol_model_shape__WEBPACK_IMPORTED_MODULE_12__[/* Shape */ "a"].create('handle', {}, mesh, getColor, function () { return 1; }, function () { return ''; });
}
function createHandleRenderObject(props) {
    var shape = getHandleShape(props);
    return _mol_model_shape__WEBPACK_IMPORTED_MODULE_12__[/* Shape */ "a"].createRenderObject(shape, props);
}
//# sourceMappingURL=handle-helper.js.map

/***/ }),
/* 397 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/


/* eslint-disable no-unused-vars */
var getOwnPropertySymbols = Object.getOwnPropertySymbols;
var hasOwnProperty = Object.prototype.hasOwnProperty;
var propIsEnumerable = Object.prototype.propertyIsEnumerable;

function toObject(val) {
	if (val === null || val === undefined) {
		throw new TypeError('Object.assign cannot be called with null or undefined');
	}

	return Object(val);
}

function shouldUseNative() {
	try {
		if (!Object.assign) {
			return false;
		}

		// Detect buggy property enumeration order in older V8 versions.

		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
		test1[5] = 'de';
		if (Object.getOwnPropertyNames(test1)[0] === '5') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test2 = {};
		for (var i = 0; i < 10; i++) {
			test2['_' + String.fromCharCode(i)] = i;
		}
		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
			return test2[n];
		});
		if (order2.join('') !== '0123456789') {
			return false;
		}

		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
		var test3 = {};
		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
			test3[letter] = letter;
		});
		if (Object.keys(Object.assign({}, test3)).join('') !==
				'abcdefghijklmnopqrst') {
			return false;
		}

		return true;
	} catch (err) {
		// We don't expect any of the above to throw, but better to be safe.
		return false;
	}
}

module.exports = shouldUseNative() ? Object.assign : function (target, source) {
	var from;
	var to = toObject(target);
	var symbols;

	for (var s = 1; s < arguments.length; s++) {
		from = Object(arguments[s]);

		for (var key in from) {
			if (hasOwnProperty.call(from, key)) {
				to[key] = from[key];
			}
		}

		if (getOwnPropertySymbols) {
			symbols = getOwnPropertySymbols(from);
			for (var i = 0; i < symbols.length; i++) {
				if (propIsEnumerable.call(from, symbols[i])) {
					to[symbols[i]] = from[symbols[i]];
				}
			}
		}
	}

	return to;
};


/***/ }),
/* 398 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _topology_topology__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(341);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "a", function() { return _topology_topology__WEBPACK_IMPORTED_MODULE_0__["a"]; });

/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

//# sourceMappingURL=topology.js.map

/***/ }),
/* 399 */
/***/ (function(module, exports) {

/**
 * Copyright (c) 2017-2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
//# sourceMappingURL=conformation.js.map

/***/ }),
/* 400 */
/***/ (function(module, exports) {

/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
//# sourceMappingURL=conformation.js.map

/***/ }),
/* 401 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return CoarseHierarchy; });
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
var CoarseHierarchy;
(function (CoarseHierarchy) {
    CoarseHierarchy.Empty = { isDefined: false };
})(CoarseHierarchy || (CoarseHierarchy = {}));
//# sourceMappingURL=hierarchy.js.map

/***/ }),
/* 402 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return IndexedCustomProperty; });
/* harmony import */ var _structure__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(27);
/* harmony import */ var _mol_data_int__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(6);
/* harmony import */ var _mol_util__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(5);
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var IndexedCustomProperty;
(function (IndexedCustomProperty) {
    function getCifDataSource(structure, prop, cache) {
        if (!prop)
            return { rowCount: 0 };
        if (cache && cache[prop.id])
            return cache[prop.id];
        var data = prop.getElements(structure);
        var ret = { data: data, rowCount: data.elements.length };
        if (cache)
            cache[prop.id] = ret;
        return ret;
    }
    IndexedCustomProperty.getCifDataSource = getCifDataSource;
    function fromAtomMap(map) {
        return new ElementMappedCustomProperty(map);
    }
    IndexedCustomProperty.fromAtomMap = fromAtomMap;
    function fromAtomArray(array) {
        // TODO: create "array based custom property" as optimization
        return new ElementMappedCustomProperty(arrayToMap(array));
    }
    IndexedCustomProperty.fromAtomArray = fromAtomArray;
    var getResidueSegments = function (model) { return model.atomicHierarchy.residueAtomSegments; };
    function fromResidueMap(map) {
        return new SegmentedMappedIndexedCustomProperty('residue', map, getResidueSegments, 0 /* Atomic */);
    }
    IndexedCustomProperty.fromResidueMap = fromResidueMap;
    function fromResidueArray(array) {
        // TODO: create "array based custom property" as optimization
        return new SegmentedMappedIndexedCustomProperty('residue', arrayToMap(array), getResidueSegments, 0 /* Atomic */);
    }
    IndexedCustomProperty.fromResidueArray = fromResidueArray;
    var getChainSegments = function (model) { return model.atomicHierarchy.chainAtomSegments; };
    function fromChainMap(map) {
        return new SegmentedMappedIndexedCustomProperty('chain', map, getChainSegments, 0 /* Atomic */);
    }
    IndexedCustomProperty.fromChainMap = fromChainMap;
    function fromChainArray(array) {
        // TODO: create "array based custom property" as optimization
        return new SegmentedMappedIndexedCustomProperty('chain', arrayToMap(array), getChainSegments, 0 /* Atomic */);
    }
    IndexedCustomProperty.fromChainArray = fromChainArray;
    function fromEntityMap(map) {
        return new EntityMappedCustomProperty(map);
    }
    IndexedCustomProperty.fromEntityMap = fromEntityMap;
})(IndexedCustomProperty || (IndexedCustomProperty = {}));
function arrayToMap(array) {
    var ret = new Map();
    for (var i = 0, _i = array.length; i < _i; i++)
        ret.set(i, array[i]);
    return ret;
}
var SegmentedMappedIndexedCustomProperty = /** @class */ (function () {
    function SegmentedMappedIndexedCustomProperty(level, map, segmentGetter, kind) {
        this.level = level;
        this.map = map;
        this.segmentGetter = segmentGetter;
        this.id = _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22();
        this.kind = kind;
    }
    SegmentedMappedIndexedCustomProperty.prototype.has = function (idx) { return this.map.has(idx); };
    SegmentedMappedIndexedCustomProperty.prototype.get = function (idx) { return this.map.get(idx); };
    SegmentedMappedIndexedCustomProperty.prototype.getStructureElements = function (structure) {
        var models = structure.models;
        if (models.length !== 1)
            throw new Error("Only works on structures with a single model.");
        var seenIndices = new Set();
        var unitGroups = structure.unitSymmetryGroups;
        var loci = [];
        var segments = this.segmentGetter(models[0]);
        for (var _a = 0, unitGroups_1 = unitGroups; _a < unitGroups_1.length; _a++) {
            var unitGroup = unitGroups_1[_a];
            var unit = unitGroup.units[0];
            if (unit.kind !== this.kind) {
                continue;
            }
            var chains = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["Segmentation"].transientSegments(segments, unit.elements);
            while (chains.hasNext) {
                var seg = chains.move();
                if (!this.has(seg.index) || seenIndices.has(seg.index))
                    continue;
                seenIndices.add(seg.index);
                loci[loci.length] = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureElement */ "d"].Location.create(structure, unit, unit.elements[seg.start]);
            }
        }
        loci.sort(function (x, y) { return x.element - y.element; });
        return loci;
    };
    SegmentedMappedIndexedCustomProperty.prototype.getElements = function (structure) {
        var _this = this;
        var index = this.segmentGetter(structure.model).index;
        var elements = this.getStructureElements(structure);
        return { elements: elements, property: function (i) { return _this.get(index[elements[i].element]); } };
    };
    return SegmentedMappedIndexedCustomProperty;
}());
var ElementMappedCustomProperty = /** @class */ (function () {
    function ElementMappedCustomProperty(map) {
        this.map = map;
        this.id = _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22();
        this.level = 'atom';
        this.kind = 0 /* Atomic */;
    }
    ElementMappedCustomProperty.prototype.has = function (idx) { return this.map.has(idx); };
    ElementMappedCustomProperty.prototype.get = function (idx) { return this.map.get(idx); };
    ElementMappedCustomProperty.prototype.getStructureElements = function (structure) {
        var models = structure.models;
        if (models.length !== 1)
            throw new Error("Only works on structures with a single model.");
        var seenIndices = new Set();
        var unitGroups = structure.unitSymmetryGroups;
        var loci = [];
        for (var _a = 0, unitGroups_2 = unitGroups; _a < unitGroups_2.length; _a++) {
            var unitGroup = unitGroups_2[_a];
            var unit = unitGroup.units[0];
            if (unit.kind !== this.kind) {
                continue;
            }
            var elements = unit.elements;
            for (var i = 0, _i = elements.length; i < _i; i++) {
                var e = elements[i];
                if (!this.has(e) || seenIndices.has(e))
                    continue;
                seenIndices.add(elements[i]);
                loci[loci.length] = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureElement */ "d"].Location.create(structure, unit, e);
            }
        }
        loci.sort(function (x, y) { return x.element - y.element; });
        return loci;
    };
    ElementMappedCustomProperty.prototype.getElements = function (structure) {
        var _this = this;
        var elements = this.getStructureElements(structure);
        return { elements: elements, property: function (i) { return _this.get(elements[i].element); } };
    };
    return ElementMappedCustomProperty;
}());
var EntityMappedCustomProperty = /** @class */ (function () {
    function EntityMappedCustomProperty(map) {
        this.map = map;
        this.id = _mol_util__WEBPACK_IMPORTED_MODULE_2__[/* UUID */ "c"].create22();
        this.level = 'entity';
        this.kind = 0 /* Atomic */;
    }
    EntityMappedCustomProperty.prototype.has = function (idx) { return this.map.has(idx); };
    EntityMappedCustomProperty.prototype.get = function (idx) { return this.map.get(idx); };
    EntityMappedCustomProperty.prototype.getStructureElements = function (structure) {
        var models = structure.models;
        if (models.length !== 1)
            throw new Error("Only works on structures with a single model.");
        var index = models[0].atomicHierarchy.index;
        var seenIndices = new Set();
        var unitGroups = structure.unitSymmetryGroups;
        var loci = [];
        var segments = models[0].atomicHierarchy.chainAtomSegments;
        for (var _a = 0, unitGroups_3 = unitGroups; _a < unitGroups_3.length; _a++) {
            var unitGroup = unitGroups_3[_a];
            var unit = unitGroup.units[0];
            if (unit.kind !== this.kind) {
                continue;
            }
            var chains = _mol_data_int__WEBPACK_IMPORTED_MODULE_1__["Segmentation"].transientSegments(segments, unit.elements);
            while (chains.hasNext) {
                var seg = chains.move();
                var eI = index.getEntityFromChain(seg.index);
                if (!this.has(eI) || seenIndices.has(eI))
                    continue;
                seenIndices.add(eI);
                loci[loci.length] = _structure__WEBPACK_IMPORTED_MODULE_0__[/* StructureElement */ "d"].Location.create(structure, unit, unit.elements[seg.start]);
            }
        }
        loci.sort(function (x, y) { return x.element - y.element; });
        return loci;
    };
    EntityMappedCustomProperty.prototype.getElements = function (structure) {
        var _this = this;
        var elements = this.getStructureElements(structure);
        var chainIndex = structure.model.atomicHierarchy.chainAtomSegments.index;
        var index = structure.model.atomicHierarchy.index;
        return { elements: elements, property: function (i) { return _this.get(index.getEntityFromChain(chainIndex[elements[i].element])); } };
    };
    return EntityMappedCustomProperty;
}());
//# sourceMappingURL=indexed.js.map

/***/ }),
/* 403 */
/***/ (function(module, exports) {

/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */
//# sourceMappingURL=indexing.js.map

/***/ }),
/* 404 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "PluginSpec", function() { return PluginSpec; });
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var PluginSpec;
(function (PluginSpec) {
    function Action(action, params) {
        return { action: action, customControl: params && params.customControl, autoUpdate: params && params.autoUpdate };
    }
    PluginSpec.Action = Action;
    function Behavior(transformer, defaultParams) {
        if (defaultParams === void 0) { defaultParams = {}; }
        return { transformer: transformer, defaultParams: defaultParams };
    }
    PluginSpec.Behavior = Behavior;
})(PluginSpec || (PluginSpec = {}));
//# sourceMappingURL=spec.js.map

/***/ }),
/* 405 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.ModelInfo = exports.QueryHelper = exports.LigandView = exports.PDBeVolumes = void 0;
var tslib_1 = __webpack_require__(0);
var commands_1 = __webpack_require__(26);
var builder_1 = __webpack_require__(10);
var mol_state_1 = __webpack_require__(13);
var structure_1 = __webpack_require__(4);
var transformers_1 = __webpack_require__(300);
// import { VolumeStreaming } from '../../mol-plugin/behavior/dynamic/volume-streaming/behavior';
var compiler_1 = __webpack_require__(163);
var PDBeVolumes;
(function (PDBeVolumes) {
    function mapParams(defaultParams, mapParams, ref) {
        var pdbeParams = tslib_1.__assign({}, defaultParams);
        pdbeParams.options.behaviorRef = 'volume-streaming' + '' + Math.floor(Math.random() * Math.floor(100));
        pdbeParams.options.emContourProvider = 'pdbe';
        pdbeParams.options.serverUrl = 'https://www.ebi.ac.uk/pdbe/densities';
        pdbeParams.options.channelParams['em'] = {
            opacity: (mapParams && mapParams.em && mapParams.em.opacity) ? mapParams.em.opacity : 0.49,
            wireframe: (mapParams && mapParams.em && mapParams.em.wireframe) ? mapParams.em.wireframe : false
        };
        pdbeParams.options.channelParams['2fo-fc'] = {
            opacity: (mapParams && mapParams['2fo-fc'] && mapParams['2fo-fc'].opacity) ? mapParams['2fo-fc'].opacity : 0.49,
            wireframe: (mapParams && mapParams['2fo-fc'] && mapParams['2fo-fc'].wireframe) ? mapParams['2fo-fc'].wireframe : false
        };
        pdbeParams.options.channelParams['fo-fc(+ve)'] = {
            opacity: (mapParams && mapParams['fo-fc(+ve)'] && mapParams['fo-fc(+ve)'].opacity) ? mapParams['fo-fc(+ve)'].opacity : 0.3,
            wireframe: (mapParams && mapParams['fo-fc(+ve)'] && mapParams['fo-fc(+ve)'].wireframe) ? mapParams['fo-fc(+ve)'].wireframe : true
        };
        pdbeParams.options.channelParams['fo-fc(-ve)'] = {
            opacity: (mapParams && mapParams['fo-fc(-ve)'] && mapParams['fo-fc(-ve)'].opacity) ? mapParams['fo-fc(-ve)'].opacity : 0.3,
            wireframe: (mapParams && mapParams['fo-fc(-ve)'] && mapParams['fo-fc(-ve)'].wireframe) ? mapParams['fo-fc(-ve)'].wireframe : true
        };
        return pdbeParams;
    }
    PDBeVolumes.mapParams = mapParams;
    function displayUsibilityMessage(plugin) {
        commands_1.PluginCommands.Toast.Show(plugin, {
            title: 'Volume',
            message: 'Streaming enabled, click on a residue or an atom to view the data.',
            key: 'toast-1',
            timeoutMs: 7000
        });
    }
    PDBeVolumes.displayUsibilityMessage = displayUsibilityMessage;
    function toggle(plugin) {
        var state = plugin.state.data;
        var streamingState = state.select(mol_state_1.StateSelection.Generators.ofTransformer(transformers_1.CreateVolumeStreamingInfo))[0];
        if (streamingState) {
            commands_1.PluginCommands.State.ToggleVisibility(plugin, { state: state, ref: streamingState.transform.ref });
            return;
        }
    }
    PDBeVolumes.toggle = toggle;
})(PDBeVolumes = exports.PDBeVolumes || (exports.PDBeVolumes = {}));
var LigandView;
(function (LigandView) {
    function query(ligandViewParams) {
        var atomGroupsParams = {
            'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()])
        };
        // Residue Param
        var residueParam;
        if (ligandViewParams.auth_seq_id) {
            residueParam = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), ligandViewParams.auth_seq_id]);
        }
        else if (ligandViewParams.label_comp_id) {
            residueParam = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_comp_id(), ligandViewParams.label_comp_id]);
        }
        if (residueParam)
            atomGroupsParams['residue-test'] = residueParam;
        // Chain Param
        if (ligandViewParams.auth_asym_id) {
            atomGroupsParams['chain-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), ligandViewParams.auth_asym_id]);
        }
        else if (ligandViewParams.struct_asym_id) {
            atomGroupsParams['chain-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_asym_id(), ligandViewParams.struct_asym_id]);
        }
        // Construct core query
        var core = ligandViewParams.show_all ?
            builder_1.MolScriptBuilder.struct.generator.atomGroups(atomGroupsParams) :
            builder_1.MolScriptBuilder.struct.filter.first([
                builder_1.MolScriptBuilder.struct.generator.atomGroups(atomGroupsParams)
            ]);
        // Construct surroundings query
        var surroundings = builder_1.MolScriptBuilder.struct.modifier.includeSurroundings({ 0: core, radius: 5, 'as-whole-residues': true });
        return {
            core: core,
            surroundings: surroundings
        };
    }
    LigandView.query = query;
    function branchedQuery(params) {
        var entityObjArray = [];
        params.atom_site.forEach(function (param) {
            var qEntities = {
                'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()]),
                'residue-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), param.auth_seq_id])
            };
            entityObjArray.push(qEntities);
        });
        var atmGroupsQueries = [];
        entityObjArray.forEach(function (entityObj) {
            atmGroupsQueries.push(builder_1.MolScriptBuilder.struct.generator.atomGroups(entityObj));
        });
        var core = builder_1.MolScriptBuilder.struct.modifier.union([
            atmGroupsQueries.length === 1
                ? atmGroupsQueries[0]
                // Need to union before merge for fast performance
                : builder_1.MolScriptBuilder.struct.combinator.merge(atmGroupsQueries.map(function (q) { return builder_1.MolScriptBuilder.struct.modifier.union([q]); }))
        ]);
        // Construct surroundings query
        var surroundings = builder_1.MolScriptBuilder.struct.modifier.includeSurroundings({ 0: core, radius: 5, 'as-whole-residues': true });
        return {
            core: core,
            surroundings: surroundings
        };
    }
    LigandView.branchedQuery = branchedQuery;
})(LigandView = exports.LigandView || (exports.LigandView = {}));
var QueryHelper;
(function (QueryHelper) {
    function getQueryObject(params) {
        var selections = [];
        params.forEach(function (param) {
            var selection = {};
            // entity
            if (param.entity_id)
                selection['entity-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_entity_id(), param.entity_id]);
            // chain
            if (param.struct_asym_id) {
                selection['chain-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_asym_id(), param.struct_asym_id]);
            }
            else if (param.auth_asym_id) {
                selection['chain-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), param.auth_asym_id]);
            }
            // residues
            if (param.label_comp_id) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_comp_id(), param.label_comp_id]);
            }
            else if (param.residue_number) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_seq_id(), param.residue_number]);
            }
            else if ((param.start_residue_number && param.end_residue_number) && (param.end_residue_number > param.start_residue_number)) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.inRange([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_seq_id(), param.start_residue_number, param.end_residue_number]);
            }
            else if ((param.start_residue_number && param.end_residue_number) && (param.end_residue_number === param.start_residue_number)) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_seq_id(), param.start_residue_number]);
            }
            else if (param.auth_seq_id) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), param.auth_seq_id]);
            }
            else if (param.auth_residue_number && !param.auth_ins_code_id) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), param.auth_residue_number]);
            }
            else if (param.auth_residue_number && param.auth_ins_code_id) {
                selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([
                    builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.authResidueId(),
                    builder_1.MolScriptBuilder.struct.type.authResidueId([undefined, param.auth_residue_number, param.auth_ins_code_id])
                ]);
            }
            else if ((param.start_auth_residue_number && param.end_auth_residue_number) && (param.end_auth_residue_number > param.start_auth_residue_number)) {
                if (param.start_auth_ins_code_id && param.end_auth_ins_code_id) {
                    selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.inRange([
                        builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.authResidueId(),
                        builder_1.MolScriptBuilder.struct.type.authResidueId([undefined, param.start_auth_residue_number, param.start_auth_ins_code_id]),
                        builder_1.MolScriptBuilder.struct.type.authResidueId([undefined, param.start_auth_residue_number, param.start_auth_ins_code_id])
                    ]);
                }
                else {
                    selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.inRange([
                        builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), param.start_auth_residue_number, param.end_auth_residue_number
                    ]);
                }
            }
            else if ((param.start_auth_residue_number && param.end_auth_residue_number) && (param.end_auth_residue_number === param.start_auth_residue_number)) {
                if (param.start_auth_ins_code_id) {
                    selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([
                        builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.authResidueId(),
                        builder_1.MolScriptBuilder.struct.type.authResidueId([undefined, param.start_auth_residue_number, param.start_auth_ins_code_id])
                    ]);
                }
                else {
                    selection['residue-test'] = builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), param.start_auth_residue_number]);
                }
            }
            // atoms
            if (param.atoms) {
                var atomsArr_1 = [];
                param.atoms.forEach(function (atom) {
                    atomsArr_1.push(builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.ammp('label_atom_id'), atom]));
                });
                selection['atom-test'] = builder_1.MolScriptBuilder.core.logic.or(atomsArr_1);
            }
            selections.push(selection);
        });
        var atmGroupsQueries = [];
        selections.forEach(function (selection) {
            atmGroupsQueries.push(builder_1.MolScriptBuilder.struct.generator.atomGroups(selection));
        });
        return builder_1.MolScriptBuilder.struct.modifier.union([
            atmGroupsQueries.length === 1
                ? atmGroupsQueries[0]
                : builder_1.MolScriptBuilder.struct.combinator.merge(atmGroupsQueries.map(function (q) { return builder_1.MolScriptBuilder.struct.modifier.union([q]); }))
        ]);
    }
    QueryHelper.getQueryObject = getQueryObject;
    function getInteractivityLoci(params, contextData) {
        var query = compiler_1.compile(QueryHelper.getQueryObject(params));
        var sel = query(new structure_1.QueryContext(contextData));
        return structure_1.StructureSelection.toLociWithSourceUnits(sel);
    }
    QueryHelper.getInteractivityLoci = getInteractivityLoci;
    function getHetLoci(queryExp, contextData) {
        var query = compiler_1.compile(queryExp);
        var sel = query(new structure_1.QueryContext(contextData));
        return structure_1.StructureSelection.toLociWithSourceUnits(sel);
    }
    QueryHelper.getHetLoci = getHetLoci;
})(QueryHelper = exports.QueryHelper || (exports.QueryHelper = {}));
var ModelInfo;
(function (ModelInfo) {
    function get(model, structures) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var residueCount, residueOffsets, chainIndex, hetNames, carbEntityCount, rI, cI, eI, entityType, comp_id;
            return tslib_1.__generator(this, function (_a) {
                residueCount = model.atomicHierarchy.residues._rowCount;
                residueOffsets = model.atomicHierarchy.residueAtomSegments.offsets;
                chainIndex = model.atomicHierarchy.chainAtomSegments.index;
                hetNames = [];
                carbEntityCount = 0;
                for (rI = 0; rI < residueCount; rI++) {
                    cI = chainIndex[residueOffsets[rI]];
                    eI = model.atomicHierarchy.index.getEntityFromChain(cI);
                    entityType = model.entities.data.type.value(eI);
                    if (entityType !== 'non-polymer' && entityType !== 'branched')
                        continue;
                    comp_id = model.atomicHierarchy.atoms.label_comp_id.value(residueOffsets[rI]);
                    if (entityType === 'branched') {
                        carbEntityCount++;
                    }
                    else {
                        if (hetNames.indexOf(comp_id) === -1)
                            hetNames.push(comp_id);
                    }
                }
                return [2 /*return*/, {
                        hetNames: hetNames,
                        carbEntityCount: carbEntityCount
                    }];
            });
        });
    }
    ModelInfo.get = get;
})(ModelInfo = exports.ModelInfo || (exports.ModelInfo = {}));
//# sourceMappingURL=helpers.js.map

/***/ }),
/* 406 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DomainAnnotationsColorThemeProvider = exports.DomainAnnotationsColorTheme = exports.DomainAnnotationsColorThemeParams = void 0;
var prop_1 = __webpack_require__(407);
var structure_1 = __webpack_require__(4);
var color_1 = __webpack_require__(24);
var param_definition_1 = __webpack_require__(2);
var DomainColors = [
    color_1.Color.fromRgb(170, 170, 170),
    color_1.Color.fromRgb(255, 112, 3)
];
exports.DomainAnnotationsColorThemeParams = {
    type: param_definition_1.ParamDefinition.MappedStatic('', {
        '': param_definition_1.ParamDefinition.EmptyGroup()
    })
};
function DomainAnnotationsColorTheme(ctx, props) {
    var color;
    if (ctx.structure && !ctx.structure.isEmpty && ctx.structure.models[0].customProperties.has(prop_1.DomainAnnotationsProvider.descriptor)) {
        var getDomains_1 = prop_1.DomainAnnotations.getDomains;
        var issue_1 = props.type.params.kind;
        color = function (location) {
            if (structure_1.StructureElement.Location.is(location) && getDomains_1(location).indexOf(issue_1) >= 0) {
                return DomainColors[1];
            }
            return DomainColors[0];
        };
    }
    else {
        color = function () { return DomainColors[0]; };
    }
    return {
        factory: DomainAnnotationsColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: 'Highlights Sequnece and Structure Domain Annotations. Data obtained via PDBe.',
    };
}
exports.DomainAnnotationsColorTheme = DomainAnnotationsColorTheme;
exports.DomainAnnotationsColorThemeProvider = {
    name: 'pdbe-domain-annotations',
    label: 'Domain annotations',
    category: "Miscellaneous" /* Misc */,
    factory: DomainAnnotationsColorTheme,
    getParams: function (ctx) {
        var domainNames = prop_1.DomainAnnotations.getDomainNames(ctx.structure);
        var domainTypes = prop_1.DomainAnnotations.getDomainTypes(ctx.structure);
        var optionObj = {};
        domainTypes.forEach(function (tp, index) {
            if (domainNames[index].length > 0) {
                optionObj[tp] = param_definition_1.ParamDefinition.Group({
                    kind: param_definition_1.ParamDefinition.Select(domainNames[index][0], param_definition_1.ParamDefinition.arrayToOptions(domainNames[index]))
                }, { isFlat: true });
            }
        });
        if (Object.keys(optionObj).length > 0) {
            return {
                type: param_definition_1.ParamDefinition.MappedStatic(optionObj[0], optionObj)
            };
        }
        else {
            return {
                type: param_definition_1.ParamDefinition.MappedStatic('', {
                    '': param_definition_1.ParamDefinition.EmptyGroup()
                })
            };
        }
    },
    defaultValues: param_definition_1.ParamDefinition.getDefaultValues(exports.DomainAnnotationsColorThemeParams),
    isApplicable: function (ctx) { var _a; return prop_1.DomainAnnotations.isApplicable((_a = ctx.structure) === null || _a === void 0 ? void 0 : _a.models[0]); },
    ensureCustomProperties: {
        attach: function (ctx, data) {
            return data.structure ? prop_1.DomainAnnotationsProvider.attach(ctx, data.structure.models[0], void 0, true) : Promise.resolve();
        },
        detach: function (data) { return data.structure && data.structure.models[0].customProperties.reference(prop_1.DomainAnnotationsProvider.descriptor, false); }
    }
};
//# sourceMappingURL=color.js.map

/***/ }),
/* 407 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DomainAnnotationsProvider = exports.DomainAnnotationsParams = exports.DomainAnnotations = void 0;
var tslib_1 = __webpack_require__(0);
var structure_1 = __webpack_require__(4);
var wrapper_1 = __webpack_require__(236);
var custom_model_property_1 = __webpack_require__(276);
var param_definition_1 = __webpack_require__(2);
var array_1 = __webpack_require__(29);
var assets_1 = __webpack_require__(114);
var custom_property_1 = __webpack_require__(65);
var DomainAnnotations;
(function (DomainAnnotations) {
    DomainAnnotations.DefaultServerUrl = 'https://www.ebi.ac.uk/pdbe/api/mappings';
    function getEntryUrl(pdbId, serverUrl) {
        return serverUrl + "/" + pdbId.toLowerCase();
    }
    DomainAnnotations.getEntryUrl = getEntryUrl;
    function isApplicable(model) {
        return !!model && structure_1.Model.isFromPdbArchive(model);
    }
    DomainAnnotations.isApplicable = isApplicable;
    function fromJson(model, data) {
        var info = wrapper_1.PropertyWrapper.createInfo();
        var domainMap = createdomainMapFromJson(model, data);
        return { info: info, data: domainMap };
    }
    DomainAnnotations.fromJson = fromJson;
    function fromServer(ctx, model, props) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var url, json, data;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        url = assets_1.Asset.getUrlAsset(ctx.assetManager, getEntryUrl(model.entryId, props.serverUrl));
                        return [4 /*yield*/, ctx.assetManager.resolve(url, 'json').runInContext(ctx.runtime)];
                    case 1:
                        json = _a.sent();
                        data = json.data[model.entryId.toLowerCase()];
                        if (!data)
                            throw new Error('missing data');
                        return [2 /*return*/, { value: fromJson(model, data), assets: [json] }];
                }
            });
        });
    }
    DomainAnnotations.fromServer = fromServer;
    var _emptyArray = [];
    function getDomains(e) {
        if (!structure_1.Unit.isAtomic(e.unit))
            return _emptyArray;
        var prop = exports.DomainAnnotationsProvider.get(e.unit.model).value;
        if (!prop || !prop.data)
            return _emptyArray;
        var rI = e.unit.residueIndex[e.element];
        return prop.data.domains.has(rI) ? prop.data.domains.get(rI) : _emptyArray;
    }
    DomainAnnotations.getDomains = getDomains;
    function getDomainTypes(structure) {
        if (!structure)
            return _emptyArray;
        var prop = exports.DomainAnnotationsProvider.get(structure.models[0]).value;
        if (!prop || !prop.data)
            return _emptyArray;
        return prop.data.domainTypes;
    }
    DomainAnnotations.getDomainTypes = getDomainTypes;
    function getDomainNames(structure) {
        if (!structure)
            return _emptyArray;
        var prop = exports.DomainAnnotationsProvider.get(structure.models[0]).value;
        if (!prop || !prop.data)
            return _emptyArray;
        return prop.data.domainNames;
    }
    DomainAnnotations.getDomainNames = getDomainNames;
})(DomainAnnotations || (DomainAnnotations = {}));
exports.DomainAnnotations = DomainAnnotations;
exports.DomainAnnotationsParams = {
    serverUrl: param_definition_1.ParamDefinition.Text(DomainAnnotations.DefaultServerUrl, { description: 'JSON API Server URL' })
};
exports.DomainAnnotationsProvider = custom_model_property_1.CustomModelProperty.createProvider({
    label: 'Domain annotations',
    descriptor: custom_property_1.CustomPropertyDescriptor({
        name: 'domain_annotations'
    }),
    type: 'static',
    defaultParams: exports.DomainAnnotationsParams,
    getParams: function (data) { return exports.DomainAnnotationsParams; },
    isApplicable: function (data) { return DomainAnnotations.isApplicable(data); },
    obtain: function (ctx, data, props) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
        var p;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    p = tslib_1.__assign(tslib_1.__assign({}, param_definition_1.ParamDefinition.getDefaultValues(exports.DomainAnnotationsParams)), props);
                    return [4 /*yield*/, DomainAnnotations.fromServer(ctx, data, p)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); }
});
function findChainLabel(map, label_entity_id, label_asym_id) {
    var entityIndex = map.entities.getEntityIndex;
    var eI = entityIndex(label_entity_id);
    if (eI < 0 || !map.entity_index_label_asym_id.has(eI))
        return -1;
    var cm = map.entity_index_label_asym_id.get(eI);
    if (!cm)
        return -1;
    return cm.has(label_asym_id) ? cm.get(label_asym_id) : -1;
}
function findResidue(modelData, map, label_entity_id, label_asym_id, label_seq_id) {
    var cI = findChainLabel(map, label_entity_id, label_asym_id);
    if (cI < 0)
        return -1;
    var rm = map.chain_index_auth_seq_id.get(cI);
    return rm.has(label_seq_id) ? rm.get(label_seq_id) : -1;
}
function createdomainMapFromJson(modelData, data) {
    var domainTypes = [];
    var domainNames = [];
    var ret = new Map();
    var defaultDomains = ['Pfam', 'InterPro', 'CATH', 'SCOP'];
    for (var _i = 0, _a = Object.keys(data); _i < _a.length; _i++) {
        var db_name = _a[_i];
        if (defaultDomains.indexOf(db_name) === -1)
            continue;
        var tempDomains = [];
        domainTypes.push(db_name);
        var db = data[db_name];
        for (var _b = 0, _c = Object.keys(db); _b < _c.length; _b++) {
            var db_code = _c[_b];
            var domain = db[db_code];
            for (var _d = 0, _e = domain.mappings; _d < _e.length; _d++) {
                var map = _e[_d];
                array_1.arraySetAdd(tempDomains, domain.identifier);
                var indexData = modelData.atomicHierarchy.index;
                var indexMap = indexData.map;
                for (var i = map.start.residue_number; i <= map.end.residue_number; i++) {
                    var seq_id = i;
                    var idx = findResidue(modelData, indexMap, map.entity_id + '', map.chain_id, seq_id);
                    var addVal = [domain.identifier];
                    var prevVal = ret.get(idx);
                    if (prevVal) {
                        prevVal.push(domain.identifier);
                        addVal = prevVal;
                    }
                    ret.set(idx, addVal);
                }
            }
        }
        domainNames.push(tempDomains);
    }
    return {
        domains: structure_1.IndexedCustomProperty.fromResidueMap(ret),
        domainNames: domainNames,
        domainTypes: domainTypes
    };
}
//# sourceMappingURL=prop.js.map

/***/ }),
/* 408 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PDBeDomainAnnotations = void 0;
var tslib_1 = __webpack_require__(0);
var prop_1 = __webpack_require__(407);
var color_1 = __webpack_require__(406);
var param_definition_1 = __webpack_require__(2);
var behavior_1 = __webpack_require__(170);
exports.PDBeDomainAnnotations = behavior_1.PluginBehavior.create({
    name: 'pdbe-domain-annotations-prop',
    category: 'custom-props',
    display: {
        name: 'Domain annotations',
        description: 'Data for domain annotations, obtained via PDBe.'
    },
    ctor: /** @class */ (function (_super) {
        tslib_1.__extends(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = prop_1.DomainAnnotationsProvider;
            _this.labelDomainAnnotations = {
                label: function (loci) { return void 0; }
            };
            return _this;
        }
        class_1.prototype.register = function () {
            this.ctx.customModelProperties.register(this.provider, this.params.autoAttach);
            this.ctx.managers.lociLabels.addProvider(this.labelDomainAnnotations);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(color_1.DomainAnnotationsColorThemeProvider);
        };
        class_1.prototype.update = function (p) {
            var updated = this.params.autoAttach !== p.autoAttach;
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customModelProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.unregister = function () {
            this.ctx.customModelProperties.unregister(prop_1.DomainAnnotationsProvider.descriptor.name);
            this.ctx.managers.lociLabels.removeProvider(this.labelDomainAnnotations);
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(color_1.DomainAnnotationsColorThemeProvider);
        };
        return class_1;
    }(behavior_1.PluginBehavior.Handler)),
    params: function () { return ({
        autoAttach: param_definition_1.ParamDefinition.Boolean(false),
        showTooltip: param_definition_1.ParamDefinition.Boolean(true)
    }); }
});
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 409 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AfConfidenceScore = void 0;
var tslib_1 = __webpack_require__(0);
var int_1 = __webpack_require__(6);
var prop_1 = __webpack_require__(410);
var color_1 = __webpack_require__(411);
var structure_1 = __webpack_require__(4);
var param_definition_1 = __webpack_require__(2);
var behavior_1 = __webpack_require__(68);
exports.AfConfidenceScore = behavior_1.PluginBehavior.create({
    name: 'af-confidence-prop',
    category: 'custom-props',
    display: {
        name: 'AlphaFold Confidence Score',
        description: 'AlphaFold Confidence Score.'
    },
    ctor: /** @class */ (function (_super) {
        tslib_1.__extends(class_1, _super);
        function class_1() {
            var _this = _super !== null && _super.apply(this, arguments) || this;
            _this.provider = prop_1.AfConfidenceProvider;
            _this.labelAfConfScore = {
                label: function (loci) {
                    if (!_this.params.showTooltip)
                        return void 0;
                    switch (loci.kind) {
                        case 'element-loci':
                            if (loci.elements.length === 0)
                                return void 0;
                            var e = loci.elements[0];
                            var u = e.unit;
                            if (!u.model.customProperties.hasReference(prop_1.AfConfidenceProvider.descriptor))
                                return void 0;
                            var se = structure_1.StructureElement.Location.create(loci.structure, u, u.elements[int_1.OrderedSet.getAt(e.indices, 0)]);
                            var confidenceScore = prop_1.AfConfidence.getConfidenceScore(se);
                            //VIP hover text
                            return confidenceScore ? "Confidence score: " + confidenceScore[0] + " <small>( " + confidenceScore[1] + " )</small>\n                        <br/>Exposure: " + confidenceScore[2] + " <small>( " + confidenceScore[3] + " )</small>\n                        <br/>AA: " + confidenceScore[4] + "\n                        <br/>PTM: " + confidenceScore[6]
                                : "No confidence score";
                        default: return void 0;
                    }
                }
            };
            return _this;
        }
        class_1.prototype.register = function () {
            this.ctx.customModelProperties.register(this.provider, this.params.autoAttach);
            this.ctx.managers.lociLabels.addProvider(this.labelAfConfScore);
            this.ctx.representation.structure.themes.colorThemeRegistry.add(color_1.AfConfidenceColorThemeProvider);
        };
        class_1.prototype.update = function (p) {
            var updated = this.params.autoAttach !== p.autoAttach;
            this.params.autoAttach = p.autoAttach;
            this.params.showTooltip = p.showTooltip;
            this.ctx.customModelProperties.setDefaultAutoAttach(this.provider.descriptor.name, this.params.autoAttach);
            return updated;
        };
        class_1.prototype.unregister = function () {
            this.ctx.customModelProperties.unregister(prop_1.AfConfidenceProvider.descriptor.name);
            this.ctx.managers.lociLabels.removeProvider(this.labelAfConfScore);
            this.ctx.representation.structure.themes.colorThemeRegistry.remove(color_1.AfConfidenceColorThemeProvider);
        };
        return class_1;
    }(behavior_1.PluginBehavior.Handler)),
    params: function () { return ({
        autoAttach: param_definition_1.ParamDefinition.Boolean(false),
        showTooltip: param_definition_1.ParamDefinition.Boolean(true)
    }); }
});
//# sourceMappingURL=behavior.js.map

/***/ }),
/* 410 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.AfConfidenceProvider = exports.AfConfidenceParams = exports.AfConfidence = void 0;
var tslib_1 = __webpack_require__(0);
var db_1 = __webpack_require__(7);
var schema_1 = __webpack_require__(135);
var structure_1 = __webpack_require__(4);
var param_definition_1 = __webpack_require__(2);
var mmcif_1 = __webpack_require__(71);
var custom_model_property_1 = __webpack_require__(276);
var custom_property_1 = __webpack_require__(65);
var date_1 = __webpack_require__(308);
var array_1 = __webpack_require__(29);
var AfConfidence;
(function (AfConfidence) {
    AfConfidence.DefaultServerUrl = '';
    function isApplicable(model) {
        return !!model && structure_1.Model.isFromPdbArchive(model);
    }
    AfConfidence.isApplicable = isApplicable;
    AfConfidence.Schema = {
        local_metric_values: {
            label_asym_id: db_1.Column.Schema.str,
            label_comp_id: db_1.Column.Schema.str,
            label_seq_id: db_1.Column.Schema.int,
            metric_id: db_1.Column.Schema.int,
            metric_value: db_1.Column.Schema.float,
            model_id: db_1.Column.Schema.int,
            ordinal_id: db_1.Column.Schema.int,
            exposure: db_1.Column.Schema.int,
            aa: db_1.Column.Schema.str,
            aa_ptm: db_1.Column.Schema.str,
            ptm: db_1.Column.Schema.str,
            idr: db_1.Column.Schema.str,
            idr_ptm : db_1.Column.Schema.str,
            structure_group: db_1.Column.Schema.str,
        }
    };
    function tryGetInfoFromCif(categoryName, model) {
        if (!mmcif_1.MmcifFormat.is(model.sourceData) || !model.sourceData.data.frame.categoryNames.includes(categoryName)) {
            return;
        }
        var timestampField = model.sourceData.data.frame.categories[categoryName].getField('metric_value');
        if (!timestampField || timestampField.rowCount === 0)
            return;
        return { timestamp_utc: timestampField.str(0) || date_1.dateToUtcString(new Date()) };
    }
    function fromCif(ctx, model) {
        var info = tryGetInfoFromCif('ma_qa_metric_local', model);
        if (!info)
            return;
        var data = getCifData(model);
        var metricMap = createScoreMapFromCif(model, data.residues);
        return { info: info, data: metricMap };
    }
    AfConfidence.fromCif = fromCif;
    function fromCifOrServer(ctx, model, props) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var cif;
            return tslib_1.__generator(this, function (_a) {
                cif = fromCif(ctx, model);
                return [2 /*return*/, { value: cif }];
            });
        });
    }
    AfConfidence.fromCifOrServer = fromCifOrServer;
    function getConfidenceScore(e) {
        if (!structure_1.Unit.isAtomic(e.unit))
            return [-1, 'No Score'];
        var prop = exports.AfConfidenceProvider.get(e.unit.model).value;
        if (!prop || !prop.data)
            return [-1, 'No Score'];
        var rI = e.unit.residueIndex[e.element];
        return prop.data.score.has(rI) ? prop.data.score.get(rI) : [-1, 'No Score'];
    }
    AfConfidence.getConfidenceScore = getConfidenceScore;
    var _emptyArray = [];
    function getCategories(structure) {
        if (!structure)
            return _emptyArray;
        var prop = exports.AfConfidenceProvider.get(structure.models[0]).value;
        if (!prop || !prop.data)
            return _emptyArray;
        return prop.data.category;
    }
    AfConfidence.getCategories = getCategories;
    function getCifData(model) {
        if (!mmcif_1.MmcifFormat.is(model.sourceData))
            throw new Error('Data format must be mmCIF.');
        return {
            residues: schema_1.toTable(AfConfidence.Schema.local_metric_values, model.sourceData.data.frame.categories.ma_qa_metric_local),
        };
    }
})(AfConfidence || (AfConfidence = {}));
exports.AfConfidence = AfConfidence;
exports.AfConfidenceParams = {
    serverUrl: param_definition_1.ParamDefinition.Text(AfConfidence.DefaultServerUrl, { description: 'JSON API Server URL' })
};
exports.AfConfidenceProvider = custom_model_property_1.CustomModelProperty.createProvider({
    label: 'AF Confidence Score',
    descriptor: custom_property_1.CustomPropertyDescriptor({
        name: 'af_confidence_score'
    }),
    type: 'static',
    defaultParams: exports.AfConfidenceParams,
    getParams: function (data) { return exports.AfConfidenceParams; },
    isApplicable: function (data) { return AfConfidence.isApplicable(data); },
    obtain: function (ctx, data, props) { return tslib_1.__awaiter(void 0, void 0, void 0, function () {
        var p;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    p = tslib_1.__assign(tslib_1.__assign({}, param_definition_1.ParamDefinition.getDefaultValues(exports.AfConfidenceParams)), props);
                    return [4 /*yield*/, AfConfidence.fromCifOrServer(ctx, data, p)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); }
});
function createScoreMapFromCif(modelData, residueData) {
    // [AF-confidence, confidence-level, accessibility, accessibility-level, ptm]
    var ret = new Map();
    var label_asym_id = residueData.label_asym_id, label_seq_id = residueData.label_seq_id, metric_value = residueData.metric_value, exposure = residueData.exposure, aa = residueData.aa, aa_ptm = residueData.aa_ptm, ptm = residueData.ptm, idr = residueData.idr, idr_ptm = residueData.idr_ptm, structure_group = residueData.structure_group, _rowCount = residueData._rowCount;
    var categories = [];
    for (var i = 0; i < _rowCount; i++) {
        var confidenceScore = metric_value.value(i);
        var idx = modelData.atomicHierarchy.index.findResidue('1', label_asym_id.value(i), label_seq_id.value(i), '');
        var confidencyCategory = 'Very low';
        if (confidenceScore > 50 && confidenceScore <= 70) {
            confidencyCategory = 'Low';
        }
        else if (confidenceScore > 70 && confidenceScore <= 90) {
            confidencyCategory = 'Confident';
        }
        else if (confidenceScore > 90) {
            confidencyCategory = 'Very high';
        }
        var acc = exposure.value(i);
        var exposureCategory = 'No neighbors';
        if (acc >= 1 && acc <= 5) {
            exposureCategory = 'Few neighbors';
        }
        else if (acc > 5 && acc <= 10) {
            exposureCategory = 'Many neighbors';
        }
        else if (acc > 10) {
            exposureCategory = 'Surrounded';
        }
        ret.set(idx, [
            confidenceScore, confidencyCategory,
            acc, exposureCategory, aa.value(i), aa_ptm.value(i), ptm.value(i),
            idr.value(i), idr_ptm.value(i), structure_group.value(i)
        ]);
        array_1.arraySetAdd(categories, confidencyCategory);
        array_1.arraySetAdd(categories, ptm.value(i));
    }
    return {
        score: structure_1.IndexedCustomProperty.fromResidueMap(ret),
        category: categories
    };
}
//# sourceMappingURL=prop.js.map

/***/ }),
/* 411 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AfConfidenceColorThemeProvider = exports.AfConfidenceColorTheme = exports.AfConfidenceColorThemeParams = void 0;
var prop_1 = __webpack_require__(410);
var structure_1 = __webpack_require__(4);
var color_1 = __webpack_require__(24);
// import { TableLegend } from 'Molstar/mol-util/legend';
var param_definition_1 = __webpack_require__(2);
var ConfidenceColors = {
    'No Score': color_1.Color.fromRgb(170, 170, 170),
    'Very low': color_1.Color.fromRgb(255, 125, 69),
    'Low': color_1.Color.fromRgb(255, 219, 19),
    'Confident': color_1.Color.fromRgb(101, 203, 243),
    'Very high': color_1.Color.fromRgb(0, 83, 214),
    'No neighbors': color_1.Color.fromRgb(143, 225, 162),
    'Few neighbors': color_1.Color.fromRgb(56, 191, 167),
    'Many neighbors': color_1.Color.fromRgb(54, 123, 195),
    'Surrounded': color_1.Color.fromRgb(82, 69, 130),
    'nan': color_1.Color.fromRgb(170, 170, 170),
    'absent': color_1.Color.fromRgb(170, 170, 170),
    'none': color_1.Color.fromRgb(170, 170, 170),
    'p': color_1.Color.fromRgb(220, 20, 60),
    'p_reg': color_1.Color.fromRgb(220, 20, 60),
    'p_functional_0': color_1.Color.fromRgb(220, 20, 60),
    'p_functional_5': color_1.Color.fromRgb(220, 20, 60),
    'p;p_reg': color_1.Color.fromRgb(220, 20, 60),
    'ub': color_1.Color.fromRgb(255, 219, 19),
    'ac': color_1.Color.fromRgb(255, 160, 94),
    'sm': color_1.Color.fromRgb(103, 132, 255),
    'gl': color_1.Color.fromRgb(0, 209, 179),
    'ga': color_1.Color.fromRgb(0, 127, 101),
    'detected': color_1.Color.fromRgb(2, 62, 138),
    '[GlyGly(K)]': color_1.Color.fromRgb(50, 205, 50),
    '[Acetyl (K)]': color_1.Color.fromRgb(255, 140, 0),
    '[Oxidation(M)]': color_1.Color.fromRgb(173, 216, 230),
    '[Phospho(STY)]': color_1.Color.fromRgb(220, 20, 60),
    '[Carbamidomethyl(C)]': color_1.Color.fromRgb(88, 143, 164),
    '[Cys-Cys]': color_1.Color.fromRgb(0, 206, 209),
    'IDR': color_1.Color.fromRgb(181, 181, 181),
    'folded': color_1.Color.fromRgb(54, 123, 195),
    'HELX': color_1.Color.fromRgb(93, 171, 232),
    'TURN': color_1.Color.fromRgb(224, 148, 188),
    'BEND': color_1.Color.fromRgb(250, 198, 130),
    'STRN': color_1.Color.fromRgb(140, 219, 173),
    'unstructured': color_1.Color.fromRgb(170, 170, 170),
    'Other PTM': color_1.Color.fromRgb(199, 21, 133),
};
exports.AfConfidenceColorThemeParams = {
    type: param_definition_1.ParamDefinition.MappedStatic('score', {
        'score': param_definition_1.ParamDefinition.Group({}),
        'category': param_definition_1.ParamDefinition.Group({
            kind: param_definition_1.ParamDefinition.Text()
        })
    })
};
function AfConfidenceColorTheme(ctx, props) {
    var color;
    if (ctx.structure && !ctx.structure.isEmpty && ctx.structure.models[0].customProperties.has(prop_1.AfConfidenceProvider.descriptor)) {
        var getConfidenceScore_1 = prop_1.AfConfidence.getConfidenceScore;
        if (props.type.name === 'score') {
            color = function (location) {
                if (structure_1.StructureElement.Location.is(location)) {
                    var confidenceScore = getConfidenceScore_1(location);
                    if (color_choice === 'af')
                        return ConfidenceColors[confidenceScore[1]];
                    else if (color_choice === 'exposure')
                        return ConfidenceColors[confidenceScore[3]];
                    else if (color_choice === 'aa')
                        return ConfidenceColors[confidenceScore[4]];
                    else if (color_choice === 'aa_ptm')
                        if (confidenceScore[5] in ConfidenceColors)
                            return ConfidenceColors[confidenceScore[5]];
                        else
                            return ConfidenceColors['Other PTM'];
                    else if (color_choice === 'ptm')
                        if (confidenceScore[6] in ConfidenceColors)
                            return ConfidenceColors[confidenceScore[6]];
                        else
                            return ConfidenceColors['Other PTM'];
                    else if (color_choice === 'idr')
                        return ConfidenceColors[confidenceScore[7]];
                    else if (color_choice === 'idr_ptm')
                        return ConfidenceColors[confidenceScore[8]];
                    else if (color_choice === 'structure_group')
                        return ConfidenceColors[confidenceScore[9]];
                    else
                        return ConfidenceColors[confidenceScore[1]];
                }
                return ConfidenceColors['No Score'];
            };
        }
        else {
            var categoryProp_1 = props.type.params.kind;
            color = function (location) {
                if (structure_1.StructureElement.Location.is(location)) {
                    var confidenceScore = getConfidenceScore_1(location);
                    if (confidenceScore[1] === categoryProp_1)
                        return ConfidenceColors[confidenceScore[1]];
                    return ConfidenceColors['No Score'];
                }
                return ConfidenceColors['No Score'];
            };
        }
    }
    else {
        color = function () { return ConfidenceColors['No Score']; };
    }
    return {
        factory: AfConfidenceColorTheme,
        granularity: 'group',
        color: color,
        props: props,
        description: 'Assigns residue colors according to the AF Confidence score'
    };
}
exports.AfConfidenceColorTheme = AfConfidenceColorTheme;
exports.AfConfidenceColorThemeProvider = {
    name: 'af-confidence',
    label: 'AF Confidence',
    category: "Validation" /* Validation */,
    factory: AfConfidenceColorTheme,
    getParams: function (ctx) {
        var categories = prop_1.AfConfidence.getCategories(ctx.structure);
        if (categories.length === 0) {
            return {
                type: param_definition_1.ParamDefinition.MappedStatic('score', {
                    'score': param_definition_1.ParamDefinition.Group({})
                })
            };
        }
        return {
            type: param_definition_1.ParamDefinition.MappedStatic('score', {
                'score': param_definition_1.ParamDefinition.Group({}),
                'category': param_definition_1.ParamDefinition.Group({
                    kind: param_definition_1.ParamDefinition.Select(categories[0], param_definition_1.ParamDefinition.arrayToOptions(categories))
                }, { isFlat: true })
            })
        };
    },
    defaultValues: param_definition_1.ParamDefinition.getDefaultValues(exports.AfConfidenceColorThemeParams),
    isApplicable: function (ctx) { var _a; return prop_1.AfConfidence.isApplicable((_a = ctx.structure) === null || _a === void 0 ? void 0 : _a.models[0]); },
    ensureCustomProperties: {
        attach: function (ctx, data) { return data.structure ? prop_1.AfConfidenceProvider.attach(ctx, data.structure.models[0], void 0, true) : Promise.resolve(); },
        detach: function (data) { return data.structure && data.structure.models[0].customProperties.reference(prop_1.AfConfidenceProvider.descriptor, false); }
    }
};
//# sourceMappingURL=color.js.map

/***/ }),
/* 412 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.renderSuperposition = exports.initSuperposition = void 0;
var tslib_1 = __webpack_require__(0);
var linear_algebra_1 = __webpack_require__(1);
var builder_1 = __webpack_require__(10);
var transforms_1 = __webpack_require__(28);
var assets_1 = __webpack_require__(114);
var helpers_1 = __webpack_require__(405);
var lists_1 = __webpack_require__(88);
var color_1 = __webpack_require__(43);
var script_1 = __webpack_require__(120);
function getRandomColor(plugin, segmentIndex) {
    var clList = lists_1.ColorLists;
    var spState = plugin.customState.superpositionState;
    var palleteIndex = spState.colorState[segmentIndex].palleteIndex;
    var colorIndex = spState.colorState[segmentIndex].colorIndex;
    if (clList[spState.colorPalette[palleteIndex]].list[colorIndex + 1]) {
        colorIndex += 1;
    }
    else {
        colorIndex = 0;
        palleteIndex = spState.colorPalette[palleteIndex + 1] ? palleteIndex + 1 : 0;
    }
    var palleteName = spState.colorPalette[palleteIndex];
    plugin.customState.superpositionState.colorState[segmentIndex].palleteIndex = palleteIndex;
    plugin.customState.superpositionState.colorState[segmentIndex].colorIndex = colorIndex;
    return clList[palleteName].list[colorIndex];
}
function initSuperposition(plugin) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var customState, superpositionParams, segmentData, segmentIndex, clusterIndexs, entryList, clusters;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, plugin.clear()];
                case 1:
                    _a.sent();
                    customState = plugin.customState;
                    superpositionParams = customState.initParams.superpositionParams;
                    plugin.customState.superpositionState = {
                        models: {},
                        entries: {},
                        refMaps: {},
                        segmentData: void 0,
                        matrixData: {},
                        activeSegment: 0,
                        loadedStructs: [],
                        visibleRefs: [],
                        invalidStruct: [],
                        noMatrixStruct: [],
                        hets: {},
                        colorPalette: ['dark-2', 'red-yellow-green', 'paired', 'set-1', 'accent', 'set-2', 'rainbow'],
                        colorState: []
                    };
                    // Get segment and cluster information for the given uniprot accession
                    return [4 /*yield*/, getSegmentData(plugin)];
                case 2:
                    // Get segment and cluster information for the given uniprot accession
                    _a.sent();
                    segmentData = plugin.customState.superpositionState.segmentData;
                    if (!segmentData)
                        return [2 /*return*/];
                    // Load Matrix Data
                    return [4 /*yield*/, getMatrixData(plugin)];
                case 3:
                    // Load Matrix Data
                    _a.sent();
                    if (!plugin.customState.superpositionState.segmentData)
                        return [2 /*return*/];
                    segmentData.forEach(function () {
                        plugin.customState.superpositionState.loadedStructs.push([]);
                        plugin.customState.superpositionState.visibleRefs.push([]);
                        plugin.customState.superpositionState.colorState.push({ palleteIndex: 0, colorIndex: -1 });
                    });
                    segmentIndex = (superpositionParams && superpositionParams.segment) ? superpositionParams.segment - 1 : 0;
                    plugin.customState.superpositionState.activeSegment = segmentIndex + 1;
                    clusterIndexs = (superpositionParams && superpositionParams.cluster) ? superpositionParams.cluster : void 0;
                    // Emit segment API data load event
                    plugin.customState.events.superpositionInit.next(true);
                    entryList = [];
                    clusters = segmentData[segmentIndex].clusters;
                    clusters.forEach(function (cluster, clusterIndex) {
                        // Validate for cluster index if provided in superPositionParams
                        if (clusterIndexs && clusterIndexs.indexOf(clusterIndex) === -1)
                            return;
                        // Add respresentative structure to the list
                        if (superpositionParams && superpositionParams.superposeAll) {
                            entryList = entryList.concat(cluster);
                        }
                        else {
                            entryList.push(cluster[0]);
                        }
                    });
                    // entryList = [{pdb_id: "3d12", auth_asym_id: "D", struct_asym_id: "C", entity_id: '1', is_representative: true}];
                    return [4 /*yield*/, renderSuperposition(plugin, segmentIndex, entryList)];
                case 4:
                    // entryList = [{pdb_id: "3d12", auth_asym_id: "D", struct_asym_id: "C", entity_id: '1', is_representative: true}];
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
exports.initSuperposition = initSuperposition;
function createCarbVisLabel(carbLigNamesAndCount) {
    var compList = [];
    for (var carbCompId in carbLigNamesAndCount) {
        compList.push(carbCompId + " (" + carbLigNamesAndCount[carbCompId] + ")");
    }
    return compList.join(', ');
}
function renderSuperposition(plugin, segmentIndex, entryList) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var customState, superpositionParams, busyFlagOn;
        var _this = this;
        return tslib_1.__generator(this, function (_a) {
            customState = plugin.customState;
            superpositionParams = customState.initParams.superpositionParams;
            busyFlagOn = false;
            if (entryList.length > 1) {
                busyFlagOn = true;
                customState.events.isBusy.next(true);
            }
            // Load Coordinates and render respresentations
            return [2 /*return*/, plugin.dataTransaction(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                    var spState, entryList_1, entryList_1_1, s, strUrl, strInstance, modelRef, clearOnFail, polymerInstance, modelInstance, isBinary, _a, model, structure, matrix, chainSel, uniformColor1, uniformColor2, invalidStruct, state, hetInfo, hets, hets_1, hets_1_1, het, ligand, labelTagParams, hetColor, _b, r, g, b, ligandExp, e_1_1, carbEntityCount, allCarbPolymers, polymerChainWithSurroundings, i, _i, _c, carbEntityChainId, carbEntityChain, carbEntityChainInVicinity, data, carbChainSel, carbLigands, carbLigNamesAndCount, carbLigList, _d, _e, carbLigs, ligResDetails, carbVisLabel, branchedEntity, labelTagParams, ligandExp, loadedStructIndex, e_2_1;
                    var e_2, _f, e_1, _g;
                    return tslib_1.__generator(this, function (_h) {
                        switch (_h.label) {
                            case 0:
                                spState = plugin.customState.superpositionState;
                                _h.label = 1;
                            case 1:
                                _h.trys.push([1, 41, 42, 47]);
                                entryList_1 = tslib_1.__asyncValues(entryList);
                                _h.label = 2;
                            case 2: return [4 /*yield*/, entryList_1.next()];
                            case 3:
                                if (!(entryList_1_1 = _h.sent(), !entryList_1_1.done)) return [3 /*break*/, 40];
                                s = entryList_1_1.value;
                                // validate matrix availability
                                if (!spState.matrixData[s.pdb_id + "_" + s.auth_asym_id]) {
                                    spState.noMatrixStruct.push(s.pdb_id + "_" + s.struct_asym_id);
                                    spState.invalidStruct.push(s.pdb_id + "_" + s.struct_asym_id);
                                    return [3 /*break*/, 39];
                                }
                                spState.loadedStructs[segmentIndex].push(s.pdb_id + "_" + s.struct_asym_id);
                                strUrl = customState.initParams.pdbeUrl + "model-server/v1/" + s.pdb_id + "/atoms?auth_asym_id=" + s.auth_asym_id + "&encoding=" + customState.initParams.encoding;
                                if (superpositionParams && superpositionParams.ligandView)
                                    strUrl = "https://www.ebi.ac.uk/pdbe/entry-files/download/" + s.pdb_id + ".bcif";
                                strInstance = void 0;
                                modelRef = void 0;
                                clearOnFail = true;
                                if (!(superpositionParams && superpositionParams.ligandView && spState.entries[s.pdb_id])) return [3 /*break*/, 5];
                                polymerInstance = plugin.state.data.select(spState.entries[s.pdb_id])[0];
                                modelRef = polymerInstance.transform.parent;
                                modelInstance = plugin.state.data.select(modelRef)[0];
                                return [4 /*yield*/, plugin.builders.structure.createStructure(modelInstance, { name: 'model', params: {} })];
                            case 4:
                                strInstance = _h.sent();
                                clearOnFail = false;
                                return [3 /*break*/, 7];
                            case 5:
                                isBinary = customState.initParams.encoding === 'bcif' ? true : false;
                                return [4 /*yield*/, loadStructure(plugin, strUrl, 'mmcif', isBinary)];
                            case 6:
                                _a = _h.sent(), model = _a.model, structure = _a.structure;
                                strInstance = structure;
                                modelRef = model.ref;
                                _h.label = 7;
                            case 7:
                                if (!strInstance)
                                    return [3 /*break*/, 39];
                                // Store Refs in state
                                if (!spState.models[s.pdb_id + "_" + s.struct_asym_id])
                                    spState.models[s.pdb_id + "_" + s.struct_asym_id] = strInstance === null || strInstance === void 0 ? void 0 : strInstance.ref;
                                if (superpositionParams && superpositionParams.ligandView && !spState.entries[s.pdb_id])
                                    spState.entries[s.pdb_id] = strInstance === null || strInstance === void 0 ? void 0 : strInstance.ref;
                                matrix = linear_algebra_1.Mat4.ofRows(plugin.customState.superpositionState.matrixData[s.pdb_id + "_" + s.auth_asym_id].matrix);
                                return [4 /*yield*/, transform(plugin, strInstance, matrix)];
                            case 8:
                                _h.sent();
                                chainSel = void 0;
                                if (!((superpositionParams && superpositionParams.ligandView) && s.is_representative)) return [3 /*break*/, 12];
                                uniformColor1 = getRandomColor(plugin, segmentIndex);
                                return [4 /*yield*/, plugin.builders.structure.tryCreateComponentFromExpression(strInstance, chainSelection(s.struct_asym_id), "Chain-" + segmentIndex, { label: "Chain", tags: ["superposition-sel"] })];
                            case 9:
                                chainSel = _h.sent();
                                if (!chainSel) return [3 /*break*/, 11];
                                return [4 /*yield*/, plugin.builders.structure.representation.addRepresentation(chainSel, { type: 'putty', color: 'uniform', colorParams: { value: uniformColor1 }, size: 'uniform' }, { tag: "superposition-visual" })];
                            case 10:
                                _h.sent();
                                spState.refMaps[chainSel.ref] = s.pdb_id + "_" + s.struct_asym_id;
                                _h.label = 11;
                            case 11: return [3 /*break*/, 16];
                            case 12:
                                if (!((superpositionParams && superpositionParams.ligandView) && !s.is_representative)) return [3 /*break*/, 13];
                                return [3 /*break*/, 16];
                            case 13:
                                uniformColor2 = getRandomColor(plugin, segmentIndex);
                                return [4 /*yield*/, plugin.builders.structure.tryCreateComponentStatic(strInstance, 'polymer', { label: "Chain", tags: ["Chain-" + segmentIndex, "superposition-sel"] })];
                            case 14:
                                chainSel = _h.sent();
                                if (!chainSel) return [3 /*break*/, 16];
                                return [4 /*yield*/, plugin.builders.structure.representation.addRepresentation(chainSel, { type: 'putty', color: 'uniform', colorParams: { value: uniformColor2 }, size: 'uniform' }, { tag: "superposition-visual" })];
                            case 15:
                                _h.sent();
                                spState.refMaps[chainSel.ref] = s.pdb_id + "_" + s.struct_asym_id;
                                _h.label = 16;
                            case 16:
                                invalidStruct = chainSel ? false : true;
                                if (!(superpositionParams && superpositionParams.ligandView)) return [3 /*break*/, 39];
                                state = plugin.state.data;
                                return [4 /*yield*/, getLigandNamesFromModelData(plugin, state, modelRef)];
                            case 17:
                                hetInfo = _h.sent();
                                hets = hetInfo ? hetInfo.hetNames : [];
                                if (!(hets && hets.length > 0)) return [3 /*break*/, 31];
                                _h.label = 18;
                            case 18:
                                _h.trys.push([18, 25, 26, 31]);
                                hets_1 = (e_1 = void 0, tslib_1.__asyncValues(hets));
                                _h.label = 19;
                            case 19: return [4 /*yield*/, hets_1.next()];
                            case 20:
                                if (!(hets_1_1 = _h.sent(), !hets_1_1.done)) return [3 /*break*/, 24];
                                het = hets_1_1.value;
                                ligand = builder_1.MolScriptBuilder.struct.generator.atomGroups({
                                    'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), s.auth_asym_id]),
                                    'residue-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_comp_id(), het]),
                                    'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()])
                                });
                                labelTagParams = { label: "" + het, tags: ["superposition-ligand-sel"] };
                                hetColor = color_1.Color.fromRgb(253, 3, 253);
                                if (superpositionParams && superpositionParams.ligandColor) {
                                    _b = superpositionParams.ligandColor, r = _b.r, g = _b.g, b = _b.b;
                                    hetColor = color_1.Color.fromRgb(r, g, b);
                                }
                                return [4 /*yield*/, plugin.builders.structure.tryCreateComponentFromExpression(strInstance, ligand, het + "-" + segmentIndex, labelTagParams)];
                            case 21:
                                ligandExp = _h.sent();
                                if (!ligandExp) return [3 /*break*/, 23];
                                return [4 /*yield*/, plugin.builders.structure.representation.addRepresentation(ligandExp, { type: 'ball-and-stick', color: 'uniform', colorParams: { value: hetColor } }, { tag: "superposition-ligand-visual" })];
                            case 22:
                                _h.sent();
                                spState.refMaps[ligandExp.ref] = s.pdb_id + "_" + s.struct_asym_id;
                                invalidStruct = false;
                                _h.label = 23;
                            case 23: return [3 /*break*/, 19];
                            case 24: return [3 /*break*/, 31];
                            case 25:
                                e_1_1 = _h.sent();
                                e_1 = { error: e_1_1 };
                                return [3 /*break*/, 31];
                            case 26:
                                _h.trys.push([26, , 29, 30]);
                                if (!(hets_1_1 && !hets_1_1.done && (_g = hets_1.return))) return [3 /*break*/, 28];
                                return [4 /*yield*/, _g.call(hets_1)];
                            case 27:
                                _h.sent();
                                _h.label = 28;
                            case 28: return [3 /*break*/, 30];
                            case 29:
                                if (e_1) throw e_1.error;
                                return [7 /*endfinally*/];
                            case 30: return [7 /*endfinally*/];
                            case 31:
                                carbEntityCount = hetInfo ? hetInfo.carbEntityCount : 0;
                                if (!(carbEntityCount > 0)) return [3 /*break*/, 38];
                                return [4 /*yield*/, getCarbPolymerDetailsFromApi(plugin, s.pdb_id)];
                            case 32:
                                allCarbPolymers = _h.sent();
                                polymerChainWithSurroundings = builder_1.MolScriptBuilder.struct.modifier.includeSurroundings({
                                    0: builder_1.MolScriptBuilder.struct.generator.atomGroups({
                                        'entity-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.ammp('entityType'), 'polymer']),
                                        'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), s.auth_asym_id]),
                                        'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()])
                                    }),
                                    radius: 5,
                                    'as-whole-residues': true
                                });
                                i = 0;
                                _i = 0, _c = allCarbPolymers.branchedChains;
                                _h.label = 33;
                            case 33:
                                if (!(_i < _c.length)) return [3 /*break*/, 38];
                                carbEntityChainId = _c[_i];
                                carbEntityChain = builder_1.MolScriptBuilder.struct.generator.atomGroups({
                                    'entity-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.ammp('entityType'), 'branched']),
                                    'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), carbEntityChainId]),
                                    'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()])
                                });
                                carbEntityChainInVicinity = builder_1.MolScriptBuilder.struct.filter.intersectedBy({
                                    0: polymerChainWithSurroundings,
                                    by: carbEntityChain
                                });
                                data = (plugin.state.data.select(strInstance.ref)[0].obj).data;
                                carbChainSel = script_1.Script.getStructureSelection(carbEntityChainInVicinity, data);
                                if (!(carbChainSel && carbChainSel.kind === 'sequence')) return [3 /*break*/, 36];
                                carbLigands = [];
                                carbLigNamesAndCount = {};
                                carbLigList = [];
                                for (_d = 0, _e = allCarbPolymers.branchedLigands[i]; _d < _e.length; _d++) {
                                    carbLigs = _e[_d];
                                    ligResDetails = carbLigs.split('-');
                                    carbLigands.push(builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_seq_id(), +ligResDetails[1]]));
                                    if (carbLigNamesAndCount[ligResDetails[0]]) {
                                        carbLigNamesAndCount[ligResDetails[0]]++;
                                    }
                                    else {
                                        carbLigNamesAndCount[ligResDetails[0]] = 1;
                                    }
                                    carbLigList.push(ligResDetails[0]);
                                }
                                carbVisLabel = createCarbVisLabel(carbLigNamesAndCount);
                                branchedEntity = builder_1.MolScriptBuilder.struct.generator.atomGroups({
                                    'entity-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.ammp('entityType'), 'branched']),
                                    'group-by': builder_1.MolScriptBuilder.core.str.concat([builder_1.MolScriptBuilder.struct.atomProperty.core.operatorName(), builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.residueKey()]),
                                    'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.auth_asym_id(), carbEntityChainId]),
                                    'residue-test': builder_1.MolScriptBuilder.core.logic.or(carbLigands)
                                });
                                labelTagParams = { label: "" + carbVisLabel, tags: ["superposition-carb-sel"] };
                                return [4 /*yield*/, plugin.builders.structure.tryCreateComponentFromExpression(strInstance, branchedEntity, carbLigList.join('-') + "-" + segmentIndex, labelTagParams)];
                            case 34:
                                ligandExp = _h.sent();
                                if (!ligandExp) return [3 /*break*/, 36];
                                return [4 /*yield*/, plugin.builders.structure.representation.addRepresentation(ligandExp, { type: 'carbohydrate' }, { tag: "superposition-carb-visual" })];
                            case 35:
                                _h.sent();
                                spState.refMaps[ligandExp.ref] = s.pdb_id + "_" + s.struct_asym_id;
                                invalidStruct = false;
                                _h.label = 36;
                            case 36:
                                i++;
                                _h.label = 37;
                            case 37:
                                _i++;
                                return [3 /*break*/, 33];
                            case 38:
                                if (invalidStruct) {
                                    spState.invalidStruct.push(s.pdb_id + "_" + s.struct_asym_id);
                                    loadedStructIndex = spState.loadedStructs[segmentIndex].indexOf(s.pdb_id + "_" + s.struct_asym_id);
                                    if (loadedStructIndex > -1)
                                        spState.loadedStructs[segmentIndex].splice(loadedStructIndex, 1);
                                    // remove downloaded data
                                    if (clearOnFail) {
                                        // const m = plugin.state.data.select(modelRef)[0];
                                        // const t = plugin.state.data.select(m.transform.parent)[0];
                                        // const d = plugin.state.data.select(t.transform.parent)[0];
                                        // PluginCommands.State.RemoveObject(plugin, { state: d.parent!, ref: d.transform.parent, removeParentGhosts: true });
                                    }
                                }
                                else {
                                    // if(interactingHets.length > 0) spState.hets[`${s.pdb_id}_${s.struct_asym_id}`] = interactingHets;
                                }
                                _h.label = 39;
                            case 39: return [3 /*break*/, 2];
                            case 40: return [3 /*break*/, 47];
                            case 41:
                                e_2_1 = _h.sent();
                                e_2 = { error: e_2_1 };
                                return [3 /*break*/, 47];
                            case 42:
                                _h.trys.push([42, , 45, 46]);
                                if (!(entryList_1_1 && !entryList_1_1.done && (_f = entryList_1.return))) return [3 /*break*/, 44];
                                return [4 /*yield*/, _f.call(entryList_1)];
                            case 43:
                                _h.sent();
                                _h.label = 44;
                            case 44: return [3 /*break*/, 46];
                            case 45:
                                if (e_2) throw e_2.error;
                                return [7 /*endfinally*/];
                            case 46: return [7 /*endfinally*/];
                            case 47:
                                if (busyFlagOn) {
                                    busyFlagOn = false;
                                    customState.events.isBusy.next(false);
                                }
                                return [2 /*return*/];
                        }
                    });
                }); })];
        });
    });
}
exports.renderSuperposition = renderSuperposition;
function getLigandNamesFromModelData(plugin, state, modelRef) {
    var _a;
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var cell, model, structures, _i, _b, s, structure, info;
        return tslib_1.__generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    cell = state.select(modelRef)[0];
                    if (!cell || !cell.obj)
                        return [2 /*return*/, void 0];
                    model = cell.obj.data;
                    if (!model)
                        return [2 /*return*/];
                    structures = [];
                    for (_i = 0, _b = plugin.managers.structure.hierarchy.selection.structures; _i < _b.length; _i++) {
                        s = _b[_i];
                        structure = (_a = s.cell.obj) === null || _a === void 0 ? void 0 : _a.data;
                        if (structure)
                            structures.push(structure);
                    }
                    return [4 /*yield*/, helpers_1.ModelInfo.get(model, structures)];
                case 1:
                    info = _c.sent();
                    return [2 /*return*/, info];
            }
        });
    });
}
function loadStructure(plugin, url, format, isBinary) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var data, trajectory, model, structure, e_3;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    _a.trys.push([0, 5, , 6]);
                    return [4 /*yield*/, plugin.builders.data.download({ url: assets_1.Asset.Url(url), isBinary: isBinary })];
                case 1:
                    data = _a.sent();
                    return [4 /*yield*/, plugin.builders.structure.parseTrajectory(data, format)];
                case 2:
                    trajectory = _a.sent();
                    return [4 /*yield*/, plugin.builders.structure.createModel(trajectory)];
                case 3:
                    model = _a.sent();
                    return [4 /*yield*/, plugin.builders.structure.createStructure(model, { name: 'model', params: {} })];
                case 4:
                    structure = _a.sent();
                    return [2 /*return*/, { data: data, trajectory: trajectory, model: model, structure: structure }];
                case 5:
                    e_3 = _a.sent();
                    return [2 /*return*/, { structure: void 0 }];
                case 6: return [2 /*return*/];
            }
        });
    });
}
function chainSelection(struct_asym_id) {
    return builder_1.MolScriptBuilder.struct.generator.atomGroups({
        'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_asym_id(), struct_asym_id])
    });
}
function transform(plugin, s, matrix) {
    var b = plugin.state.data.build().to(s)
        .insert(transforms_1.StateTransforms.Model.TransformStructureConformation, { transform: { name: 'matrix', params: { data: matrix, transpose: false } } });
    return plugin.runTask(plugin.state.data.updateTree(b));
}
function getMatrixData(plugin) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var customState, matrixAccession, clusterRecUrlStr, assetManager, clusterRecUrl, clusterRecData, e_4;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    customState = plugin.customState;
                    matrixAccession = customState.initParams.superpositionParams.matrixAccession ? customState.initParams.superpositionParams.matrixAccession : customState.initParams.moleculeId;
                    clusterRecUrlStr = customState.initParams.pdbeUrl + "static/superpose/matrices/" + matrixAccession;
                    assetManager = plugin.managers.asset;
                    clusterRecUrl = assets_1.Asset.getUrlAsset(assetManager, clusterRecUrlStr);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, plugin.runTask(assetManager.resolve(clusterRecUrl, 'json', false))];
                case 2:
                    clusterRecData = _a.sent();
                    if (clusterRecData && clusterRecData.data) {
                        plugin.customState.superpositionState.matrixData = clusterRecData.data;
                    }
                    return [3 /*break*/, 4];
                case 3:
                    e_4 = _a.sent();
                    customState['superpositionError'] = "Matrix data not available for " + matrixAccession;
                    plugin.customState.events.superpositionInit.next(true); // Emit segment API data load event
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function getSegmentData(plugin) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var customState, segmentsUrl, assetManager, url, result, e_5;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    customState = plugin.customState;
                    segmentsUrl = customState.initParams.pdbeUrl + "graph-api/uniprot/superposition/" + customState.initParams.moleculeId;
                    assetManager = plugin.managers.asset;
                    url = assets_1.Asset.getUrlAsset(assetManager, segmentsUrl);
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, plugin.runTask(assetManager.resolve(url, 'json', false))];
                case 2:
                    result = _a.sent();
                    if (result && result.data) {
                        customState.superpositionState.segmentData = result.data[customState.initParams.moleculeId];
                    }
                    return [3 /*break*/, 4];
                case 3:
                    e_5 = _a.sent();
                    customState['superpositionError'] = "Superposition data not available for " + customState.initParams.moleculeId;
                    plugin.customState.events.superpositionInit.next(true); // Emit segment API data load event
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/];
            }
        });
    });
}
function getChainLigands(carbEntity) {
    var ligandChain = [];
    var ligandLabels = [];
    var ligands = [];
    var labelValueArr = [];
    var ligNameStr = '';
    for (var _i = 0, _a = carbEntity.chem_comp_list; _i < _a.length; _i++) {
        var chemComp = _a[_i];
        labelValueArr.push(chemComp.chem_comp_id + " (" + chemComp.count + ")");
    }
    ligNameStr = labelValueArr.join(', ');
    for (var _b = 0, _c = carbEntity.chains; _b < _c.length; _b++) {
        var chain = _c[_b];
        ligandChain.push(chain.chain_id);
        ligandLabels.push(ligNameStr);
        var chainLigands = [];
        for (var _d = 0, _e = chain.residues; _d < _e.length; _d++) {
            var residue = _e[_d];
            chainLigands.push(residue.chem_comp_id + '-' + residue.residue_number);
        }
        ligands.push(chainLigands);
    }
    return {
        ligands: ligands,
        ligandChain: ligandChain,
        ligandLabels: ligandLabels
    };
}
function getCarbPolymerDetailsFromApi(plugin, pdb_id) {
    return tslib_1.__awaiter(this, void 0, void 0, function () {
        var customState, apiUrl, assetManager, url, branchedLigands, branchedChains, branchedlabels, result, carbEntities, _i, carbEntities_1, carbEntity, carbLigData, e_6;
        return tslib_1.__generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    customState = plugin.customState;
                    apiUrl = customState.initParams.pdbeUrl + "api/pdb/entry/carbohydrate_polymer/" + pdb_id;
                    assetManager = plugin.managers.asset;
                    url = assets_1.Asset.getUrlAsset(assetManager, apiUrl);
                    branchedLigands = [];
                    branchedChains = [];
                    branchedlabels = [];
                    _a.label = 1;
                case 1:
                    _a.trys.push([1, 3, , 4]);
                    return [4 /*yield*/, plugin.runTask(assetManager.resolve(url, 'json', false))];
                case 2:
                    result = _a.sent();
                    if (result && result.data) {
                        carbEntities = result.data[pdb_id];
                        for (_i = 0, carbEntities_1 = carbEntities; _i < carbEntities_1.length; _i++) {
                            carbEntity = carbEntities_1[_i];
                            carbLigData = getChainLigands(carbEntity);
                            branchedLigands = branchedLigands.concat(carbLigData.ligands);
                            branchedChains = branchedChains.concat(carbLigData.ligandChain);
                            branchedlabels = branchedlabels.concat(carbLigData.ligandLabels);
                        }
                    }
                    return [3 /*break*/, 4];
                case 3:
                    e_6 = _a.sent();
                    return [3 /*break*/, 4];
                case 4: return [2 /*return*/, {
                        branchedChains: branchedChains,
                        branchedLigands: branchedLigands,
                        branchedlabels: branchedlabels
                    }];
            }
        });
    });
}
//# sourceMappingURL=superposition.js.map

/***/ }),
/* 413 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports._bundleLabel = exports.bondLabel = exports.lociDetails = void 0;
var tslib_1 = __webpack_require__(0);
var structure_1 = __webpack_require__(4);
var int_1 = __webpack_require__(6);
function lociDetails(loci) {
    switch (loci.kind) {
        case 'structure-loci':
            return { models: loci.structure.models.map(function (m) { return m.entry; }).filter(function (l) { return !!l; }) };
        case 'element-loci':
            return structureElementStatsDetail(structure_1.StructureElement.Stats.ofLoci(loci));
        case 'bond-loci':
            var bond = loci.bonds[0];
            return bond ? bondLabel(bond, 'element') : '';
        default:
            return void 0;
    }
}
exports.lociDetails = lociDetails;
function structureElementStatsDetail(stats) {
    var chainCount = stats.chainCount, residueCount = stats.residueCount, elementCount = stats.elementCount;
    if (elementCount === 1 && residueCount === 0 && chainCount === 0) {
        return getElementDetails(stats.firstElementLoc, 'element');
    }
    else if (elementCount === 0 && residueCount === 1 && chainCount === 0) {
        return getElementDetails(stats.firstResidueLoc, 'residue');
    }
    else {
        return void 0;
    }
}
function getElementDetails(location, granularity) {
    if (granularity === void 0) { granularity = 'element'; }
    var basicDetails = {};
    var entry = location.unit.model.entry;
    if (entry.length > 30)
        entry = entry.substr(0, 27) + '\u2026'; // ellipsis
    basicDetails['entry_id'] = entry; // entry
    if (granularity !== 'structure') {
        basicDetails['model'] = location.unit.model.modelNum; // model
        basicDetails['instance'] = location.unit.conformation.operator.name; // instance
    }
    var elementDetails;
    if (structure_1.Unit.isAtomic(location.unit)) {
        elementDetails = atomicElementDetails(location, granularity);
    }
    else if (structure_1.Unit.isCoarse(location.unit)) {
        elementDetails = coarseElementDetails(location, granularity);
    }
    return tslib_1.__assign(tslib_1.__assign({}, basicDetails), elementDetails);
}
function atomicElementDetails(location, granularity) {
    var elementDetails = {
        entity_id: structure_1.StructureProperties.chain.label_entity_id(location),
        label_asym_id: structure_1.StructureProperties.chain.label_asym_id(location),
        auth_asym_id: structure_1.StructureProperties.chain.auth_asym_id(location),
        seq_id: structure_1.StructureProperties.residue.label_seq_id(location),
        auth_seq_id: structure_1.StructureProperties.residue.auth_seq_id(location),
        ins_code: structure_1.StructureProperties.residue.pdbx_PDB_ins_code(location),
        comp_id: structure_1.StructureProperties.atom.label_comp_id(location),
        atom_id: [structure_1.StructureProperties.atom.label_atom_id(location)],
        alt_id: structure_1.StructureProperties.atom.label_alt_id(location)
    };
    var microHetCompIds = structure_1.StructureProperties.residue.microheterogeneityCompIds(location);
    elementDetails['micro_het_comp_ids'] = granularity === 'residue' && microHetCompIds.length > 1 ?
        microHetCompIds : [elementDetails['comp_id']];
    return elementDetails;
}
function coarseElementDetails(location, granularity) {
    var elementDetails = {
        asym_id: structure_1.StructureProperties.coarse.asym_id(location),
        seq_id_begin: structure_1.StructureProperties.coarse.seq_id_begin(location),
        seq_id_end: structure_1.StructureProperties.coarse.seq_id_end(location)
    };
    if (granularity === 'residue') {
        if (elementDetails.seq_id_begin === elementDetails.seq_id_end) {
            var entityIndex = structure_1.StructureProperties.coarse.entityKey(location);
            var seq = location.unit.model.sequence.byEntityKey[entityIndex];
            elementDetails['comp_id'] = seq.sequence.compId.value(elementDetails.seq_id_begin - 1); // 1-indexed
        }
    }
    return elementDetails;
}
function bondLabel(bond, granularity) {
    return _bundleLabel({ loci: [
            structure_1.StructureElement.Loci(bond.aStructure, [{ unit: bond.aUnit, indices: int_1.OrderedSet.ofSingleton(bond.aIndex) }]),
            structure_1.StructureElement.Loci(bond.bStructure, [{ unit: bond.bUnit, indices: int_1.OrderedSet.ofSingleton(bond.bIndex) }])
        ] }, granularity);
}
exports.bondLabel = bondLabel;
function _bundleLabel(bundle, granularity) {
    var isSingleElements = true;
    for (var _i = 0, _a = bundle.loci; _i < _a.length; _i++) {
        var l = _a[_i];
        if (!structure_1.StructureElement.Loci.is(l) || structure_1.StructureElement.Loci.size(l) !== 1) {
            isSingleElements = false;
            break;
        }
    }
    if (isSingleElements) {
        var locations = bundle.loci.map(function (l) {
            var _a = l.elements[0], unit = _a.unit, indices = _a.indices;
            return structure_1.StructureElement.Location.create(l.structure, unit, unit.elements[int_1.OrderedSet.start(indices)]);
        });
        var elementDetailsArr = locations.map(function (l) { return getElementDetails(l, granularity); });
        var atomIds = [elementDetailsArr[0].atom_id[0], elementDetailsArr[1].atom_id[0]];
        var elementDetails = elementDetailsArr[0];
        elementDetails['atom_id'] = atomIds;
        return elementDetails;
    }
    else {
        var elementDetails = bundle.loci.map(function (l) { return lociDetails(l); });
        return elementDetails;
    }
}
exports._bundleLabel = _bundleLabel;
//# sourceMappingURL=loci-details.js.map

/***/ }),
/* 414 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony import */ var _coarse_conformation__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(400);
/* harmony import */ var _coarse_conformation__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_coarse_conformation__WEBPACK_IMPORTED_MODULE_0__);
/* harmony reexport (checked) */ if(__webpack_require__.o(_coarse_conformation__WEBPACK_IMPORTED_MODULE_0__, "CoarseHierarchy")) __webpack_require__.d(__webpack_exports__, "CoarseHierarchy", function() { return _coarse_conformation__WEBPACK_IMPORTED_MODULE_0__["CoarseHierarchy"]; });

/* harmony import */ var _coarse_hierarchy__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(401);
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "CoarseHierarchy", function() { return _coarse_hierarchy__WEBPACK_IMPORTED_MODULE_1__["a"]; });

/**
 * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */


//# sourceMappingURL=coarse.js.map

/***/ }),
/* 415 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return Canvas3dInteractionHelper; });
/* harmony import */ var _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(23);
/* harmony import */ var _mol_repr_representation__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(40);
/* harmony import */ var _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(84);
/* harmony import */ var _mol_util_rx_event_helper__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(180);
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var Canvas3dInteractionHelper = /** @class */ (function () {
    function Canvas3dInteractionHelper(canvasIdentify, getLoci, input, maxFps) {
        var _this = this;
        if (maxFps === void 0) { maxFps = 30; }
        this.canvasIdentify = canvasIdentify;
        this.getLoci = getLoci;
        this.maxFps = maxFps;
        this.ev = _mol_util_rx_event_helper__WEBPACK_IMPORTED_MODULE_3__["RxEventHelper"].create();
        this.events = {
            hover: this.ev(),
            click: this.ev(),
        };
        this.cX = -1;
        this.cY = -1;
        this.lastX = -1;
        this.lastY = -1;
        this.id = void 0;
        this.currentIdentifyT = 0;
        this.prevLoci = _mol_repr_representation__WEBPACK_IMPORTED_MODULE_1__[/* Representation */ "a"].Loci.Empty;
        this.prevT = 0;
        this.inside = false;
        this.buttons = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_2__[/* ButtonsType */ "a"].create(0);
        this.button = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_2__[/* ButtonsType */ "a"].create(0);
        this.modifiers = _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_2__[/* ModifiersKeys */ "b"].None;
        input.move.subscribe(function (_a) {
            var x = _a.x, y = _a.y, inside = _a.inside, buttons = _a.buttons, button = _a.button, modifiers = _a.modifiers;
            if (!inside)
                return;
            _this.move(x, y, buttons, button, modifiers);
        });
        input.leave.subscribe(function () {
            _this.leave();
        });
        input.click.subscribe(function (_a) {
            var x = _a.x, y = _a.y, buttons = _a.buttons, button = _a.button, modifiers = _a.modifiers;
            _this.select(x, y, buttons, button, modifiers);
        });
        input.modifiers.subscribe(function (modifiers) { return _this.modify(modifiers); });
    }
    Canvas3dInteractionHelper.prototype.identify = function (isClick, t) {
        if (this.lastX !== this.cX || this.lastY !== this.cY) {
            this.id = this.canvasIdentify(this.cX, this.cY);
            this.lastX = this.cX;
            this.lastY = this.cY;
        }
        if (!this.id)
            return;
        if (isClick) {
            this.events.click.next({ current: this.getLoci(this.id), buttons: this.buttons, button: this.button, modifiers: this.modifiers });
            return;
        }
        if (!this.inside || this.currentIdentifyT !== t) {
            return;
        }
        var loci = this.getLoci(this.id);
        // only broadcast the latest hover
        if (!_mol_repr_representation__WEBPACK_IMPORTED_MODULE_1__[/* Representation */ "a"].Loci.areEqual(this.prevLoci, loci)) {
            this.events.hover.next({ current: loci, buttons: this.buttons, button: this.button, modifiers: this.modifiers });
            this.prevLoci = loci;
        }
    };
    Canvas3dInteractionHelper.prototype.tick = function (t) {
        if (this.inside && t - this.prevT > 1000 / this.maxFps) {
            this.prevT = t;
            this.currentIdentifyT = t;
            this.identify(false, t);
        }
    };
    Canvas3dInteractionHelper.prototype.leave = function () {
        this.inside = false;
        if (this.prevLoci.loci !== _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["EmptyLoci"]) {
            this.prevLoci = _mol_repr_representation__WEBPACK_IMPORTED_MODULE_1__[/* Representation */ "a"].Loci.Empty;
            this.events.hover.next({ current: this.prevLoci, buttons: this.buttons, button: this.button, modifiers: this.modifiers });
        }
    };
    Canvas3dInteractionHelper.prototype.move = function (x, y, buttons, button, modifiers) {
        this.inside = true;
        this.buttons = buttons;
        this.button = button;
        this.modifiers = modifiers;
        this.cX = x;
        this.cY = y;
    };
    Canvas3dInteractionHelper.prototype.select = function (x, y, buttons, button, modifiers) {
        this.cX = x;
        this.cY = y;
        this.buttons = buttons;
        this.button = button;
        this.modifiers = modifiers;
        this.identify(true, 0);
    };
    Canvas3dInteractionHelper.prototype.modify = function (modifiers) {
        if (this.prevLoci.loci === _mol_model_loci__WEBPACK_IMPORTED_MODULE_0__["EmptyLoci"] || _mol_util_input_input_observer__WEBPACK_IMPORTED_MODULE_2__[/* ModifiersKeys */ "b"].areEqual(modifiers, this.modifiers))
            return;
        this.modifiers = modifiers;
        this.events.hover.next({ current: this.prevLoci, buttons: this.buttons, button: this.button, modifiers: this.modifiers });
    };
    Canvas3dInteractionHelper.prototype.dispose = function () {
        this.ev.dispose();
    };
    return Canvas3dInteractionHelper;
}());

//# sourceMappingURL=interaction-events.js.map

/***/ }),
/* 416 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return PickPass; });
/* harmony import */ var _mol_util_float_packing__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(217);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */

var PickPass = /** @class */ (function () {
    function PickPass(webgl, renderer, scene, camera, handleHelper, pickBaseScale) {
        this.webgl = webgl;
        this.renderer = renderer;
        this.scene = scene;
        this.camera = camera;
        this.handleHelper = handleHelper;
        this.pickBaseScale = pickBaseScale;
        this.pickDirty = true;
        var gl = webgl.gl;
        var width = gl.drawingBufferWidth;
        var height = gl.drawingBufferHeight;
        this.pickScale = pickBaseScale / webgl.pixelRatio;
        this.pickWidth = Math.round(width * this.pickScale);
        this.pickHeight = Math.round(height * this.pickScale);
        this.objectPickTarget = webgl.createRenderTarget(this.pickWidth, this.pickHeight);
        this.instancePickTarget = webgl.createRenderTarget(this.pickWidth, this.pickHeight);
        this.groupPickTarget = webgl.createRenderTarget(this.pickWidth, this.pickHeight);
        this.setupBuffers();
    }
    PickPass.prototype.setupBuffers = function () {
        var bufferSize = this.pickWidth * this.pickHeight * 4;
        if (!this.objectBuffer || this.objectBuffer.length !== bufferSize) {
            this.objectBuffer = new Uint8Array(bufferSize);
            this.instanceBuffer = new Uint8Array(bufferSize);
            this.groupBuffer = new Uint8Array(bufferSize);
        }
    };
    PickPass.prototype.setSize = function (width, height) {
        this.pickScale = this.pickBaseScale / this.webgl.pixelRatio;
        this.pickWidth = Math.round(width * this.pickScale);
        this.pickHeight = Math.round(height * this.pickScale);
        this.objectPickTarget.setSize(this.pickWidth, this.pickHeight);
        this.instancePickTarget.setSize(this.pickWidth, this.pickHeight);
        this.groupPickTarget.setSize(this.pickWidth, this.pickHeight);
        this.setupBuffers();
    };
    PickPass.prototype.render = function () {
        var _a = this, renderer = _a.renderer, scene = _a.scene, camera = _a.camera, handleScene = _a.handleHelper.scene;
        renderer.setViewport(0, 0, this.pickWidth, this.pickHeight);
        this.objectPickTarget.bind();
        renderer.render(scene, camera, 'pickObject', true, false);
        renderer.render(handleScene, camera, 'pickObject', false, false);
        this.instancePickTarget.bind();
        renderer.render(scene, camera, 'pickInstance', true, false);
        renderer.render(handleScene, camera, 'pickInstance', false, false);
        this.groupPickTarget.bind();
        renderer.render(scene, camera, 'pickGroup', true, false);
        renderer.render(handleScene, camera, 'pickGroup', false, false);
        this.pickDirty = false;
    };
    PickPass.prototype.syncBuffers = function () {
        var webgl = this.webgl;
        this.objectPickTarget.bind();
        webgl.readPixels(0, 0, this.pickWidth, this.pickHeight, this.objectBuffer);
        this.instancePickTarget.bind();
        webgl.readPixels(0, 0, this.pickWidth, this.pickHeight, this.instanceBuffer);
        this.groupPickTarget.bind();
        webgl.readPixels(0, 0, this.pickWidth, this.pickHeight, this.groupBuffer);
    };
    PickPass.prototype.getId = function (x, y, buffer) {
        var idx = (y * this.pickWidth + x) * 4;
        return Object(_mol_util_float_packing__WEBPACK_IMPORTED_MODULE_0__[/* decodeFloatRGB */ "b"])(buffer[idx], buffer[idx + 1], buffer[idx + 2]);
    };
    PickPass.prototype.identify = function (x, y) {
        var _a = this, webgl = _a.webgl, pickScale = _a.pickScale;
        if (webgl.isContextLost)
            return;
        var gl = webgl.gl;
        if (this.pickDirty) {
            this.render();
            this.syncBuffers();
        }
        x *= webgl.pixelRatio;
        y *= webgl.pixelRatio;
        y = gl.drawingBufferHeight - y; // flip y
        var xp = Math.round(x * pickScale);
        var yp = Math.round(y * pickScale);
        var objectId = this.getId(xp, yp, this.objectBuffer);
        if (objectId === -1)
            return;
        var instanceId = this.getId(xp, yp, this.instanceBuffer);
        if (instanceId === -1)
            return;
        var groupId = this.getId(xp, yp, this.groupBuffer);
        if (groupId === -1)
            return;
        return { objectId: objectId, instanceId: instanceId, groupId: groupId };
    };
    return PickPass;
}());

//# sourceMappingURL=pick.js.map

/***/ }),
/* 417 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
/* unused harmony export ImageParams */
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return ImagePass; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(2);
/* harmony import */ var _draw__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(331);
/* harmony import */ var _postprocessing__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(318);
/* harmony import */ var _multi_sample__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(319);
/* harmony import */ var _camera__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(232);
/* harmony import */ var _camera_util__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(176);
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var ImageParams = {
    transparentBackground: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Boolean(false),
    multiSample: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Group(_multi_sample__WEBPACK_IMPORTED_MODULE_4__[/* MultiSampleParams */ "a"]),
    postprocessing: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Group(_postprocessing__WEBPACK_IMPORTED_MODULE_3__[/* PostprocessingParams */ "a"]),
    drawPass: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].Group(_draw__WEBPACK_IMPORTED_MODULE_2__[/* DrawPassParams */ "b"]),
};
var ImagePass = /** @class */ (function () {
    function ImagePass(webgl, renderer, scene, camera, debugHelper, handleHelper, props) {
        this.renderer = renderer;
        this.camera = camera;
        this._width = 1024;
        this._height = 768;
        this._camera = new _camera__WEBPACK_IMPORTED_MODULE_5__[/* Camera */ "a"]();
        this._transparentBackground = false;
        var p = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_1__["ParamDefinition"].getDefaultValues(ImageParams)), props);
        this._transparentBackground = p.transparentBackground;
        this.drawPass = new _draw__WEBPACK_IMPORTED_MODULE_2__[/* DrawPass */ "a"](webgl, renderer, scene, this._camera, debugHelper, handleHelper, p.drawPass);
        this.postprocessing = new _postprocessing__WEBPACK_IMPORTED_MODULE_3__[/* PostprocessingPass */ "b"](webgl, this._camera, this.drawPass, p.postprocessing);
        this.multiSample = new _multi_sample__WEBPACK_IMPORTED_MODULE_4__[/* MultiSamplePass */ "b"](webgl, this._camera, this.drawPass, this.postprocessing, p.multiSample);
        this.setSize(this._width, this._height);
    }
    Object.defineProperty(ImagePass.prototype, "colorTarget", {
        get: function () { return this._colorTarget; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ImagePass.prototype, "width", {
        get: function () { return this._width; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ImagePass.prototype, "height", {
        get: function () { return this._height; },
        enumerable: false,
        configurable: true
    });
    ImagePass.prototype.setSize = function (width, height) {
        if (width === this._width && height === this._height)
            return;
        this._width = width;
        this._height = height;
        this.drawPass.setSize(width, height);
        this.postprocessing.setSize(width, height);
        this.multiSample.setSize(width, height);
    };
    ImagePass.prototype.setProps = function (props) {
        if (props === void 0) { props = {}; }
        if (props.transparentBackground !== undefined)
            this._transparentBackground = props.transparentBackground;
        if (props.postprocessing)
            this.postprocessing.setProps(props.postprocessing);
        if (props.multiSample)
            this.multiSample.setProps(props.multiSample);
        if (props.drawPass)
            this.drawPass.setProps(props.drawPass);
    };
    Object.defineProperty(ImagePass.prototype, "props", {
        get: function () {
            return {
                transparentBackground: this._transparentBackground,
                postprocessing: this.postprocessing.props,
                multiSample: this.multiSample.props,
                drawPass: this.drawPass.props
            };
        },
        enumerable: false,
        configurable: true
    });
    ImagePass.prototype.render = function () {
        _camera__WEBPACK_IMPORTED_MODULE_5__[/* Camera */ "a"].copySnapshot(this._camera.state, this.camera.state);
        _camera_util__WEBPACK_IMPORTED_MODULE_6__[/* Viewport */ "a"].set(this._camera.viewport, 0, 0, this._width, this._height);
        this._camera.update();
        this.renderer.setViewport(0, 0, this._width, this._height);
        if (this.multiSample.enabled) {
            this.multiSample.render(false, this._transparentBackground);
            this._colorTarget = this.multiSample.colorTarget;
        }
        else {
            this.drawPass.render(false, this._transparentBackground);
            if (this.postprocessing.enabled) {
                this.postprocessing.render(false);
                this._colorTarget = this.postprocessing.target;
            }
            else {
                this._colorTarget = this.drawPass.colorTarget;
            }
        }
    };
    ImagePass.prototype.getImageData = function (width, height) {
        this.setSize(width, height);
        this.render();
        var pd = this.colorTarget.getPixelData();
        return new ImageData(new Uint8ClampedArray(pd.array), pd.width, pd.height);
    };
    return ImagePass;
}());

//# sourceMappingURL=image.js.map

/***/ }),
/* 418 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
var tslib_1 = __webpack_require__(0);
var spec_1 = __webpack_require__(419);
var commands_1 = __webpack_require__(26);
var mol_state_1 = __webpack_require__(13);
var loci_1 = __webpack_require__(23);
var rx_event_helper_1 = __webpack_require__(180);
var helpers_1 = __webpack_require__(405);
var pdbe_structure_controls_1 = __webpack_require__(434);
var pdbe_viewport_controls_1 = __webpack_require__(438);
var mol_state_2 = __webpack_require__(13);
var structure_focus_representation_1 = __webpack_require__(320);
var spec_2 = __webpack_require__(404);
var transformers_1 = __webpack_require__(300);
var structure_representation_params_1 = __webpack_require__(162);
var subscribe_events_1 = __webpack_require__(440);
var pdbe_left_panel_1 = __webpack_require__(441);
var superposition_1 = __webpack_require__(412);
var custom_events_1 = __webpack_require__(443);
var assets_1 = __webpack_require__(114);
var config_1 = __webpack_require__(101);
var color_1 = __webpack_require__(43);
var component_1 = __webpack_require__(246);
var param_definition_1 = __webpack_require__(2);
var behavior_1 = __webpack_require__(408);
var pdbe_1 = __webpack_require__(449);
var built_in_1 = __webpack_require__(450);
var structure_overpaint_1 = __webpack_require__(368);
var element_symbol_1 = __webpack_require__(307);
var superposition_focus_representation_1 = __webpack_require__(444);
var superposition_viewport_1 = __webpack_require__(445);
var behavior_2 = __webpack_require__(409);
// import { AFConfidenceComponentControls } from './ui/af-confidence-controls'
__webpack_require__(446);
// Override carbon by chain-id theme default
element_symbol_1.ElementSymbolColorThemeParams.carbonByChainId.defaultValue = false;
var PDBeMolstarPlugin = /** @class */ (function () {
    function PDBeMolstarPlugin() {
        var _this = this;
        this._ev = rx_event_helper_1.RxEventHelper.create();
        this.events = {
            loadComplete: this._ev()
        };
        this.assemblyRef = '';
        this.isHighlightColorUpdated = false;
        this.isSelectedColorUpdated = false;
        this.applyVisualParams = function () {
            var TagRefs = {
                'structure-component-static-polymer': 'polymer',
                'structure-component-static-ligand': 'het',
                'structure-component-static-branched': 'carbs',
                'structure-component-static-water': 'water',
                'structure-component-static-coarse': 'coarse',
                'non-standard': 'nonStandard'
            };
            var componentGroups = _this.plugin.managers.structure.hierarchy.currentComponentGroups;
            componentGroups.forEach(function (compGrp) {
                var _a;
                var key = compGrp[0].key;
                var rm = false;
                if (key && _this.initParams.hideStructure) {
                    var structType = TagRefs[key];
                    if (structType && ((_a = _this.initParams.hideStructure) === null || _a === void 0 ? void 0 : _a.indexOf(structType)) > -1)
                        rm = true;
                }
                if (rm) {
                    _this.plugin.managers.structure.hierarchy.remove(compGrp);
                }
                if (!rm && _this.initParams.visualStyle) {
                    if (compGrp[0] && compGrp[0].representations) {
                        compGrp[0].representations.forEach(function (rep) {
                            var currentParams = structure_representation_params_1.createStructureRepresentationParams(_this.plugin, void 0, { type: _this.initParams.visualStyle });
                            _this.plugin.managers.structure.component.updateRepresentations(compGrp, rep, currentParams);
                        });
                    }
                }
            });
        };
        this.canvas = {
            toggleControls: function (isVisible) {
                if (typeof isVisible === 'undefined')
                    isVisible = !_this.plugin.layout.state.showControls;
                commands_1.PluginCommands.Layout.Update(_this.plugin, { state: { showControls: isVisible } });
            },
            toggleExpanded: function (isExpanded) {
                if (typeof isExpanded === 'undefined')
                    isExpanded = !_this.plugin.layout.state.isExpanded;
                commands_1.PluginCommands.Layout.Update(_this.plugin, { state: { isExpanded: isExpanded } });
            },
            setBgColor: function (color) {
                if (!color)
                    return;
                var renderer = _this.plugin.canvas3d.props.renderer;
                commands_1.PluginCommands.Canvas3D.SetSettings(_this.plugin, { settings: { renderer: tslib_1.__assign(tslib_1.__assign({}, renderer), { backgroundColor: color_1.Color.fromRgb(color.r, color.g, color.b) }) } });
            },
        };
        this.visual = {
            highlight: function (params) {
                var loci = _this.getLociForParams(params.data);
                if (loci_1.Loci.isEmpty(loci))
                    return;
                if (params.color) {
                    _this.visual.setColor({ highlight: params.color });
                }
                _this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci: loci });
                if (params.focus)
                    _this.plugin.managers.camera.focusLoci(loci);
            },
            clearHighlight: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                return tslib_1.__generator(this, function (_a) {
                    this.plugin.managers.interactivity.lociHighlights.highlightOnly({ loci: loci_1.EmptyLoci });
                    if (this.isHighlightColorUpdated)
                        this.visual.reset({ highlightColor: true });
                    return [2 /*return*/];
                });
            }); },
            select: function (params) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var _a, _b, s, e_1_1, _c, _d, param, loci, themeParams, colorValue, repr, defaultParams, defaultValues, values, structures, comps, lastCompsIndex, recentRepComp, uniformColor, e_2_1;
                var e_1, _e, e_2, _f;
                return tslib_1.__generator(this, function (_g) {
                    switch (_g.label) {
                        case 0:
                            if (!this.selectedParams) return [3 /*break*/, 2];
                            return [4 /*yield*/, this.visual.clearSelection()];
                        case 1:
                            _g.sent();
                            _g.label = 2;
                        case 2:
                            if (!params.nonSelectedColor) return [3 /*break*/, 15];
                            _g.label = 3;
                        case 3:
                            _g.trys.push([3, 9, 10, 15]);
                            _a = tslib_1.__asyncValues(this.plugin.managers.structure.hierarchy.current.structures);
                            _g.label = 4;
                        case 4: return [4 /*yield*/, _a.next()];
                        case 5:
                            if (!(_b = _g.sent(), !_b.done)) return [3 /*break*/, 8];
                            s = _b.value;
                            return [4 /*yield*/, this.plugin.managers.structure.component.updateRepresentationsTheme(s.components, { color: 'uniform', colorParams: { value: this.normalizeColor(params.nonSelectedColor) } })];
                        case 6:
                            _g.sent();
                            _g.label = 7;
                        case 7: return [3 /*break*/, 4];
                        case 8: return [3 /*break*/, 15];
                        case 9:
                            e_1_1 = _g.sent();
                            e_1 = { error: e_1_1 };
                            return [3 /*break*/, 15];
                        case 10:
                            _g.trys.push([10, , 13, 14]);
                            if (!(_b && !_b.done && (_e = _a.return))) return [3 /*break*/, 12];
                            return [4 /*yield*/, _e.call(_a)];
                        case 11:
                            _g.sent();
                            _g.label = 12;
                        case 12: return [3 /*break*/, 14];
                        case 13:
                            if (e_1) throw e_1.error;
                            return [7 /*endfinally*/];
                        case 14: return [7 /*endfinally*/];
                        case 15:
                            _g.trys.push([15, 23, 24, 29]);
                            _c = tslib_1.__asyncValues(params.data);
                            _g.label = 16;
                        case 16: return [4 /*yield*/, _c.next()];
                        case 17:
                            if (!(_d = _g.sent(), !_d.done)) return [3 /*break*/, 22];
                            param = _d.value;
                            loci = this.getLociForParams([param]);
                            if (loci_1.Loci.isEmpty(loci))
                                return [2 /*return*/];
                            // set default selection color to minimise change display
                            this.visual.setColor({ select: param.color ? param.color : { r: 255, g: 112, b: 3 } });
                            // apply selection
                            this.plugin.managers.interactivity.lociSelects.selectOnly({ loci: loci });
                            themeParams = component_1.StructureComponentManager.getThemeParams(this.plugin, this.plugin.managers.structure.component.pivotStructure);
                            colorValue = param_definition_1.ParamDefinition.getDefaultValues(themeParams);
                            colorValue.action.params = { color: param.color ? this.normalizeColor(param.color) : color_1.Color.fromRgb(255, 112, 3), opacity: 1 };
                            return [4 /*yield*/, this.plugin.managers.structure.component.applyTheme(colorValue, this.plugin.managers.structure.hierarchy.current.structures)];
                        case 18:
                            _g.sent();
                            if (!(param.sideChain || param.representation)) return [3 /*break*/, 20];
                            repr = 'ball-and-stick';
                            if (param.representation)
                                repr = param.representation;
                            defaultParams = component_1.StructureComponentManager.getAddParams(this.plugin, { allowNone: false, hideSelection: true, checkExisting: true });
                            defaultValues = param_definition_1.ParamDefinition.getDefaultValues(defaultParams);
                            defaultValues.options = { label: 'selection-by-script', checkExisting: true };
                            values = tslib_1.__assign(tslib_1.__assign({}, defaultValues), { representation: repr });
                            structures = this.plugin.managers.structure.hierarchy.getStructuresWithSelection();
                            return [4 /*yield*/, this.plugin.managers.structure.component.add(values, structures)];
                        case 19:
                            _g.sent();
                            // Apply uniform theme
                            if (param.representationColor) {
                                comps = this.plugin.managers.structure.hierarchy.current.structures[0].components;
                                lastCompsIndex = comps.length - 1;
                                recentRepComp = [comps[lastCompsIndex]];
                                uniformColor = param.representationColor ? this.normalizeColor(param.representationColor) : color_1.Color.fromRgb(255, 112, 3);
                                this.plugin.managers.structure.component.updateRepresentationsTheme(recentRepComp, { color: 'uniform', colorParams: { value: uniformColor } });
                            }
                            params.addedRepr = true;
                            _g.label = 20;
                        case 20:
                            // focus loci
                            if (param.focus)
                                this.plugin.managers.camera.focusLoci(loci);
                            // remove selection
                            this.plugin.managers.interactivity.lociSelects.deselect({ loci: loci });
                            _g.label = 21;
                        case 21: return [3 /*break*/, 16];
                        case 22: return [3 /*break*/, 29];
                        case 23:
                            e_2_1 = _g.sent();
                            e_2 = { error: e_2_1 };
                            return [3 /*break*/, 29];
                        case 24:
                            _g.trys.push([24, , 27, 28]);
                            if (!(_d && !_d.done && (_f = _c.return))) return [3 /*break*/, 26];
                            return [4 /*yield*/, _f.call(_c)];
                        case 25:
                            _g.sent();
                            _g.label = 26;
                        case 26: return [3 /*break*/, 28];
                        case 27:
                            if (e_2) throw e_2.error;
                            return [7 /*endfinally*/];
                        case 28: return [7 /*endfinally*/];
                        case 29:
                            // reset selection color
                            this.visual.reset({ selectColor: true });
                            // save selection params to optimise clear
                            this.selectedParams = params;
                            return [2 /*return*/];
                    }
                });
            }); },
            clearSelection: function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var selReprCells, _i, _a, c, selReprCells_1, selReprCells_1_1, selReprCell, e_3_1;
                var e_3, _b;
                return tslib_1.__generator(this, function (_c) {
                    switch (_c.label) {
                        case 0:
                            this.plugin.managers.interactivity.lociSelects.deselectAll();
                            // reset theme to default
                            if (this.selectedParams && this.selectedParams.nonSelectedColor) {
                                this.visual.reset({ theme: true });
                            }
                            // remove overpaints
                            return [4 /*yield*/, structure_overpaint_1.clearStructureOverpaint(this.plugin, this.plugin.managers.structure.hierarchy.current.structures[0].components)];
                        case 1:
                            // remove overpaints
                            _c.sent();
                            if (!(this.selectedParams && this.selectedParams.addedRepr)) return [3 /*break*/, 15];
                            selReprCells = [];
                            for (_i = 0, _a = this.plugin.managers.structure.hierarchy.current.structures[0].components; _i < _a.length; _i++) {
                                c = _a[_i];
                                if (c.cell && c.cell.params && c.cell.params.values && c.cell.params.values.label === 'selection-by-script')
                                    selReprCells.push(c.cell);
                            }
                            if (!(selReprCells.length > 0)) return [3 /*break*/, 15];
                            _c.label = 2;
                        case 2:
                            _c.trys.push([2, 8, 9, 14]);
                            selReprCells_1 = tslib_1.__asyncValues(selReprCells);
                            _c.label = 3;
                        case 3: return [4 /*yield*/, selReprCells_1.next()];
                        case 4:
                            if (!(selReprCells_1_1 = _c.sent(), !selReprCells_1_1.done)) return [3 /*break*/, 7];
                            selReprCell = selReprCells_1_1.value;
                            return [4 /*yield*/, commands_1.PluginCommands.State.RemoveObject(this.plugin, { state: selReprCell.parent, ref: selReprCell.transform.ref })];
                        case 5:
                            _c.sent();
                            _c.label = 6;
                        case 6: return [3 /*break*/, 3];
                        case 7: return [3 /*break*/, 14];
                        case 8:
                            e_3_1 = _c.sent();
                            e_3 = { error: e_3_1 };
                            return [3 /*break*/, 14];
                        case 9:
                            _c.trys.push([9, , 12, 13]);
                            if (!(selReprCells_1_1 && !selReprCells_1_1.done && (_b = selReprCells_1.return))) return [3 /*break*/, 11];
                            return [4 /*yield*/, _b.call(selReprCells_1)];
                        case 10:
                            _c.sent();
                            _c.label = 11;
                        case 11: return [3 /*break*/, 13];
                        case 12:
                            if (e_3) throw e_3.error;
                            return [7 /*endfinally*/];
                        case 13: return [7 /*endfinally*/];
                        case 14:
                            ;
                            _c.label = 15;
                        case 15:
                            this.selectedParams = undefined;
                            return [2 /*return*/];
                    }
                });
            }); },
            update: function (options, fullLoad) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var param, dataSource;
                return tslib_1.__generator(this, function (_a) {
                    if (!options)
                        return [2 /*return*/];
                    // for(let param in this.initParams){
                    //     if(options[param]) this.initParams[param] = options[param];
                    // }
                    this.initParams = tslib_1.__assign({}, spec_1.DefaultParams);
                    for (param in spec_1.DefaultParams) {
                        if (typeof options[param] !== 'undefined')
                            this.initParams[param] = options[param];
                    }
                    if (!this.initParams.moleculeId && !this.initParams.customData)
                        return [2 /*return*/, false];
                    if (this.initParams.customData && this.initParams.customData.url && !this.initParams.customData.format)
                        return [2 /*return*/, false];
                    this.plugin.customState.initParams = this.initParams;
                    // Set background colour
                    if (this.initParams.bgColor) {
                        this.canvas.setBgColor(this.initParams.bgColor);
                    }
                    dataSource = this.getMoleculeSrcUrl();
                    if (dataSource) {
                        this.load({ url: dataSource.url, format: dataSource.format, assemblyId: this.initParams.assemblyId, isBinary: dataSource.isBinary }, fullLoad);
                    }
                    return [2 /*return*/];
                });
            }); },
            visibility: function (data) {
                if (!data)
                    return;
                var refMap = {
                    polymer: 'structure-component-static-polymer',
                    het: 'structure-component-static-ligand',
                    water: 'structure-component-static-water',
                    carbs: 'structure-component-static-branched',
                    maps: 'volume-streaming-info'
                };
                for (var visual in data) {
                    var tagName = refMap[visual];
                    var componentRef = mol_state_2.StateSelection.findTagInSubtree(_this.plugin.state.data.tree, mol_state_1.StateTransform.RootRef, tagName);
                    if (componentRef) {
                        var compVisual = _this.plugin.state.data.select(componentRef)[0];
                        if (compVisual && compVisual.obj) {
                            var currentlyVisible = (compVisual.state && compVisual.state.isHidden) ? false : true;
                            if (data[visual] !== currentlyVisible) {
                                commands_1.PluginCommands.State.ToggleVisibility(_this.plugin, { state: _this.state, ref: componentRef });
                            }
                        }
                    }
                }
            },
            toggleSpin: function (isSpinning, resetCamera) {
                if (!_this.plugin.canvas3d)
                    return;
                var trackball = _this.plugin.canvas3d.props.trackball;
                if (typeof isSpinning === 'undefined')
                    isSpinning = !trackball.spin;
                commands_1.PluginCommands.Canvas3D.SetSettings(_this.plugin, { settings: { trackball: tslib_1.__assign(tslib_1.__assign({}, trackball), { spin: isSpinning }) } });
                if (resetCamera)
                    commands_1.PluginCommands.Camera.Reset(_this.plugin, {});
            },
            focus: function (params) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var loci;
                return tslib_1.__generator(this, function (_a) {
                    loci = this.getLociForParams(params);
                    this.plugin.managers.camera.focusLoci(loci);
                    return [2 /*return*/];
                });
            }); },
            setColor: function (param) {
                if (!_this.plugin.canvas3d)
                    return;
                var renderer = _this.plugin.canvas3d.props.renderer;
                var rParam = {};
                if (param.highlight)
                    rParam['highlightColor'] = _this.normalizeColor(param.highlight);
                if (param.select)
                    rParam['selectColor'] = _this.normalizeColor(param.select);
                commands_1.PluginCommands.Canvas3D.SetSettings(_this.plugin, { settings: { renderer: tslib_1.__assign(tslib_1.__assign({}, renderer), rParam) } });
                if (rParam.highlightColor)
                    _this.isHighlightColorUpdated = true;
            },
            reset: function (params) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var defaultTheme_1, componentGroups, renderer, rParam;
                var _this = this;
                return tslib_1.__generator(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            if (!params.camera) return [3 /*break*/, 2];
                            return [4 /*yield*/, commands_1.PluginCommands.Camera.Reset(this.plugin, { durationMs: 250 })];
                        case 1:
                            _a.sent();
                            _a.label = 2;
                        case 2:
                            if (params.theme) {
                                defaultTheme_1 = { color: this.initParams.isAfView ? 'af-confidence' : 'default' };
                                componentGroups = this.plugin.managers.structure.hierarchy.currentComponentGroups;
                                componentGroups.forEach(function (compGrp) {
                                    _this.plugin.managers.structure.component.updateRepresentationsTheme(compGrp, defaultTheme_1);
                                });
                            }
                            if (params.highlightColor || params.selectColor) {
                                if (!this.plugin.canvas3d)
                                    return [2 /*return*/];
                                renderer = this.plugin.canvas3d.props.renderer;
                                rParam = {};
                                if (params.highlightColor)
                                    rParam['highlightColor'] = this.defaultRendererProps.highlightColor;
                                if (params.selectColor)
                                    rParam['selectColor'] = this.defaultRendererProps.selectColor;
                                commands_1.PluginCommands.Canvas3D.SetSettings(this.plugin, { settings: { renderer: tslib_1.__assign(tslib_1.__assign({}, renderer), rParam) } });
                                if (rParam.highlightColor)
                                    this.isHighlightColorUpdated = false;
                            }
                            return [2 /*return*/];
                    }
                });
            }); }
        };
    }
    PDBeMolstarPlugin.prototype.render = function (target, options) {
        if (!options)
            return;
        this.initParams = tslib_1.__assign({}, spec_1.DefaultParams);
        for (var param in spec_1.DefaultParams) {
            if (typeof options[param] !== 'undefined')
                this.initParams[param] = options[param];
        }
        if (!this.initParams.moleculeId && !this.initParams.customData)
            return false;
        if (this.initParams.customData && this.initParams.customData.url && !this.initParams.customData.format)
            return false;
        // Set PDBe Plugin Spec
        var pdbePluginSpec = {
            actions: tslib_1.__spreadArrays(spec_1.DefaultPluginSpec.actions),
            behaviors: tslib_1.__spreadArrays(spec_1.DefaultPluginSpec.behaviors),
            animations: tslib_1.__spreadArrays(spec_1.DefaultPluginSpec.animations || []),
            customParamEditors: spec_1.DefaultPluginSpec.customParamEditors,
            config: spec_1.DefaultPluginSpec.config
        };
        if (!this.initParams.ligandView && !this.initParams.superposition && this.initParams.selectInteraction) {
            pdbePluginSpec.behaviors.push(spec_2.PluginSpec.Behavior(structure_focus_representation_1.StructureFocusRepresentation));
        }
        if (this.initParams.superposition) {
            var displaySurroundings = true;
            // if(this.initParams.superpositionParams && this.initParams.superpositionParams.ligandView) displaySurroundings = false;
            if (displaySurroundings)
                pdbePluginSpec.behaviors.push(spec_2.PluginSpec.Behavior(superposition_focus_representation_1.SuperpositionFocusRepresentation));
        }
        // Add custom properties
        if (this.initParams.domainAnnotation) {
            pdbePluginSpec.behaviors.push(spec_2.PluginSpec.Behavior(behavior_1.PDBeDomainAnnotations, { autoAttach: true, showTooltip: false }));
        }
        if (this.initParams.validationAnnotation) {
            pdbePluginSpec.behaviors.push(spec_2.PluginSpec.Behavior(pdbe_1.PDBeStructureQualityReport, { autoAttach: true, showTooltip: false }));
        }
        pdbePluginSpec.layout = {
            initial: {
                isExpanded: this.initParams.landscape ? false : this.initParams.expanded,
                showControls: !this.initParams.hideControls
            },
            controls: {
                left: pdbe_left_panel_1.LeftPanelControls,
                // right: DefaultStructureTools,
                top: 'none',
                bottom: 'none'
            },
        };
        if (this.initParams.isAfView) {
            pdbePluginSpec.behaviors.push(spec_2.PluginSpec.Behavior(behavior_2.AfConfidenceScore, { autoAttach: true, showTooltip: true }));
            pdbePluginSpec.layout.controls = {
                left: 'none',
                right: 'none',
                // top: 'none',
                bottom: 'none'
            };
        }
        pdbePluginSpec.components = {
            viewport: {
                controls: pdbe_viewport_controls_1.PDBeViewportControls,
                view: this.initParams.superposition ? superposition_viewport_1.SuperpostionViewport : void 0
            },
            remoteState: 'none',
            structureTools: this.initParams.superposition ? pdbe_structure_controls_1.PDBeSuperpositionStructureTools : this.initParams.ligandView ? pdbe_structure_controls_1.PDBeLigandViewStructureTools : this.initParams.isAfView ? pdbe_structure_controls_1.PDBeAfViewStructureTools : pdbe_structure_controls_1.PDBeStructureTools
        };
        pdbePluginSpec.config = [
            [config_1.PluginConfig.Structure.DefaultRepresentationPresetParams, { theme: { globalName: (this.initParams.isAfView) ? 'af-confidence' : undefined, carbonByChainId: false, focus: { name: 'element-symbol', params: { carbonByChainId: false } } } }]
        ];
        // Add animation props
        if (!this.initParams.ligandView && !this.initParams.superposition) {
            pdbePluginSpec['animations'] = [built_in_1.AnimateModelIndex];
        }
        if (this.initParams.hideCanvasControls) {
            // let hideCanvasControls: any = [];
            if (this.initParams.hideCanvasControls.indexOf('expand') > -1)
                pdbePluginSpec.config.push([config_1.PluginConfig.Viewport.ShowExpand, false]);
            if (this.initParams.hideCanvasControls.indexOf('selection') > -1)
                pdbePluginSpec.config.push([config_1.PluginConfig.Viewport.ShowSelectionMode, false]);
            if (this.initParams.hideCanvasControls.indexOf('animation') > -1)
                pdbePluginSpec.config.push([config_1.PluginConfig.Viewport.ShowAnimation, false]);
            // pdbePluginSpec.config = hideCanvasControls;
        }
        ;
        if (this.initParams.landscape && pdbePluginSpec.layout && pdbePluginSpec.layout.initial)
            pdbePluginSpec.layout.initial['controlsDisplay'] = 'landscape';
        this.targetElement = typeof target === 'string' ? document.getElementById(target) : target;
        // Create/ Initialise Plugin
        this.plugin = spec_1.createPlugin(this.targetElement, pdbePluginSpec);
        this.plugin.customState.initParams = tslib_1.__assign({}, this.initParams);
        this.plugin.customState.events = {
            segmentUpdate: this._ev(),
            superpositionInit: this._ev(),
            isBusy: this._ev()
        };
        // Set background colour
        if (this.initParams.bgColor) {
            this.canvas.setBgColor(this.initParams.bgColor);
        }
        // Set selection granularity
        if (this.initParams.granularity) {
            this.plugin.managers.interactivity.setProps({ granularity: this.initParams.granularity });
        }
        // Set default highlight and selection colors
        if (this.initParams.highlightColor || this.initParams.selectColor) {
            this.visual.setColor({ highlight: this.initParams.highlightColor, select: this.initParams.selectColor });
        }
        // Save renderer defaults
        this.defaultRendererProps = tslib_1.__assign({}, this.plugin.canvas3d.props.renderer);
        if (this.initParams.superposition) {
            // Set left panel tab
            this.plugin.behaviors.layout.leftPanelTabName.next('segments');
            // Initialise superposition
            superposition_1.initSuperposition(this.plugin);
        }
        else {
            // Collapse left panel and set left panel tab to none
            commands_1.PluginCommands.Layout.Update(this.plugin, { state: { regionState: tslib_1.__assign(tslib_1.__assign({}, this.plugin.layout.state.regionState), { left: 'collapsed' }) } });
            this.plugin.behaviors.layout.leftPanelTabName.next('none');
            // Load Molecule CIF or coordQuery and Parse
            var dataSource = this.getMoleculeSrcUrl();
            if (dataSource) {
                this.load({ url: dataSource.url, format: dataSource.format, assemblyId: this.initParams.assemblyId, isBinary: dataSource.isBinary });
            }
            // Binding to other PDB Component events
            if (this.initParams.subscribeEvents) {
                subscribe_events_1.subscribeToComponentEvents(this);
            }
            // Event handling
            custom_events_1.CustomEvents.add(this.plugin, this.targetElement);
        }
    };
    PDBeMolstarPlugin.prototype.getMoleculeSrcUrl = function () {
        var supportedFormats = ['mmcif', 'pdb', 'sdf'];
        var id = this.initParams.moleculeId;
        if (!id && !this.initParams.customData) {
            throw new Error("Mandatory parameters missing!");
        }
        var query = 'full';
        var sep = '?';
        if (this.initParams.ligandView) {
            var queryParams = ['data_source=pdb-h'];
            if (!this.initParams.ligandView.label_comp_id_list) {
                if (this.initParams.ligandView.label_comp_id) {
                    queryParams.push('label_comp_id=' + this.initParams.ligandView.label_comp_id);
                }
                else if (this.initParams.ligandView.auth_seq_id) {
                    queryParams.push('auth_seq_id=' + this.initParams.ligandView.auth_seq_id);
                }
                if (this.initParams.ligandView.auth_asym_id)
                    queryParams.push('auth_asym_id=' + this.initParams.ligandView.auth_asym_id);
            }
            query = 'residueSurroundings?' + queryParams.join('&');
            sep = '&';
        }
        var url = this.initParams.pdbeUrl + "model-server/v1/" + id + "/" + query + sep + "encoding=" + this.initParams.encoding + (this.initParams.lowPrecisionCoords ? '&lowPrecisionCoords=1' : '');
        var isBinary = this.initParams.encoding === 'bcif' ? true : false;
        var format = 'mmcif';
        if (this.initParams.customData) {
            if (!this.initParams.customData.url || !this.initParams.customData.format) {
                throw new Error("Provide all custom data parameters");
            }
            url = this.initParams.customData.url;
            format = this.initParams.customData.format;
            if (format === 'cif' || format === 'bcif')
                format = 'mmcif';
            // Validate supported format
            if (supportedFormats.indexOf(format) === -1) {
                throw new Error(format + " not supported.");
            }
            isBinary = this.initParams.customData.binary ? this.initParams.customData.binary : false;
        }
        return {
            url: url,
            format: format,
            isBinary: isBinary
        };
    };
    Object.defineProperty(PDBeMolstarPlugin.prototype, "state", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    PDBeMolstarPlugin.prototype.createLigandStructure = function (isBranched) {
        var e_4, _a;
        var _b;
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var _c, _d, comp, e_4_1, structure, ligandQuery, ligandVis, ligandSurr, ligRef, cell, ligLoci;
            var _this = this;
            return tslib_1.__generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        if (this.assemblyRef === '')
                            return [2 /*return*/];
                        _e.label = 1;
                    case 1:
                        _e.trys.push([1, 7, 8, 13]);
                        _c = tslib_1.__asyncValues(this.plugin.managers.structure.hierarchy.currentComponentGroups);
                        _e.label = 2;
                    case 2: return [4 /*yield*/, _c.next()];
                    case 3:
                        if (!(_d = _e.sent(), !_d.done)) return [3 /*break*/, 6];
                        comp = _d.value;
                        return [4 /*yield*/, commands_1.PluginCommands.State.RemoveObject(this.plugin, { state: comp[0].cell.parent, ref: comp[0].cell.transform.ref, removeParentGhosts: true })];
                    case 4:
                        _e.sent();
                        _e.label = 5;
                    case 5: return [3 /*break*/, 2];
                    case 6: return [3 /*break*/, 13];
                    case 7:
                        e_4_1 = _e.sent();
                        e_4 = { error: e_4_1 };
                        return [3 /*break*/, 13];
                    case 8:
                        _e.trys.push([8, , 11, 12]);
                        if (!(_d && !_d.done && (_a = _c.return))) return [3 /*break*/, 10];
                        return [4 /*yield*/, _a.call(_c)];
                    case 9:
                        _e.sent();
                        _e.label = 10;
                    case 10: return [3 /*break*/, 12];
                    case 11:
                        if (e_4) throw e_4.error;
                        return [7 /*endfinally*/];
                    case 12: return [7 /*endfinally*/];
                    case 13:
                        structure = this.state.select(this.assemblyRef)[0];
                        if (isBranched) {
                            ligandQuery = helpers_1.LigandView.branchedQuery((_b = this.initParams.ligandView) === null || _b === void 0 ? void 0 : _b.label_comp_id_list);
                        }
                        else {
                            ligandQuery = helpers_1.LigandView.query(this.initParams.ligandView);
                        }
                        return [4 /*yield*/, this.plugin.builders.structure.tryCreateComponentFromExpression(structure, ligandQuery.core, 'pivot', { label: 'Ligand' })];
                    case 14:
                        ligandVis = _e.sent();
                        if (!ligandVis) return [3 /*break*/, 16];
                        return [4 /*yield*/, this.plugin.builders.structure.representation.addRepresentation(ligandVis, { type: 'ball-and-stick', color: 'element-symbol', colorParams: { carbonByChainId: false }, size: 'uniform', sizeParams: { value: 2.5 } }, { tag: 'ligand-vis' })];
                    case 15:
                        _e.sent();
                        _e.label = 16;
                    case 16: return [4 /*yield*/, this.plugin.builders.structure.tryCreateComponentFromExpression(structure, ligandQuery.surroundings, 'rest', { label: 'Surroundings' })];
                    case 17:
                        ligandSurr = _e.sent();
                        if (!ligandSurr) return [3 /*break*/, 19];
                        return [4 /*yield*/, this.plugin.builders.structure.representation.addRepresentation(ligandSurr, { type: 'ball-and-stick', color: 'element-symbol', colorParams: { carbonByChainId: false }, size: 'uniform', sizeParams: { value: 0.8 } })];
                    case 18:
                        _e.sent();
                        _e.label = 19;
                    case 19:
                        ligRef = mol_state_2.StateSelection.findTagInSubtree(this.plugin.state.data.tree, mol_state_1.StateTransform.RootRef, 'ligand-vis');
                        if (!ligRef)
                            return [2 /*return*/];
                        cell = this.plugin.state.data.cells.get(ligRef);
                        if (cell) {
                            ligLoci = cell.obj.data.repr.getLoci();
                            this.plugin.managers.structure.focus.setFromLoci(ligLoci);
                            setTimeout(function () {
                                var _a;
                                // focus-add is not handled in camera behavior, doing it here
                                var current = (_a = _this.plugin.managers.structure.focus.current) === null || _a === void 0 ? void 0 : _a.loci;
                                if (current)
                                    _this.plugin.managers.camera.focusLoci(current);
                            }, 500);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    PDBeMolstarPlugin.prototype.load = function (_a, fullLoad) {
        var url = _a.url, _b = _a.format, format = _b === void 0 ? 'mmcif' : _b, _c = _a.isBinary, isBinary = _c === void 0 ? false : _c, _d = _a.assemblyId, assemblyId = _d === void 0 ? '' : _d;
        if (fullLoad === void 0) { fullLoad = true; }
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var isHetView, downloadOptions, isBranchedView, data, trajectory, model, pivotIndex, pivot, asm, defaultMapParams, pdbeMapParams;
            return tslib_1.__generator(this, function (_e) {
                switch (_e.label) {
                    case 0:
                        if (fullLoad)
                            this.clear();
                        isHetView = this.initParams.ligandView ? true : false;
                        downloadOptions = void 0;
                        isBranchedView = false;
                        if (this.initParams.ligandView && this.initParams.ligandView.label_comp_id_list) {
                            isBranchedView = true;
                            downloadOptions = { body: JSON.stringify(this.initParams.ligandView.label_comp_id_list), headers: [['Content-type', 'application/json']] };
                        }
                        return [4 /*yield*/, this.plugin.builders.data.download({ url: assets_1.Asset.Url(url, downloadOptions), isBinary: isBinary }, { state: { isGhost: true } })];
                    case 1:
                        data = _e.sent();
                        return [4 /*yield*/, this.plugin.builders.structure.parseTrajectory(data, format)];
                    case 2:
                        trajectory = _e.sent();
                        if (!!isHetView) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.plugin.builders.structure.hierarchy.applyPreset(trajectory, 'default', {
                                structure: assemblyId ? (assemblyId === 'preferred') ? void 0 : { name: 'assembly', params: { id: assemblyId } } : { name: 'model', params: {} },
                                showUnitcell: false,
                                representationPreset: 'auto'
                            })];
                    case 3:
                        _e.sent();
                        if (this.initParams.hideStructure || this.initParams.visualStyle) {
                            this.applyVisualParams();
                        }
                        return [3 /*break*/, 7];
                    case 4: return [4 /*yield*/, this.plugin.builders.structure.createModel(trajectory)];
                    case 5:
                        model = _e.sent();
                        return [4 /*yield*/, this.plugin.builders.structure.createStructure(model, { name: 'model', params: {} })];
                    case 6:
                        _e.sent();
                        _e.label = 7;
                    case 7:
                        // show selection if param is set
                        if (this.initParams.selection) {
                            this.visual.select(this.initParams.selection);
                        }
                        pivotIndex = this.plugin.managers.structure.hierarchy.selection.structures.length - 1;
                        pivot = this.plugin.managers.structure.hierarchy.selection.structures[pivotIndex];
                        if (pivot && pivot.cell.parent)
                            this.assemblyRef = pivot.cell.transform.ref;
                        if (!this.initParams.loadMaps) return [3 /*break*/, 9];
                        if (this.assemblyRef === '')
                            return [2 /*return*/];
                        asm = this.state.select(this.assemblyRef)[0].obj;
                        defaultMapParams = transformers_1.InitVolumeStreaming.createDefaultParams(asm, this.plugin);
                        pdbeMapParams = helpers_1.PDBeVolumes.mapParams(defaultMapParams, this.initParams.mapSettings, '');
                        if (!pdbeMapParams) return [3 /*break*/, 9];
                        return [4 /*yield*/, this.plugin.runTask(this.state.applyAction(transformers_1.InitVolumeStreaming, pdbeMapParams, this.assemblyRef))];
                    case 8:
                        _e.sent();
                        if (pdbeMapParams.method !== 'em' && !this.initParams.ligandView)
                            helpers_1.PDBeVolumes.displayUsibilityMessage(this.plugin);
                        _e.label = 9;
                    case 9:
                        if (!isHetView) return [3 /*break*/, 11];
                        return [4 /*yield*/, this.createLigandStructure(isBranchedView)];
                    case 10:
                        _e.sent();
                        _e.label = 11;
                    case 11:
                        this.events.loadComplete.next(true);
                        return [2 /*return*/];
                }
            });
        });
    };
    PDBeMolstarPlugin.prototype.getLociForParams = function (params) {
        if (this.assemblyRef === '')
            return loci_1.EmptyLoci;
        var data = this.plugin.state.data.select(this.assemblyRef)[0].obj.data;
        if (!data)
            return loci_1.EmptyLoci;
        return helpers_1.QueryHelper.getInteractivityLoci(params, data);
    };
    PDBeMolstarPlugin.prototype.normalizeColor = function (colorVal, defaultColor) {
        var color = color_1.Color.fromRgb(170, 170, 170);
        try {
            if (colorVal.r) {
                color = color_1.Color.fromRgb(colorVal.r, colorVal.g, colorVal.b);
            }
            else if (colorVal[0] === '#') {
                color = color_1.Color(Number("0x" + colorVal.substr(1)));
            }
            else {
                color = color_1.Color(colorVal);
            }
        }
        catch (e) {
            if (defaultColor)
                color = defaultColor;
        }
        return color;
    };
    PDBeMolstarPlugin.prototype.clear = function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            return tslib_1.__generator(this, function (_a) {
                this.plugin.clear();
                this.assemblyRef = '';
                this.selectedParams = void 0;
                this.isHighlightColorUpdated = false;
                this.isSelectedColorUpdated = false;
                return [2 /*return*/];
            });
        });
    };
    return PDBeMolstarPlugin;
}());
window.PDBeMolstarPlugin = PDBeMolstarPlugin;
//# sourceMappingURL=index.js.map

/***/ }),
/* 419 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.DefaultParams = exports.createPlugin = exports.DefaultPluginSpec = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var ReactDOM = tslib_1.__importStar(__webpack_require__(421));
var volume_1 = __webpack_require__(425);
var plugin_1 = __webpack_require__(448);
var behavior_1 = __webpack_require__(170);
var transformers_1 = __webpack_require__(300);
var context_1 = __webpack_require__(447);
var spec_1 = __webpack_require__(404);
var config_1 = __webpack_require__(101);
var labels_1 = __webpack_require__(433);
exports.DefaultPluginSpec = {
    actions: [],
    behaviors: [
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.Representation.HighlightLoci),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.Representation.SelectLoci),
        spec_1.PluginSpec.Behavior(labels_1.PDBeLociLabelProvider),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.Representation.FocusLoci),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.Camera.FocusLoci),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.CustomProps.AccessibleSurfaceArea),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.CustomProps.Interactions),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.CustomProps.SecondaryStructure),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.CustomProps.ValenceModel),
        spec_1.PluginSpec.Behavior(behavior_1.PluginBehaviors.CustomProps.CrossLinkRestraint)
    ],
    customParamEditors: [
        [transformers_1.CreateVolumeStreamingBehavior, volume_1.VolumeStreamingCustomControls]
    ],
    // animations: [],
    config: [
        [config_1.PluginConfig.VolumeStreaming.DefaultServer, 'https://www.ebi.ac.uk/pdbe/densities']
    ]
};
function createPlugin(target, spec) {
    var ctx = new context_1.PluginContext(spec || exports.DefaultPluginSpec);
    ReactDOM.render(React.createElement(plugin_1.Plugin, { plugin: ctx }), target);
    return ctx;
}
exports.createPlugin = createPlugin;
exports.DefaultParams = {
    moleculeId: undefined,
    superposition: undefined,
    superpositionParams: undefined,
    customData: undefined,
    ligandView: undefined,
    assemblyId: undefined,
    visualStyle: undefined,
    highlightColor: undefined,
    selectColor: undefined,
    hideStructure: undefined,
    hideCanvasControls: undefined,
    granularity: undefined,
    selection: undefined,
    mapSettings: undefined,
    pdbeUrl: 'https://www.ebi.ac.uk/pdbe/',
    bgColor: { r: 0, g: 0, b: 0 },
    encoding: 'bcif',
    selectInteraction: true,
    loadMaps: false,
    validationAnnotation: false,
    domainAnnotation: false,
    lowPrecisionCoords: false,
    expanded: false,
    hideControls: false,
    pdbeLink: true,
    loadCartoonsOnly: false,
    landscape: false,
    subscribeEvents: false,
    isAfView: false
};
//# sourceMappingURL=spec.js.map

/***/ }),
/* 420 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.13.1
 * react.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var l=__webpack_require__(397),n="function"===typeof Symbol&&Symbol.for,p=n?Symbol.for("react.element"):60103,q=n?Symbol.for("react.portal"):60106,r=n?Symbol.for("react.fragment"):60107,t=n?Symbol.for("react.strict_mode"):60108,u=n?Symbol.for("react.profiler"):60114,v=n?Symbol.for("react.provider"):60109,w=n?Symbol.for("react.context"):60110,x=n?Symbol.for("react.forward_ref"):60112,y=n?Symbol.for("react.suspense"):60113,z=n?Symbol.for("react.memo"):60115,A=n?Symbol.for("react.lazy"):
60116,B="function"===typeof Symbol&&Symbol.iterator;function C(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}
var D={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},E={};function F(a,b,c){this.props=a;this.context=b;this.refs=E;this.updater=c||D}F.prototype.isReactComponent={};F.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error(C(85));this.updater.enqueueSetState(this,a,b,"setState")};F.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate")};
function G(){}G.prototype=F.prototype;function H(a,b,c){this.props=a;this.context=b;this.refs=E;this.updater=c||D}var I=H.prototype=new G;I.constructor=H;l(I,F.prototype);I.isPureReactComponent=!0;var J={current:null},K=Object.prototype.hasOwnProperty,L={key:!0,ref:!0,__self:!0,__source:!0};
function M(a,b,c){var e,d={},g=null,k=null;if(null!=b)for(e in void 0!==b.ref&&(k=b.ref),void 0!==b.key&&(g=""+b.key),b)K.call(b,e)&&!L.hasOwnProperty(e)&&(d[e]=b[e]);var f=arguments.length-2;if(1===f)d.children=c;else if(1<f){for(var h=Array(f),m=0;m<f;m++)h[m]=arguments[m+2];d.children=h}if(a&&a.defaultProps)for(e in f=a.defaultProps,f)void 0===d[e]&&(d[e]=f[e]);return{$$typeof:p,type:a,key:g,ref:k,props:d,_owner:J.current}}
function N(a,b){return{$$typeof:p,type:a.type,key:b,ref:a.ref,props:a.props,_owner:a._owner}}function O(a){return"object"===typeof a&&null!==a&&a.$$typeof===p}function escape(a){var b={"=":"=0",":":"=2"};return"$"+(""+a).replace(/[=:]/g,function(a){return b[a]})}var P=/\/+/g,Q=[];function R(a,b,c,e){if(Q.length){var d=Q.pop();d.result=a;d.keyPrefix=b;d.func=c;d.context=e;d.count=0;return d}return{result:a,keyPrefix:b,func:c,context:e,count:0}}
function S(a){a.result=null;a.keyPrefix=null;a.func=null;a.context=null;a.count=0;10>Q.length&&Q.push(a)}
function T(a,b,c,e){var d=typeof a;if("undefined"===d||"boolean"===d)a=null;var g=!1;if(null===a)g=!0;else switch(d){case "string":case "number":g=!0;break;case "object":switch(a.$$typeof){case p:case q:g=!0}}if(g)return c(e,a,""===b?"."+U(a,0):b),1;g=0;b=""===b?".":b+":";if(Array.isArray(a))for(var k=0;k<a.length;k++){d=a[k];var f=b+U(d,k);g+=T(d,f,c,e)}else if(null===a||"object"!==typeof a?f=null:(f=B&&a[B]||a["@@iterator"],f="function"===typeof f?f:null),"function"===typeof f)for(a=f.call(a),k=
0;!(d=a.next()).done;)d=d.value,f=b+U(d,k++),g+=T(d,f,c,e);else if("object"===d)throw c=""+a,Error(C(31,"[object Object]"===c?"object with keys {"+Object.keys(a).join(", ")+"}":c,""));return g}function V(a,b,c){return null==a?0:T(a,"",b,c)}function U(a,b){return"object"===typeof a&&null!==a&&null!=a.key?escape(a.key):b.toString(36)}function W(a,b){a.func.call(a.context,b,a.count++)}
function aa(a,b,c){var e=a.result,d=a.keyPrefix;a=a.func.call(a.context,b,a.count++);Array.isArray(a)?X(a,e,c,function(a){return a}):null!=a&&(O(a)&&(a=N(a,d+(!a.key||b&&b.key===a.key?"":(""+a.key).replace(P,"$&/")+"/")+c)),e.push(a))}function X(a,b,c,e,d){var g="";null!=c&&(g=(""+c).replace(P,"$&/")+"/");b=R(b,g,e,d);V(a,aa,b);S(b)}var Y={current:null};function Z(){var a=Y.current;if(null===a)throw Error(C(321));return a}
var ba={ReactCurrentDispatcher:Y,ReactCurrentBatchConfig:{suspense:null},ReactCurrentOwner:J,IsSomeRendererActing:{current:!1},assign:l};exports.Children={map:function(a,b,c){if(null==a)return a;var e=[];X(a,e,null,b,c);return e},forEach:function(a,b,c){if(null==a)return a;b=R(null,null,b,c);V(a,W,b);S(b)},count:function(a){return V(a,function(){return null},null)},toArray:function(a){var b=[];X(a,b,null,function(a){return a});return b},only:function(a){if(!O(a))throw Error(C(143));return a}};
exports.Component=F;exports.Fragment=r;exports.Profiler=u;exports.PureComponent=H;exports.StrictMode=t;exports.Suspense=y;exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=ba;
exports.cloneElement=function(a,b,c){if(null===a||void 0===a)throw Error(C(267,a));var e=l({},a.props),d=a.key,g=a.ref,k=a._owner;if(null!=b){void 0!==b.ref&&(g=b.ref,k=J.current);void 0!==b.key&&(d=""+b.key);if(a.type&&a.type.defaultProps)var f=a.type.defaultProps;for(h in b)K.call(b,h)&&!L.hasOwnProperty(h)&&(e[h]=void 0===b[h]&&void 0!==f?f[h]:b[h])}var h=arguments.length-2;if(1===h)e.children=c;else if(1<h){f=Array(h);for(var m=0;m<h;m++)f[m]=arguments[m+2];e.children=f}return{$$typeof:p,type:a.type,
key:d,ref:g,props:e,_owner:k}};exports.createContext=function(a,b){void 0===b&&(b=null);a={$$typeof:w,_calculateChangedBits:b,_currentValue:a,_currentValue2:a,_threadCount:0,Provider:null,Consumer:null};a.Provider={$$typeof:v,_context:a};return a.Consumer=a};exports.createElement=M;exports.createFactory=function(a){var b=M.bind(null,a);b.type=a;return b};exports.createRef=function(){return{current:null}};exports.forwardRef=function(a){return{$$typeof:x,render:a}};exports.isValidElement=O;
exports.lazy=function(a){return{$$typeof:A,_ctor:a,_status:-1,_result:null}};exports.memo=function(a,b){return{$$typeof:z,type:a,compare:void 0===b?null:b}};exports.useCallback=function(a,b){return Z().useCallback(a,b)};exports.useContext=function(a,b){return Z().useContext(a,b)};exports.useDebugValue=function(){};exports.useEffect=function(a,b){return Z().useEffect(a,b)};exports.useImperativeHandle=function(a,b,c){return Z().useImperativeHandle(a,b,c)};
exports.useLayoutEffect=function(a,b){return Z().useLayoutEffect(a,b)};exports.useMemo=function(a,b){return Z().useMemo(a,b)};exports.useReducer=function(a,b,c){return Z().useReducer(a,b,c)};exports.useRef=function(a){return Z().useRef(a)};exports.useState=function(a){return Z().useState(a)};exports.version="16.13.1";


/***/ }),
/* 421 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


function checkDCE() {
  /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */
  if (
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined' ||
    typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE !== 'function'
  ) {
    return;
  }
  if (false) {}
  try {
    // Verify that the code above has been dead code eliminated (DCE'd).
    __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(checkDCE);
  } catch (err) {
    // DevTools shouldn't crash React, no matter what.
    // We should still report in case we break this code.
    console.error(err);
  }
}

if (true) {
  // DCE check should happen before ReactDOM bundle executes so that
  // DevTools can report bad minification during injection.
  checkDCE();
  module.exports = __webpack_require__(422);
} else {}


/***/ }),
/* 422 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v16.13.1
 * react-dom.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

/*
 Modernizr 3.0.0pre (Custom Build) | MIT
*/
var aa=__webpack_require__(3),n=__webpack_require__(397),r=__webpack_require__(423);function u(a){for(var b="https://reactjs.org/docs/error-decoder.html?invariant="+a,c=1;c<arguments.length;c++)b+="&args[]="+encodeURIComponent(arguments[c]);return"Minified React error #"+a+"; visit "+b+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}if(!aa)throw Error(u(227));
function ba(a,b,c,d,e,f,g,h,k){var l=Array.prototype.slice.call(arguments,3);try{b.apply(c,l)}catch(m){this.onError(m)}}var da=!1,ea=null,fa=!1,ha=null,ia={onError:function(a){da=!0;ea=a}};function ja(a,b,c,d,e,f,g,h,k){da=!1;ea=null;ba.apply(ia,arguments)}function ka(a,b,c,d,e,f,g,h,k){ja.apply(this,arguments);if(da){if(da){var l=ea;da=!1;ea=null}else throw Error(u(198));fa||(fa=!0,ha=l)}}var la=null,ma=null,na=null;
function oa(a,b,c){var d=a.type||"unknown-event";a.currentTarget=na(c);ka(d,b,void 0,a);a.currentTarget=null}var pa=null,qa={};
function ra(){if(pa)for(var a in qa){var b=qa[a],c=pa.indexOf(a);if(!(-1<c))throw Error(u(96,a));if(!sa[c]){if(!b.extractEvents)throw Error(u(97,a));sa[c]=b;c=b.eventTypes;for(var d in c){var e=void 0;var f=c[d],g=b,h=d;if(ta.hasOwnProperty(h))throw Error(u(99,h));ta[h]=f;var k=f.phasedRegistrationNames;if(k){for(e in k)k.hasOwnProperty(e)&&ua(k[e],g,h);e=!0}else f.registrationName?(ua(f.registrationName,g,h),e=!0):e=!1;if(!e)throw Error(u(98,d,a));}}}}
function ua(a,b,c){if(va[a])throw Error(u(100,a));va[a]=b;wa[a]=b.eventTypes[c].dependencies}var sa=[],ta={},va={},wa={};function xa(a){var b=!1,c;for(c in a)if(a.hasOwnProperty(c)){var d=a[c];if(!qa.hasOwnProperty(c)||qa[c]!==d){if(qa[c])throw Error(u(102,c));qa[c]=d;b=!0}}b&&ra()}var ya=!("undefined"===typeof window||"undefined"===typeof window.document||"undefined"===typeof window.document.createElement),za=null,Aa=null,Ba=null;
function Ca(a){if(a=ma(a)){if("function"!==typeof za)throw Error(u(280));var b=a.stateNode;b&&(b=la(b),za(a.stateNode,a.type,b))}}function Da(a){Aa?Ba?Ba.push(a):Ba=[a]:Aa=a}function Ea(){if(Aa){var a=Aa,b=Ba;Ba=Aa=null;Ca(a);if(b)for(a=0;a<b.length;a++)Ca(b[a])}}function Fa(a,b){return a(b)}function Ga(a,b,c,d,e){return a(b,c,d,e)}function Ha(){}var Ia=Fa,Ja=!1,Ka=!1;function La(){if(null!==Aa||null!==Ba)Ha(),Ea()}
function Ma(a,b,c){if(Ka)return a(b,c);Ka=!0;try{return Ia(a,b,c)}finally{Ka=!1,La()}}var Na=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Oa=Object.prototype.hasOwnProperty,Pa={},Qa={};
function Ra(a){if(Oa.call(Qa,a))return!0;if(Oa.call(Pa,a))return!1;if(Na.test(a))return Qa[a]=!0;Pa[a]=!0;return!1}function Sa(a,b,c,d){if(null!==c&&0===c.type)return!1;switch(typeof b){case "function":case "symbol":return!0;case "boolean":if(d)return!1;if(null!==c)return!c.acceptsBooleans;a=a.toLowerCase().slice(0,5);return"data-"!==a&&"aria-"!==a;default:return!1}}
function Ta(a,b,c,d){if(null===b||"undefined"===typeof b||Sa(a,b,c,d))return!0;if(d)return!1;if(null!==c)switch(c.type){case 3:return!b;case 4:return!1===b;case 5:return isNaN(b);case 6:return isNaN(b)||1>b}return!1}function v(a,b,c,d,e,f){this.acceptsBooleans=2===b||3===b||4===b;this.attributeName=d;this.attributeNamespace=e;this.mustUseProperty=c;this.propertyName=a;this.type=b;this.sanitizeURL=f}var C={};
"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(a){C[a]=new v(a,0,!1,a,null,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(a){var b=a[0];C[b]=new v(b,1,!1,a[1],null,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(a){C[a]=new v(a,2,!1,a.toLowerCase(),null,!1)});
["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(a){C[a]=new v(a,2,!1,a,null,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(a){C[a]=new v(a,3,!1,a.toLowerCase(),null,!1)});
["checked","multiple","muted","selected"].forEach(function(a){C[a]=new v(a,3,!0,a,null,!1)});["capture","download"].forEach(function(a){C[a]=new v(a,4,!1,a,null,!1)});["cols","rows","size","span"].forEach(function(a){C[a]=new v(a,6,!1,a,null,!1)});["rowSpan","start"].forEach(function(a){C[a]=new v(a,5,!1,a.toLowerCase(),null,!1)});var Ua=/[\-:]([a-z])/g;function Va(a){return a[1].toUpperCase()}
"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(a){var b=a.replace(Ua,
Va);C[b]=new v(b,1,!1,a,null,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/1999/xlink",!1)});["xml:base","xml:lang","xml:space"].forEach(function(a){var b=a.replace(Ua,Va);C[b]=new v(b,1,!1,a,"http://www.w3.org/XML/1998/namespace",!1)});["tabIndex","crossOrigin"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!1)});
C.xlinkHref=new v("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0);["src","href","action","formAction"].forEach(function(a){C[a]=new v(a,1,!1,a.toLowerCase(),null,!0)});var Wa=aa.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;Wa.hasOwnProperty("ReactCurrentDispatcher")||(Wa.ReactCurrentDispatcher={current:null});Wa.hasOwnProperty("ReactCurrentBatchConfig")||(Wa.ReactCurrentBatchConfig={suspense:null});
function Xa(a,b,c,d){var e=C.hasOwnProperty(b)?C[b]:null;var f=null!==e?0===e.type:d?!1:!(2<b.length)||"o"!==b[0]&&"O"!==b[0]||"n"!==b[1]&&"N"!==b[1]?!1:!0;f||(Ta(b,c,e,d)&&(c=null),d||null===e?Ra(b)&&(null===c?a.removeAttribute(b):a.setAttribute(b,""+c)):e.mustUseProperty?a[e.propertyName]=null===c?3===e.type?!1:"":c:(b=e.attributeName,d=e.attributeNamespace,null===c?a.removeAttribute(b):(e=e.type,c=3===e||4===e&&!0===c?"":""+c,d?a.setAttributeNS(d,b,c):a.setAttribute(b,c))))}
var Ya=/^(.*)[\\\/]/,E="function"===typeof Symbol&&Symbol.for,Za=E?Symbol.for("react.element"):60103,$a=E?Symbol.for("react.portal"):60106,ab=E?Symbol.for("react.fragment"):60107,bb=E?Symbol.for("react.strict_mode"):60108,cb=E?Symbol.for("react.profiler"):60114,db=E?Symbol.for("react.provider"):60109,eb=E?Symbol.for("react.context"):60110,fb=E?Symbol.for("react.concurrent_mode"):60111,gb=E?Symbol.for("react.forward_ref"):60112,hb=E?Symbol.for("react.suspense"):60113,ib=E?Symbol.for("react.suspense_list"):
60120,jb=E?Symbol.for("react.memo"):60115,kb=E?Symbol.for("react.lazy"):60116,lb=E?Symbol.for("react.block"):60121,mb="function"===typeof Symbol&&Symbol.iterator;function nb(a){if(null===a||"object"!==typeof a)return null;a=mb&&a[mb]||a["@@iterator"];return"function"===typeof a?a:null}function ob(a){if(-1===a._status){a._status=0;var b=a._ctor;b=b();a._result=b;b.then(function(b){0===a._status&&(b=b.default,a._status=1,a._result=b)},function(b){0===a._status&&(a._status=2,a._result=b)})}}
function pb(a){if(null==a)return null;if("function"===typeof a)return a.displayName||a.name||null;if("string"===typeof a)return a;switch(a){case ab:return"Fragment";case $a:return"Portal";case cb:return"Profiler";case bb:return"StrictMode";case hb:return"Suspense";case ib:return"SuspenseList"}if("object"===typeof a)switch(a.$$typeof){case eb:return"Context.Consumer";case db:return"Context.Provider";case gb:var b=a.render;b=b.displayName||b.name||"";return a.displayName||(""!==b?"ForwardRef("+b+")":
"ForwardRef");case jb:return pb(a.type);case lb:return pb(a.render);case kb:if(a=1===a._status?a._result:null)return pb(a)}return null}function qb(a){var b="";do{a:switch(a.tag){case 3:case 4:case 6:case 7:case 10:case 9:var c="";break a;default:var d=a._debugOwner,e=a._debugSource,f=pb(a.type);c=null;d&&(c=pb(d.type));d=f;f="";e?f=" (at "+e.fileName.replace(Ya,"")+":"+e.lineNumber+")":c&&(f=" (created by "+c+")");c="\n    in "+(d||"Unknown")+f}b+=c;a=a.return}while(a);return b}
function rb(a){switch(typeof a){case "boolean":case "number":case "object":case "string":case "undefined":return a;default:return""}}function sb(a){var b=a.type;return(a=a.nodeName)&&"input"===a.toLowerCase()&&("checkbox"===b||"radio"===b)}
function tb(a){var b=sb(a)?"checked":"value",c=Object.getOwnPropertyDescriptor(a.constructor.prototype,b),d=""+a[b];if(!a.hasOwnProperty(b)&&"undefined"!==typeof c&&"function"===typeof c.get&&"function"===typeof c.set){var e=c.get,f=c.set;Object.defineProperty(a,b,{configurable:!0,get:function(){return e.call(this)},set:function(a){d=""+a;f.call(this,a)}});Object.defineProperty(a,b,{enumerable:c.enumerable});return{getValue:function(){return d},setValue:function(a){d=""+a},stopTracking:function(){a._valueTracker=
null;delete a[b]}}}}function xb(a){a._valueTracker||(a._valueTracker=tb(a))}function yb(a){if(!a)return!1;var b=a._valueTracker;if(!b)return!0;var c=b.getValue();var d="";a&&(d=sb(a)?a.checked?"true":"false":a.value);a=d;return a!==c?(b.setValue(a),!0):!1}function zb(a,b){var c=b.checked;return n({},b,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=c?c:a._wrapperState.initialChecked})}
function Ab(a,b){var c=null==b.defaultValue?"":b.defaultValue,d=null!=b.checked?b.checked:b.defaultChecked;c=rb(null!=b.value?b.value:c);a._wrapperState={initialChecked:d,initialValue:c,controlled:"checkbox"===b.type||"radio"===b.type?null!=b.checked:null!=b.value}}function Bb(a,b){b=b.checked;null!=b&&Xa(a,"checked",b,!1)}
function Cb(a,b){Bb(a,b);var c=rb(b.value),d=b.type;if(null!=c)if("number"===d){if(0===c&&""===a.value||a.value!=c)a.value=""+c}else a.value!==""+c&&(a.value=""+c);else if("submit"===d||"reset"===d){a.removeAttribute("value");return}b.hasOwnProperty("value")?Db(a,b.type,c):b.hasOwnProperty("defaultValue")&&Db(a,b.type,rb(b.defaultValue));null==b.checked&&null!=b.defaultChecked&&(a.defaultChecked=!!b.defaultChecked)}
function Eb(a,b,c){if(b.hasOwnProperty("value")||b.hasOwnProperty("defaultValue")){var d=b.type;if(!("submit"!==d&&"reset"!==d||void 0!==b.value&&null!==b.value))return;b=""+a._wrapperState.initialValue;c||b===a.value||(a.value=b);a.defaultValue=b}c=a.name;""!==c&&(a.name="");a.defaultChecked=!!a._wrapperState.initialChecked;""!==c&&(a.name=c)}
function Db(a,b,c){if("number"!==b||a.ownerDocument.activeElement!==a)null==c?a.defaultValue=""+a._wrapperState.initialValue:a.defaultValue!==""+c&&(a.defaultValue=""+c)}function Fb(a){var b="";aa.Children.forEach(a,function(a){null!=a&&(b+=a)});return b}function Gb(a,b){a=n({children:void 0},b);if(b=Fb(b.children))a.children=b;return a}
function Hb(a,b,c,d){a=a.options;if(b){b={};for(var e=0;e<c.length;e++)b["$"+c[e]]=!0;for(c=0;c<a.length;c++)e=b.hasOwnProperty("$"+a[c].value),a[c].selected!==e&&(a[c].selected=e),e&&d&&(a[c].defaultSelected=!0)}else{c=""+rb(c);b=null;for(e=0;e<a.length;e++){if(a[e].value===c){a[e].selected=!0;d&&(a[e].defaultSelected=!0);return}null!==b||a[e].disabled||(b=a[e])}null!==b&&(b.selected=!0)}}
function Ib(a,b){if(null!=b.dangerouslySetInnerHTML)throw Error(u(91));return n({},b,{value:void 0,defaultValue:void 0,children:""+a._wrapperState.initialValue})}function Jb(a,b){var c=b.value;if(null==c){c=b.children;b=b.defaultValue;if(null!=c){if(null!=b)throw Error(u(92));if(Array.isArray(c)){if(!(1>=c.length))throw Error(u(93));c=c[0]}b=c}null==b&&(b="");c=b}a._wrapperState={initialValue:rb(c)}}
function Kb(a,b){var c=rb(b.value),d=rb(b.defaultValue);null!=c&&(c=""+c,c!==a.value&&(a.value=c),null==b.defaultValue&&a.defaultValue!==c&&(a.defaultValue=c));null!=d&&(a.defaultValue=""+d)}function Lb(a){var b=a.textContent;b===a._wrapperState.initialValue&&""!==b&&null!==b&&(a.value=b)}var Mb={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};
function Nb(a){switch(a){case "svg":return"http://www.w3.org/2000/svg";case "math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function Ob(a,b){return null==a||"http://www.w3.org/1999/xhtml"===a?Nb(b):"http://www.w3.org/2000/svg"===a&&"foreignObject"===b?"http://www.w3.org/1999/xhtml":a}
var Pb,Qb=function(a){return"undefined"!==typeof MSApp&&MSApp.execUnsafeLocalFunction?function(b,c,d,e){MSApp.execUnsafeLocalFunction(function(){return a(b,c,d,e)})}:a}(function(a,b){if(a.namespaceURI!==Mb.svg||"innerHTML"in a)a.innerHTML=b;else{Pb=Pb||document.createElement("div");Pb.innerHTML="<svg>"+b.valueOf().toString()+"</svg>";for(b=Pb.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;b.firstChild;)a.appendChild(b.firstChild)}});
function Rb(a,b){if(b){var c=a.firstChild;if(c&&c===a.lastChild&&3===c.nodeType){c.nodeValue=b;return}}a.textContent=b}function Sb(a,b){var c={};c[a.toLowerCase()]=b.toLowerCase();c["Webkit"+a]="webkit"+b;c["Moz"+a]="moz"+b;return c}var Tb={animationend:Sb("Animation","AnimationEnd"),animationiteration:Sb("Animation","AnimationIteration"),animationstart:Sb("Animation","AnimationStart"),transitionend:Sb("Transition","TransitionEnd")},Ub={},Vb={};
ya&&(Vb=document.createElement("div").style,"AnimationEvent"in window||(delete Tb.animationend.animation,delete Tb.animationiteration.animation,delete Tb.animationstart.animation),"TransitionEvent"in window||delete Tb.transitionend.transition);function Wb(a){if(Ub[a])return Ub[a];if(!Tb[a])return a;var b=Tb[a],c;for(c in b)if(b.hasOwnProperty(c)&&c in Vb)return Ub[a]=b[c];return a}
var Xb=Wb("animationend"),Yb=Wb("animationiteration"),Zb=Wb("animationstart"),$b=Wb("transitionend"),ac="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),bc=new ("function"===typeof WeakMap?WeakMap:Map);function cc(a){var b=bc.get(a);void 0===b&&(b=new Map,bc.set(a,b));return b}
function dc(a){var b=a,c=a;if(a.alternate)for(;b.return;)b=b.return;else{a=b;do b=a,0!==(b.effectTag&1026)&&(c=b.return),a=b.return;while(a)}return 3===b.tag?c:null}function ec(a){if(13===a.tag){var b=a.memoizedState;null===b&&(a=a.alternate,null!==a&&(b=a.memoizedState));if(null!==b)return b.dehydrated}return null}function fc(a){if(dc(a)!==a)throw Error(u(188));}
function gc(a){var b=a.alternate;if(!b){b=dc(a);if(null===b)throw Error(u(188));return b!==a?null:a}for(var c=a,d=b;;){var e=c.return;if(null===e)break;var f=e.alternate;if(null===f){d=e.return;if(null!==d){c=d;continue}break}if(e.child===f.child){for(f=e.child;f;){if(f===c)return fc(e),a;if(f===d)return fc(e),b;f=f.sibling}throw Error(u(188));}if(c.return!==d.return)c=e,d=f;else{for(var g=!1,h=e.child;h;){if(h===c){g=!0;c=e;d=f;break}if(h===d){g=!0;d=e;c=f;break}h=h.sibling}if(!g){for(h=f.child;h;){if(h===
c){g=!0;c=f;d=e;break}if(h===d){g=!0;d=f;c=e;break}h=h.sibling}if(!g)throw Error(u(189));}}if(c.alternate!==d)throw Error(u(190));}if(3!==c.tag)throw Error(u(188));return c.stateNode.current===c?a:b}function hc(a){a=gc(a);if(!a)return null;for(var b=a;;){if(5===b.tag||6===b.tag)return b;if(b.child)b.child.return=b,b=b.child;else{if(b===a)break;for(;!b.sibling;){if(!b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}}return null}
function ic(a,b){if(null==b)throw Error(u(30));if(null==a)return b;if(Array.isArray(a)){if(Array.isArray(b))return a.push.apply(a,b),a;a.push(b);return a}return Array.isArray(b)?[a].concat(b):[a,b]}function jc(a,b,c){Array.isArray(a)?a.forEach(b,c):a&&b.call(c,a)}var kc=null;
function lc(a){if(a){var b=a._dispatchListeners,c=a._dispatchInstances;if(Array.isArray(b))for(var d=0;d<b.length&&!a.isPropagationStopped();d++)oa(a,b[d],c[d]);else b&&oa(a,b,c);a._dispatchListeners=null;a._dispatchInstances=null;a.isPersistent()||a.constructor.release(a)}}function mc(a){null!==a&&(kc=ic(kc,a));a=kc;kc=null;if(a){jc(a,lc);if(kc)throw Error(u(95));if(fa)throw a=ha,fa=!1,ha=null,a;}}
function nc(a){a=a.target||a.srcElement||window;a.correspondingUseElement&&(a=a.correspondingUseElement);return 3===a.nodeType?a.parentNode:a}function oc(a){if(!ya)return!1;a="on"+a;var b=a in document;b||(b=document.createElement("div"),b.setAttribute(a,"return;"),b="function"===typeof b[a]);return b}var pc=[];function qc(a){a.topLevelType=null;a.nativeEvent=null;a.targetInst=null;a.ancestors.length=0;10>pc.length&&pc.push(a)}
function rc(a,b,c,d){if(pc.length){var e=pc.pop();e.topLevelType=a;e.eventSystemFlags=d;e.nativeEvent=b;e.targetInst=c;return e}return{topLevelType:a,eventSystemFlags:d,nativeEvent:b,targetInst:c,ancestors:[]}}
function sc(a){var b=a.targetInst,c=b;do{if(!c){a.ancestors.push(c);break}var d=c;if(3===d.tag)d=d.stateNode.containerInfo;else{for(;d.return;)d=d.return;d=3!==d.tag?null:d.stateNode.containerInfo}if(!d)break;b=c.tag;5!==b&&6!==b||a.ancestors.push(c);c=tc(d)}while(c);for(c=0;c<a.ancestors.length;c++){b=a.ancestors[c];var e=nc(a.nativeEvent);d=a.topLevelType;var f=a.nativeEvent,g=a.eventSystemFlags;0===c&&(g|=64);for(var h=null,k=0;k<sa.length;k++){var l=sa[k];l&&(l=l.extractEvents(d,b,f,e,g))&&(h=
ic(h,l))}mc(h)}}function uc(a,b,c){if(!c.has(a)){switch(a){case "scroll":vc(b,"scroll",!0);break;case "focus":case "blur":vc(b,"focus",!0);vc(b,"blur",!0);c.set("blur",null);c.set("focus",null);break;case "cancel":case "close":oc(a)&&vc(b,a,!0);break;case "invalid":case "submit":case "reset":break;default:-1===ac.indexOf(a)&&F(a,b)}c.set(a,null)}}
var wc,xc,yc,zc=!1,Ac=[],Bc=null,Cc=null,Dc=null,Ec=new Map,Fc=new Map,Gc=[],Hc="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput close cancel copy cut paste click change contextmenu reset submit".split(" "),Ic="focus blur dragenter dragleave mouseover mouseout pointerover pointerout gotpointercapture lostpointercapture".split(" ");
function Jc(a,b){var c=cc(b);Hc.forEach(function(a){uc(a,b,c)});Ic.forEach(function(a){uc(a,b,c)})}function Kc(a,b,c,d,e){return{blockedOn:a,topLevelType:b,eventSystemFlags:c|32,nativeEvent:e,container:d}}
function Lc(a,b){switch(a){case "focus":case "blur":Bc=null;break;case "dragenter":case "dragleave":Cc=null;break;case "mouseover":case "mouseout":Dc=null;break;case "pointerover":case "pointerout":Ec.delete(b.pointerId);break;case "gotpointercapture":case "lostpointercapture":Fc.delete(b.pointerId)}}function Mc(a,b,c,d,e,f){if(null===a||a.nativeEvent!==f)return a=Kc(b,c,d,e,f),null!==b&&(b=Nc(b),null!==b&&xc(b)),a;a.eventSystemFlags|=d;return a}
function Oc(a,b,c,d,e){switch(b){case "focus":return Bc=Mc(Bc,a,b,c,d,e),!0;case "dragenter":return Cc=Mc(Cc,a,b,c,d,e),!0;case "mouseover":return Dc=Mc(Dc,a,b,c,d,e),!0;case "pointerover":var f=e.pointerId;Ec.set(f,Mc(Ec.get(f)||null,a,b,c,d,e));return!0;case "gotpointercapture":return f=e.pointerId,Fc.set(f,Mc(Fc.get(f)||null,a,b,c,d,e)),!0}return!1}
function Pc(a){var b=tc(a.target);if(null!==b){var c=dc(b);if(null!==c)if(b=c.tag,13===b){if(b=ec(c),null!==b){a.blockedOn=b;r.unstable_runWithPriority(a.priority,function(){yc(c)});return}}else if(3===b&&c.stateNode.hydrate){a.blockedOn=3===c.tag?c.stateNode.containerInfo:null;return}}a.blockedOn=null}function Qc(a){if(null!==a.blockedOn)return!1;var b=Rc(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);if(null!==b){var c=Nc(b);null!==c&&xc(c);a.blockedOn=b;return!1}return!0}
function Sc(a,b,c){Qc(a)&&c.delete(b)}function Tc(){for(zc=!1;0<Ac.length;){var a=Ac[0];if(null!==a.blockedOn){a=Nc(a.blockedOn);null!==a&&wc(a);break}var b=Rc(a.topLevelType,a.eventSystemFlags,a.container,a.nativeEvent);null!==b?a.blockedOn=b:Ac.shift()}null!==Bc&&Qc(Bc)&&(Bc=null);null!==Cc&&Qc(Cc)&&(Cc=null);null!==Dc&&Qc(Dc)&&(Dc=null);Ec.forEach(Sc);Fc.forEach(Sc)}function Uc(a,b){a.blockedOn===b&&(a.blockedOn=null,zc||(zc=!0,r.unstable_scheduleCallback(r.unstable_NormalPriority,Tc)))}
function Vc(a){function b(b){return Uc(b,a)}if(0<Ac.length){Uc(Ac[0],a);for(var c=1;c<Ac.length;c++){var d=Ac[c];d.blockedOn===a&&(d.blockedOn=null)}}null!==Bc&&Uc(Bc,a);null!==Cc&&Uc(Cc,a);null!==Dc&&Uc(Dc,a);Ec.forEach(b);Fc.forEach(b);for(c=0;c<Gc.length;c++)d=Gc[c],d.blockedOn===a&&(d.blockedOn=null);for(;0<Gc.length&&(c=Gc[0],null===c.blockedOn);)Pc(c),null===c.blockedOn&&Gc.shift()}
var Wc={},Yc=new Map,Zc=new Map,$c=["abort","abort",Xb,"animationEnd",Yb,"animationIteration",Zb,"animationStart","canplay","canPlay","canplaythrough","canPlayThrough","durationchange","durationChange","emptied","emptied","encrypted","encrypted","ended","ended","error","error","gotpointercapture","gotPointerCapture","load","load","loadeddata","loadedData","loadedmetadata","loadedMetadata","loadstart","loadStart","lostpointercapture","lostPointerCapture","playing","playing","progress","progress","seeking",
"seeking","stalled","stalled","suspend","suspend","timeupdate","timeUpdate",$b,"transitionEnd","waiting","waiting"];function ad(a,b){for(var c=0;c<a.length;c+=2){var d=a[c],e=a[c+1],f="on"+(e[0].toUpperCase()+e.slice(1));f={phasedRegistrationNames:{bubbled:f,captured:f+"Capture"},dependencies:[d],eventPriority:b};Zc.set(d,b);Yc.set(d,f);Wc[e]=f}}
ad("blur blur cancel cancel click click close close contextmenu contextMenu copy copy cut cut auxclick auxClick dblclick doubleClick dragend dragEnd dragstart dragStart drop drop focus focus input input invalid invalid keydown keyDown keypress keyPress keyup keyUp mousedown mouseDown mouseup mouseUp paste paste pause pause play play pointercancel pointerCancel pointerdown pointerDown pointerup pointerUp ratechange rateChange reset reset seeked seeked submit submit touchcancel touchCancel touchend touchEnd touchstart touchStart volumechange volumeChange".split(" "),0);
ad("drag drag dragenter dragEnter dragexit dragExit dragleave dragLeave dragover dragOver mousemove mouseMove mouseout mouseOut mouseover mouseOver pointermove pointerMove pointerout pointerOut pointerover pointerOver scroll scroll toggle toggle touchmove touchMove wheel wheel".split(" "),1);ad($c,2);for(var bd="change selectionchange textInput compositionstart compositionend compositionupdate".split(" "),cd=0;cd<bd.length;cd++)Zc.set(bd[cd],0);
var dd=r.unstable_UserBlockingPriority,ed=r.unstable_runWithPriority,fd=!0;function F(a,b){vc(b,a,!1)}function vc(a,b,c){var d=Zc.get(b);switch(void 0===d?2:d){case 0:d=gd.bind(null,b,1,a);break;case 1:d=hd.bind(null,b,1,a);break;default:d=id.bind(null,b,1,a)}c?a.addEventListener(b,d,!0):a.addEventListener(b,d,!1)}function gd(a,b,c,d){Ja||Ha();var e=id,f=Ja;Ja=!0;try{Ga(e,a,b,c,d)}finally{(Ja=f)||La()}}function hd(a,b,c,d){ed(dd,id.bind(null,a,b,c,d))}
function id(a,b,c,d){if(fd)if(0<Ac.length&&-1<Hc.indexOf(a))a=Kc(null,a,b,c,d),Ac.push(a);else{var e=Rc(a,b,c,d);if(null===e)Lc(a,d);else if(-1<Hc.indexOf(a))a=Kc(e,a,b,c,d),Ac.push(a);else if(!Oc(e,a,b,c,d)){Lc(a,d);a=rc(a,d,null,b);try{Ma(sc,a)}finally{qc(a)}}}}
function Rc(a,b,c,d){c=nc(d);c=tc(c);if(null!==c){var e=dc(c);if(null===e)c=null;else{var f=e.tag;if(13===f){c=ec(e);if(null!==c)return c;c=null}else if(3===f){if(e.stateNode.hydrate)return 3===e.tag?e.stateNode.containerInfo:null;c=null}else e!==c&&(c=null)}}a=rc(a,d,c,b);try{Ma(sc,a)}finally{qc(a)}return null}
var jd={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,
floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},kd=["Webkit","ms","Moz","O"];Object.keys(jd).forEach(function(a){kd.forEach(function(b){b=b+a.charAt(0).toUpperCase()+a.substring(1);jd[b]=jd[a]})});function ld(a,b,c){return null==b||"boolean"===typeof b||""===b?"":c||"number"!==typeof b||0===b||jd.hasOwnProperty(a)&&jd[a]?(""+b).trim():b+"px"}
function md(a,b){a=a.style;for(var c in b)if(b.hasOwnProperty(c)){var d=0===c.indexOf("--"),e=ld(c,b[c],d);"float"===c&&(c="cssFloat");d?a.setProperty(c,e):a[c]=e}}var nd=n({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});
function od(a,b){if(b){if(nd[a]&&(null!=b.children||null!=b.dangerouslySetInnerHTML))throw Error(u(137,a,""));if(null!=b.dangerouslySetInnerHTML){if(null!=b.children)throw Error(u(60));if(!("object"===typeof b.dangerouslySetInnerHTML&&"__html"in b.dangerouslySetInnerHTML))throw Error(u(61));}if(null!=b.style&&"object"!==typeof b.style)throw Error(u(62,""));}}
function pd(a,b){if(-1===a.indexOf("-"))return"string"===typeof b.is;switch(a){case "annotation-xml":case "color-profile":case "font-face":case "font-face-src":case "font-face-uri":case "font-face-format":case "font-face-name":case "missing-glyph":return!1;default:return!0}}var qd=Mb.html;function rd(a,b){a=9===a.nodeType||11===a.nodeType?a:a.ownerDocument;var c=cc(a);b=wa[b];for(var d=0;d<b.length;d++)uc(b[d],a,c)}function sd(){}
function td(a){a=a||("undefined"!==typeof document?document:void 0);if("undefined"===typeof a)return null;try{return a.activeElement||a.body}catch(b){return a.body}}function ud(a){for(;a&&a.firstChild;)a=a.firstChild;return a}function vd(a,b){var c=ud(a);a=0;for(var d;c;){if(3===c.nodeType){d=a+c.textContent.length;if(a<=b&&d>=b)return{node:c,offset:b-a};a=d}a:{for(;c;){if(c.nextSibling){c=c.nextSibling;break a}c=c.parentNode}c=void 0}c=ud(c)}}
function wd(a,b){return a&&b?a===b?!0:a&&3===a.nodeType?!1:b&&3===b.nodeType?wd(a,b.parentNode):"contains"in a?a.contains(b):a.compareDocumentPosition?!!(a.compareDocumentPosition(b)&16):!1:!1}function xd(){for(var a=window,b=td();b instanceof a.HTMLIFrameElement;){try{var c="string"===typeof b.contentWindow.location.href}catch(d){c=!1}if(c)a=b.contentWindow;else break;b=td(a.document)}return b}
function yd(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return b&&("input"===b&&("text"===a.type||"search"===a.type||"tel"===a.type||"url"===a.type||"password"===a.type)||"textarea"===b||"true"===a.contentEditable)}var zd="$",Ad="/$",Bd="$?",Cd="$!",Dd=null,Ed=null;function Fd(a,b){switch(a){case "button":case "input":case "select":case "textarea":return!!b.autoFocus}return!1}
function Gd(a,b){return"textarea"===a||"option"===a||"noscript"===a||"string"===typeof b.children||"number"===typeof b.children||"object"===typeof b.dangerouslySetInnerHTML&&null!==b.dangerouslySetInnerHTML&&null!=b.dangerouslySetInnerHTML.__html}var Hd="function"===typeof setTimeout?setTimeout:void 0,Id="function"===typeof clearTimeout?clearTimeout:void 0;function Jd(a){for(;null!=a;a=a.nextSibling){var b=a.nodeType;if(1===b||3===b)break}return a}
function Kd(a){a=a.previousSibling;for(var b=0;a;){if(8===a.nodeType){var c=a.data;if(c===zd||c===Cd||c===Bd){if(0===b)return a;b--}else c===Ad&&b++}a=a.previousSibling}return null}var Ld=Math.random().toString(36).slice(2),Md="__reactInternalInstance$"+Ld,Nd="__reactEventHandlers$"+Ld,Od="__reactContainere$"+Ld;
function tc(a){var b=a[Md];if(b)return b;for(var c=a.parentNode;c;){if(b=c[Od]||c[Md]){c=b.alternate;if(null!==b.child||null!==c&&null!==c.child)for(a=Kd(a);null!==a;){if(c=a[Md])return c;a=Kd(a)}return b}a=c;c=a.parentNode}return null}function Nc(a){a=a[Md]||a[Od];return!a||5!==a.tag&&6!==a.tag&&13!==a.tag&&3!==a.tag?null:a}function Pd(a){if(5===a.tag||6===a.tag)return a.stateNode;throw Error(u(33));}function Qd(a){return a[Nd]||null}
function Rd(a){do a=a.return;while(a&&5!==a.tag);return a?a:null}
function Sd(a,b){var c=a.stateNode;if(!c)return null;var d=la(c);if(!d)return null;c=d[b];a:switch(b){case "onClick":case "onClickCapture":case "onDoubleClick":case "onDoubleClickCapture":case "onMouseDown":case "onMouseDownCapture":case "onMouseMove":case "onMouseMoveCapture":case "onMouseUp":case "onMouseUpCapture":case "onMouseEnter":(d=!d.disabled)||(a=a.type,d=!("button"===a||"input"===a||"select"===a||"textarea"===a));a=!d;break a;default:a=!1}if(a)return null;if(c&&"function"!==typeof c)throw Error(u(231,
b,typeof c));return c}function Td(a,b,c){if(b=Sd(a,c.dispatchConfig.phasedRegistrationNames[b]))c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a)}function Ud(a){if(a&&a.dispatchConfig.phasedRegistrationNames){for(var b=a._targetInst,c=[];b;)c.push(b),b=Rd(b);for(b=c.length;0<b--;)Td(c[b],"captured",a);for(b=0;b<c.length;b++)Td(c[b],"bubbled",a)}}
function Vd(a,b,c){a&&c&&c.dispatchConfig.registrationName&&(b=Sd(a,c.dispatchConfig.registrationName))&&(c._dispatchListeners=ic(c._dispatchListeners,b),c._dispatchInstances=ic(c._dispatchInstances,a))}function Wd(a){a&&a.dispatchConfig.registrationName&&Vd(a._targetInst,null,a)}function Xd(a){jc(a,Ud)}var Yd=null,Zd=null,$d=null;
function ae(){if($d)return $d;var a,b=Zd,c=b.length,d,e="value"in Yd?Yd.value:Yd.textContent,f=e.length;for(a=0;a<c&&b[a]===e[a];a++);var g=c-a;for(d=1;d<=g&&b[c-d]===e[f-d];d++);return $d=e.slice(a,1<d?1-d:void 0)}function be(){return!0}function ce(){return!1}
function G(a,b,c,d){this.dispatchConfig=a;this._targetInst=b;this.nativeEvent=c;a=this.constructor.Interface;for(var e in a)a.hasOwnProperty(e)&&((b=a[e])?this[e]=b(c):"target"===e?this.target=d:this[e]=c[e]);this.isDefaultPrevented=(null!=c.defaultPrevented?c.defaultPrevented:!1===c.returnValue)?be:ce;this.isPropagationStopped=ce;return this}
n(G.prototype,{preventDefault:function(){this.defaultPrevented=!0;var a=this.nativeEvent;a&&(a.preventDefault?a.preventDefault():"unknown"!==typeof a.returnValue&&(a.returnValue=!1),this.isDefaultPrevented=be)},stopPropagation:function(){var a=this.nativeEvent;a&&(a.stopPropagation?a.stopPropagation():"unknown"!==typeof a.cancelBubble&&(a.cancelBubble=!0),this.isPropagationStopped=be)},persist:function(){this.isPersistent=be},isPersistent:ce,destructor:function(){var a=this.constructor.Interface,
b;for(b in a)this[b]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null;this.isPropagationStopped=this.isDefaultPrevented=ce;this._dispatchInstances=this._dispatchListeners=null}});G.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(a){return a.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null};
G.extend=function(a){function b(){}function c(){return d.apply(this,arguments)}var d=this;b.prototype=d.prototype;var e=new b;n(e,c.prototype);c.prototype=e;c.prototype.constructor=c;c.Interface=n({},d.Interface,a);c.extend=d.extend;de(c);return c};de(G);function ee(a,b,c,d){if(this.eventPool.length){var e=this.eventPool.pop();this.call(e,a,b,c,d);return e}return new this(a,b,c,d)}
function fe(a){if(!(a instanceof this))throw Error(u(279));a.destructor();10>this.eventPool.length&&this.eventPool.push(a)}function de(a){a.eventPool=[];a.getPooled=ee;a.release=fe}var ge=G.extend({data:null}),he=G.extend({data:null}),ie=[9,13,27,32],je=ya&&"CompositionEvent"in window,ke=null;ya&&"documentMode"in document&&(ke=document.documentMode);
var le=ya&&"TextEvent"in window&&!ke,me=ya&&(!je||ke&&8<ke&&11>=ke),ne=String.fromCharCode(32),oe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",
captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},pe=!1;
function qe(a,b){switch(a){case "keyup":return-1!==ie.indexOf(b.keyCode);case "keydown":return 229!==b.keyCode;case "keypress":case "mousedown":case "blur":return!0;default:return!1}}function re(a){a=a.detail;return"object"===typeof a&&"data"in a?a.data:null}var se=!1;function te(a,b){switch(a){case "compositionend":return re(b);case "keypress":if(32!==b.which)return null;pe=!0;return ne;case "textInput":return a=b.data,a===ne&&pe?null:a;default:return null}}
function ue(a,b){if(se)return"compositionend"===a||!je&&qe(a,b)?(a=ae(),$d=Zd=Yd=null,se=!1,a):null;switch(a){case "paste":return null;case "keypress":if(!(b.ctrlKey||b.altKey||b.metaKey)||b.ctrlKey&&b.altKey){if(b.char&&1<b.char.length)return b.char;if(b.which)return String.fromCharCode(b.which)}return null;case "compositionend":return me&&"ko"!==b.locale?null:b.data;default:return null}}
var ve={eventTypes:oe,extractEvents:function(a,b,c,d){var e;if(je)b:{switch(a){case "compositionstart":var f=oe.compositionStart;break b;case "compositionend":f=oe.compositionEnd;break b;case "compositionupdate":f=oe.compositionUpdate;break b}f=void 0}else se?qe(a,c)&&(f=oe.compositionEnd):"keydown"===a&&229===c.keyCode&&(f=oe.compositionStart);f?(me&&"ko"!==c.locale&&(se||f!==oe.compositionStart?f===oe.compositionEnd&&se&&(e=ae()):(Yd=d,Zd="value"in Yd?Yd.value:Yd.textContent,se=!0)),f=ge.getPooled(f,
b,c,d),e?f.data=e:(e=re(c),null!==e&&(f.data=e)),Xd(f),e=f):e=null;(a=le?te(a,c):ue(a,c))?(b=he.getPooled(oe.beforeInput,b,c,d),b.data=a,Xd(b)):b=null;return null===e?b:null===b?e:[e,b]}},we={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function xe(a){var b=a&&a.nodeName&&a.nodeName.toLowerCase();return"input"===b?!!we[a.type]:"textarea"===b?!0:!1}
var ye={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function ze(a,b,c){a=G.getPooled(ye.change,a,b,c);a.type="change";Da(c);Xd(a);return a}var Ae=null,Be=null;function Ce(a){mc(a)}function De(a){var b=Pd(a);if(yb(b))return a}function Ee(a,b){if("change"===a)return b}var Fe=!1;ya&&(Fe=oc("input")&&(!document.documentMode||9<document.documentMode));
function Ge(){Ae&&(Ae.detachEvent("onpropertychange",He),Be=Ae=null)}function He(a){if("value"===a.propertyName&&De(Be))if(a=ze(Be,a,nc(a)),Ja)mc(a);else{Ja=!0;try{Fa(Ce,a)}finally{Ja=!1,La()}}}function Ie(a,b,c){"focus"===a?(Ge(),Ae=b,Be=c,Ae.attachEvent("onpropertychange",He)):"blur"===a&&Ge()}function Je(a){if("selectionchange"===a||"keyup"===a||"keydown"===a)return De(Be)}function Ke(a,b){if("click"===a)return De(b)}function Le(a,b){if("input"===a||"change"===a)return De(b)}
var Me={eventTypes:ye,_isInputEventSupported:Fe,extractEvents:function(a,b,c,d){var e=b?Pd(b):window,f=e.nodeName&&e.nodeName.toLowerCase();if("select"===f||"input"===f&&"file"===e.type)var g=Ee;else if(xe(e))if(Fe)g=Le;else{g=Je;var h=Ie}else(f=e.nodeName)&&"input"===f.toLowerCase()&&("checkbox"===e.type||"radio"===e.type)&&(g=Ke);if(g&&(g=g(a,b)))return ze(g,c,d);h&&h(a,e,b);"blur"===a&&(a=e._wrapperState)&&a.controlled&&"number"===e.type&&Db(e,"number",e.value)}},Ne=G.extend({view:null,detail:null}),
Oe={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Pe(a){var b=this.nativeEvent;return b.getModifierState?b.getModifierState(a):(a=Oe[a])?!!b[a]:!1}function Qe(){return Pe}
var Re=0,Se=0,Te=!1,Ue=!1,Ve=Ne.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Qe,button:null,buttons:null,relatedTarget:function(a){return a.relatedTarget||(a.fromElement===a.srcElement?a.toElement:a.fromElement)},movementX:function(a){if("movementX"in a)return a.movementX;var b=Re;Re=a.screenX;return Te?"mousemove"===a.type?a.screenX-b:0:(Te=!0,0)},movementY:function(a){if("movementY"in a)return a.movementY;
var b=Se;Se=a.screenY;return Ue?"mousemove"===a.type?a.screenY-b:0:(Ue=!0,0)}}),We=Ve.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),Xe={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",
dependencies:["pointerout","pointerover"]}},Ye={eventTypes:Xe,extractEvents:function(a,b,c,d,e){var f="mouseover"===a||"pointerover"===a,g="mouseout"===a||"pointerout"===a;if(f&&0===(e&32)&&(c.relatedTarget||c.fromElement)||!g&&!f)return null;f=d.window===d?d:(f=d.ownerDocument)?f.defaultView||f.parentWindow:window;if(g){if(g=b,b=(b=c.relatedTarget||c.toElement)?tc(b):null,null!==b){var h=dc(b);if(b!==h||5!==b.tag&&6!==b.tag)b=null}}else g=null;if(g===b)return null;if("mouseout"===a||"mouseover"===
a){var k=Ve;var l=Xe.mouseLeave;var m=Xe.mouseEnter;var p="mouse"}else if("pointerout"===a||"pointerover"===a)k=We,l=Xe.pointerLeave,m=Xe.pointerEnter,p="pointer";a=null==g?f:Pd(g);f=null==b?f:Pd(b);l=k.getPooled(l,g,c,d);l.type=p+"leave";l.target=a;l.relatedTarget=f;c=k.getPooled(m,b,c,d);c.type=p+"enter";c.target=f;c.relatedTarget=a;d=g;p=b;if(d&&p)a:{k=d;m=p;g=0;for(a=k;a;a=Rd(a))g++;a=0;for(b=m;b;b=Rd(b))a++;for(;0<g-a;)k=Rd(k),g--;for(;0<a-g;)m=Rd(m),a--;for(;g--;){if(k===m||k===m.alternate)break a;
k=Rd(k);m=Rd(m)}k=null}else k=null;m=k;for(k=[];d&&d!==m;){g=d.alternate;if(null!==g&&g===m)break;k.push(d);d=Rd(d)}for(d=[];p&&p!==m;){g=p.alternate;if(null!==g&&g===m)break;d.push(p);p=Rd(p)}for(p=0;p<k.length;p++)Vd(k[p],"bubbled",l);for(p=d.length;0<p--;)Vd(d[p],"captured",c);return 0===(e&64)?[l]:[l,c]}};function Ze(a,b){return a===b&&(0!==a||1/a===1/b)||a!==a&&b!==b}var $e="function"===typeof Object.is?Object.is:Ze,af=Object.prototype.hasOwnProperty;
function bf(a,b){if($e(a,b))return!0;if("object"!==typeof a||null===a||"object"!==typeof b||null===b)return!1;var c=Object.keys(a),d=Object.keys(b);if(c.length!==d.length)return!1;for(d=0;d<c.length;d++)if(!af.call(b,c[d])||!$e(a[c[d]],b[c[d]]))return!1;return!0}
var cf=ya&&"documentMode"in document&&11>=document.documentMode,df={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},ef=null,ff=null,gf=null,hf=!1;
function jf(a,b){var c=b.window===b?b.document:9===b.nodeType?b:b.ownerDocument;if(hf||null==ef||ef!==td(c))return null;c=ef;"selectionStart"in c&&yd(c)?c={start:c.selectionStart,end:c.selectionEnd}:(c=(c.ownerDocument&&c.ownerDocument.defaultView||window).getSelection(),c={anchorNode:c.anchorNode,anchorOffset:c.anchorOffset,focusNode:c.focusNode,focusOffset:c.focusOffset});return gf&&bf(gf,c)?null:(gf=c,a=G.getPooled(df.select,ff,a,b),a.type="select",a.target=ef,Xd(a),a)}
var kf={eventTypes:df,extractEvents:function(a,b,c,d,e,f){e=f||(d.window===d?d.document:9===d.nodeType?d:d.ownerDocument);if(!(f=!e)){a:{e=cc(e);f=wa.onSelect;for(var g=0;g<f.length;g++)if(!e.has(f[g])){e=!1;break a}e=!0}f=!e}if(f)return null;e=b?Pd(b):window;switch(a){case "focus":if(xe(e)||"true"===e.contentEditable)ef=e,ff=b,gf=null;break;case "blur":gf=ff=ef=null;break;case "mousedown":hf=!0;break;case "contextmenu":case "mouseup":case "dragend":return hf=!1,jf(c,d);case "selectionchange":if(cf)break;
case "keydown":case "keyup":return jf(c,d)}return null}},lf=G.extend({animationName:null,elapsedTime:null,pseudoElement:null}),mf=G.extend({clipboardData:function(a){return"clipboardData"in a?a.clipboardData:window.clipboardData}}),nf=Ne.extend({relatedTarget:null});function of(a){var b=a.keyCode;"charCode"in a?(a=a.charCode,0===a&&13===b&&(a=13)):a=b;10===a&&(a=13);return 32<=a||13===a?a:0}
var pf={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},qf={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",
116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},rf=Ne.extend({key:function(a){if(a.key){var b=pf[a.key]||a.key;if("Unidentified"!==b)return b}return"keypress"===a.type?(a=of(a),13===a?"Enter":String.fromCharCode(a)):"keydown"===a.type||"keyup"===a.type?qf[a.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Qe,charCode:function(a){return"keypress"===
a.type?of(a):0},keyCode:function(a){return"keydown"===a.type||"keyup"===a.type?a.keyCode:0},which:function(a){return"keypress"===a.type?of(a):"keydown"===a.type||"keyup"===a.type?a.keyCode:0}}),sf=Ve.extend({dataTransfer:null}),tf=Ne.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Qe}),uf=G.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),vf=Ve.extend({deltaX:function(a){return"deltaX"in a?a.deltaX:"wheelDeltaX"in
a?-a.wheelDeltaX:0},deltaY:function(a){return"deltaY"in a?a.deltaY:"wheelDeltaY"in a?-a.wheelDeltaY:"wheelDelta"in a?-a.wheelDelta:0},deltaZ:null,deltaMode:null}),wf={eventTypes:Wc,extractEvents:function(a,b,c,d){var e=Yc.get(a);if(!e)return null;switch(a){case "keypress":if(0===of(c))return null;case "keydown":case "keyup":a=rf;break;case "blur":case "focus":a=nf;break;case "click":if(2===c.button)return null;case "auxclick":case "dblclick":case "mousedown":case "mousemove":case "mouseup":case "mouseout":case "mouseover":case "contextmenu":a=
Ve;break;case "drag":case "dragend":case "dragenter":case "dragexit":case "dragleave":case "dragover":case "dragstart":case "drop":a=sf;break;case "touchcancel":case "touchend":case "touchmove":case "touchstart":a=tf;break;case Xb:case Yb:case Zb:a=lf;break;case $b:a=uf;break;case "scroll":a=Ne;break;case "wheel":a=vf;break;case "copy":case "cut":case "paste":a=mf;break;case "gotpointercapture":case "lostpointercapture":case "pointercancel":case "pointerdown":case "pointermove":case "pointerout":case "pointerover":case "pointerup":a=
We;break;default:a=G}b=a.getPooled(e,b,c,d);Xd(b);return b}};if(pa)throw Error(u(101));pa=Array.prototype.slice.call("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" "));ra();var xf=Nc;la=Qd;ma=xf;na=Pd;xa({SimpleEventPlugin:wf,EnterLeaveEventPlugin:Ye,ChangeEventPlugin:Me,SelectEventPlugin:kf,BeforeInputEventPlugin:ve});var yf=[],zf=-1;function H(a){0>zf||(a.current=yf[zf],yf[zf]=null,zf--)}
function I(a,b){zf++;yf[zf]=a.current;a.current=b}var Af={},J={current:Af},K={current:!1},Bf=Af;function Cf(a,b){var c=a.type.contextTypes;if(!c)return Af;var d=a.stateNode;if(d&&d.__reactInternalMemoizedUnmaskedChildContext===b)return d.__reactInternalMemoizedMaskedChildContext;var e={},f;for(f in c)e[f]=b[f];d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=b,a.__reactInternalMemoizedMaskedChildContext=e);return e}function L(a){a=a.childContextTypes;return null!==a&&void 0!==a}
function Df(){H(K);H(J)}function Ef(a,b,c){if(J.current!==Af)throw Error(u(168));I(J,b);I(K,c)}function Ff(a,b,c){var d=a.stateNode;a=b.childContextTypes;if("function"!==typeof d.getChildContext)return c;d=d.getChildContext();for(var e in d)if(!(e in a))throw Error(u(108,pb(b)||"Unknown",e));return n({},c,{},d)}function Gf(a){a=(a=a.stateNode)&&a.__reactInternalMemoizedMergedChildContext||Af;Bf=J.current;I(J,a);I(K,K.current);return!0}
function Hf(a,b,c){var d=a.stateNode;if(!d)throw Error(u(169));c?(a=Ff(a,b,Bf),d.__reactInternalMemoizedMergedChildContext=a,H(K),H(J),I(J,a)):H(K);I(K,c)}
var If=r.unstable_runWithPriority,Jf=r.unstable_scheduleCallback,Kf=r.unstable_cancelCallback,Lf=r.unstable_requestPaint,Mf=r.unstable_now,Nf=r.unstable_getCurrentPriorityLevel,Of=r.unstable_ImmediatePriority,Pf=r.unstable_UserBlockingPriority,Qf=r.unstable_NormalPriority,Rf=r.unstable_LowPriority,Sf=r.unstable_IdlePriority,Tf={},Uf=r.unstable_shouldYield,Vf=void 0!==Lf?Lf:function(){},Wf=null,Xf=null,Yf=!1,Zf=Mf(),$f=1E4>Zf?Mf:function(){return Mf()-Zf};
function ag(){switch(Nf()){case Of:return 99;case Pf:return 98;case Qf:return 97;case Rf:return 96;case Sf:return 95;default:throw Error(u(332));}}function bg(a){switch(a){case 99:return Of;case 98:return Pf;case 97:return Qf;case 96:return Rf;case 95:return Sf;default:throw Error(u(332));}}function cg(a,b){a=bg(a);return If(a,b)}function dg(a,b,c){a=bg(a);return Jf(a,b,c)}function eg(a){null===Wf?(Wf=[a],Xf=Jf(Of,fg)):Wf.push(a);return Tf}function gg(){if(null!==Xf){var a=Xf;Xf=null;Kf(a)}fg()}
function fg(){if(!Yf&&null!==Wf){Yf=!0;var a=0;try{var b=Wf;cg(99,function(){for(;a<b.length;a++){var c=b[a];do c=c(!0);while(null!==c)}});Wf=null}catch(c){throw null!==Wf&&(Wf=Wf.slice(a+1)),Jf(Of,gg),c;}finally{Yf=!1}}}function hg(a,b,c){c/=10;return 1073741821-(((1073741821-a+b/10)/c|0)+1)*c}function ig(a,b){if(a&&a.defaultProps){b=n({},b);a=a.defaultProps;for(var c in a)void 0===b[c]&&(b[c]=a[c])}return b}var jg={current:null},kg=null,lg=null,mg=null;function ng(){mg=lg=kg=null}
function og(a){var b=jg.current;H(jg);a.type._context._currentValue=b}function pg(a,b){for(;null!==a;){var c=a.alternate;if(a.childExpirationTime<b)a.childExpirationTime=b,null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);else if(null!==c&&c.childExpirationTime<b)c.childExpirationTime=b;else break;a=a.return}}function qg(a,b){kg=a;mg=lg=null;a=a.dependencies;null!==a&&null!==a.firstContext&&(a.expirationTime>=b&&(rg=!0),a.firstContext=null)}
function sg(a,b){if(mg!==a&&!1!==b&&0!==b){if("number"!==typeof b||1073741823===b)mg=a,b=1073741823;b={context:a,observedBits:b,next:null};if(null===lg){if(null===kg)throw Error(u(308));lg=b;kg.dependencies={expirationTime:0,firstContext:b,responders:null}}else lg=lg.next=b}return a._currentValue}var tg=!1;function ug(a){a.updateQueue={baseState:a.memoizedState,baseQueue:null,shared:{pending:null},effects:null}}
function vg(a,b){a=a.updateQueue;b.updateQueue===a&&(b.updateQueue={baseState:a.baseState,baseQueue:a.baseQueue,shared:a.shared,effects:a.effects})}function wg(a,b){a={expirationTime:a,suspenseConfig:b,tag:0,payload:null,callback:null,next:null};return a.next=a}function xg(a,b){a=a.updateQueue;if(null!==a){a=a.shared;var c=a.pending;null===c?b.next=b:(b.next=c.next,c.next=b);a.pending=b}}
function yg(a,b){var c=a.alternate;null!==c&&vg(c,a);a=a.updateQueue;c=a.baseQueue;null===c?(a.baseQueue=b.next=b,b.next=b):(b.next=c.next,c.next=b)}
function zg(a,b,c,d){var e=a.updateQueue;tg=!1;var f=e.baseQueue,g=e.shared.pending;if(null!==g){if(null!==f){var h=f.next;f.next=g.next;g.next=h}f=g;e.shared.pending=null;h=a.alternate;null!==h&&(h=h.updateQueue,null!==h&&(h.baseQueue=g))}if(null!==f){h=f.next;var k=e.baseState,l=0,m=null,p=null,x=null;if(null!==h){var z=h;do{g=z.expirationTime;if(g<d){var ca={expirationTime:z.expirationTime,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null};null===x?(p=x=
ca,m=k):x=x.next=ca;g>l&&(l=g)}else{null!==x&&(x=x.next={expirationTime:1073741823,suspenseConfig:z.suspenseConfig,tag:z.tag,payload:z.payload,callback:z.callback,next:null});Ag(g,z.suspenseConfig);a:{var D=a,t=z;g=b;ca=c;switch(t.tag){case 1:D=t.payload;if("function"===typeof D){k=D.call(ca,k,g);break a}k=D;break a;case 3:D.effectTag=D.effectTag&-4097|64;case 0:D=t.payload;g="function"===typeof D?D.call(ca,k,g):D;if(null===g||void 0===g)break a;k=n({},k,g);break a;case 2:tg=!0}}null!==z.callback&&
(a.effectTag|=32,g=e.effects,null===g?e.effects=[z]:g.push(z))}z=z.next;if(null===z||z===h)if(g=e.shared.pending,null===g)break;else z=f.next=g.next,g.next=h,e.baseQueue=f=g,e.shared.pending=null}while(1)}null===x?m=k:x.next=p;e.baseState=m;e.baseQueue=x;Bg(l);a.expirationTime=l;a.memoizedState=k}}
function Cg(a,b,c){a=b.effects;b.effects=null;if(null!==a)for(b=0;b<a.length;b++){var d=a[b],e=d.callback;if(null!==e){d.callback=null;d=e;e=c;if("function"!==typeof d)throw Error(u(191,d));d.call(e)}}}var Dg=Wa.ReactCurrentBatchConfig,Eg=(new aa.Component).refs;function Fg(a,b,c,d){b=a.memoizedState;c=c(d,b);c=null===c||void 0===c?b:n({},b,c);a.memoizedState=c;0===a.expirationTime&&(a.updateQueue.baseState=c)}
var Jg={isMounted:function(a){return(a=a._reactInternalFiber)?dc(a)===a:!1},enqueueSetState:function(a,b,c){a=a._reactInternalFiber;var d=Gg(),e=Dg.suspense;d=Hg(d,a,e);e=wg(d,e);e.payload=b;void 0!==c&&null!==c&&(e.callback=c);xg(a,e);Ig(a,d)},enqueueReplaceState:function(a,b,c){a=a._reactInternalFiber;var d=Gg(),e=Dg.suspense;d=Hg(d,a,e);e=wg(d,e);e.tag=1;e.payload=b;void 0!==c&&null!==c&&(e.callback=c);xg(a,e);Ig(a,d)},enqueueForceUpdate:function(a,b){a=a._reactInternalFiber;var c=Gg(),d=Dg.suspense;
c=Hg(c,a,d);d=wg(c,d);d.tag=2;void 0!==b&&null!==b&&(d.callback=b);xg(a,d);Ig(a,c)}};function Kg(a,b,c,d,e,f,g){a=a.stateNode;return"function"===typeof a.shouldComponentUpdate?a.shouldComponentUpdate(d,f,g):b.prototype&&b.prototype.isPureReactComponent?!bf(c,d)||!bf(e,f):!0}
function Lg(a,b,c){var d=!1,e=Af;var f=b.contextType;"object"===typeof f&&null!==f?f=sg(f):(e=L(b)?Bf:J.current,d=b.contextTypes,f=(d=null!==d&&void 0!==d)?Cf(a,e):Af);b=new b(c,f);a.memoizedState=null!==b.state&&void 0!==b.state?b.state:null;b.updater=Jg;a.stateNode=b;b._reactInternalFiber=a;d&&(a=a.stateNode,a.__reactInternalMemoizedUnmaskedChildContext=e,a.__reactInternalMemoizedMaskedChildContext=f);return b}
function Mg(a,b,c,d){a=b.state;"function"===typeof b.componentWillReceiveProps&&b.componentWillReceiveProps(c,d);"function"===typeof b.UNSAFE_componentWillReceiveProps&&b.UNSAFE_componentWillReceiveProps(c,d);b.state!==a&&Jg.enqueueReplaceState(b,b.state,null)}
function Ng(a,b,c,d){var e=a.stateNode;e.props=c;e.state=a.memoizedState;e.refs=Eg;ug(a);var f=b.contextType;"object"===typeof f&&null!==f?e.context=sg(f):(f=L(b)?Bf:J.current,e.context=Cf(a,f));zg(a,c,e,d);e.state=a.memoizedState;f=b.getDerivedStateFromProps;"function"===typeof f&&(Fg(a,b,f,c),e.state=a.memoizedState);"function"===typeof b.getDerivedStateFromProps||"function"===typeof e.getSnapshotBeforeUpdate||"function"!==typeof e.UNSAFE_componentWillMount&&"function"!==typeof e.componentWillMount||
(b=e.state,"function"===typeof e.componentWillMount&&e.componentWillMount(),"function"===typeof e.UNSAFE_componentWillMount&&e.UNSAFE_componentWillMount(),b!==e.state&&Jg.enqueueReplaceState(e,e.state,null),zg(a,c,e,d),e.state=a.memoizedState);"function"===typeof e.componentDidMount&&(a.effectTag|=4)}var Og=Array.isArray;
function Pg(a,b,c){a=c.ref;if(null!==a&&"function"!==typeof a&&"object"!==typeof a){if(c._owner){c=c._owner;if(c){if(1!==c.tag)throw Error(u(309));var d=c.stateNode}if(!d)throw Error(u(147,a));var e=""+a;if(null!==b&&null!==b.ref&&"function"===typeof b.ref&&b.ref._stringRef===e)return b.ref;b=function(a){var b=d.refs;b===Eg&&(b=d.refs={});null===a?delete b[e]:b[e]=a};b._stringRef=e;return b}if("string"!==typeof a)throw Error(u(284));if(!c._owner)throw Error(u(290,a));}return a}
function Qg(a,b){if("textarea"!==a.type)throw Error(u(31,"[object Object]"===Object.prototype.toString.call(b)?"object with keys {"+Object.keys(b).join(", ")+"}":b,""));}
function Rg(a){function b(b,c){if(a){var d=b.lastEffect;null!==d?(d.nextEffect=c,b.lastEffect=c):b.firstEffect=b.lastEffect=c;c.nextEffect=null;c.effectTag=8}}function c(c,d){if(!a)return null;for(;null!==d;)b(c,d),d=d.sibling;return null}function d(a,b){for(a=new Map;null!==b;)null!==b.key?a.set(b.key,b):a.set(b.index,b),b=b.sibling;return a}function e(a,b){a=Sg(a,b);a.index=0;a.sibling=null;return a}function f(b,c,d){b.index=d;if(!a)return c;d=b.alternate;if(null!==d)return d=d.index,d<c?(b.effectTag=
2,c):d;b.effectTag=2;return c}function g(b){a&&null===b.alternate&&(b.effectTag=2);return b}function h(a,b,c,d){if(null===b||6!==b.tag)return b=Tg(c,a.mode,d),b.return=a,b;b=e(b,c);b.return=a;return b}function k(a,b,c,d){if(null!==b&&b.elementType===c.type)return d=e(b,c.props),d.ref=Pg(a,b,c),d.return=a,d;d=Ug(c.type,c.key,c.props,null,a.mode,d);d.ref=Pg(a,b,c);d.return=a;return d}function l(a,b,c,d){if(null===b||4!==b.tag||b.stateNode.containerInfo!==c.containerInfo||b.stateNode.implementation!==
c.implementation)return b=Vg(c,a.mode,d),b.return=a,b;b=e(b,c.children||[]);b.return=a;return b}function m(a,b,c,d,f){if(null===b||7!==b.tag)return b=Wg(c,a.mode,d,f),b.return=a,b;b=e(b,c);b.return=a;return b}function p(a,b,c){if("string"===typeof b||"number"===typeof b)return b=Tg(""+b,a.mode,c),b.return=a,b;if("object"===typeof b&&null!==b){switch(b.$$typeof){case Za:return c=Ug(b.type,b.key,b.props,null,a.mode,c),c.ref=Pg(a,null,b),c.return=a,c;case $a:return b=Vg(b,a.mode,c),b.return=a,b}if(Og(b)||
nb(b))return b=Wg(b,a.mode,c,null),b.return=a,b;Qg(a,b)}return null}function x(a,b,c,d){var e=null!==b?b.key:null;if("string"===typeof c||"number"===typeof c)return null!==e?null:h(a,b,""+c,d);if("object"===typeof c&&null!==c){switch(c.$$typeof){case Za:return c.key===e?c.type===ab?m(a,b,c.props.children,d,e):k(a,b,c,d):null;case $a:return c.key===e?l(a,b,c,d):null}if(Og(c)||nb(c))return null!==e?null:m(a,b,c,d,null);Qg(a,c)}return null}function z(a,b,c,d,e){if("string"===typeof d||"number"===typeof d)return a=
a.get(c)||null,h(b,a,""+d,e);if("object"===typeof d&&null!==d){switch(d.$$typeof){case Za:return a=a.get(null===d.key?c:d.key)||null,d.type===ab?m(b,a,d.props.children,e,d.key):k(b,a,d,e);case $a:return a=a.get(null===d.key?c:d.key)||null,l(b,a,d,e)}if(Og(d)||nb(d))return a=a.get(c)||null,m(b,a,d,e,null);Qg(b,d)}return null}function ca(e,g,h,k){for(var l=null,t=null,m=g,y=g=0,A=null;null!==m&&y<h.length;y++){m.index>y?(A=m,m=null):A=m.sibling;var q=x(e,m,h[y],k);if(null===q){null===m&&(m=A);break}a&&
m&&null===q.alternate&&b(e,m);g=f(q,g,y);null===t?l=q:t.sibling=q;t=q;m=A}if(y===h.length)return c(e,m),l;if(null===m){for(;y<h.length;y++)m=p(e,h[y],k),null!==m&&(g=f(m,g,y),null===t?l=m:t.sibling=m,t=m);return l}for(m=d(e,m);y<h.length;y++)A=z(m,e,y,h[y],k),null!==A&&(a&&null!==A.alternate&&m.delete(null===A.key?y:A.key),g=f(A,g,y),null===t?l=A:t.sibling=A,t=A);a&&m.forEach(function(a){return b(e,a)});return l}function D(e,g,h,l){var k=nb(h);if("function"!==typeof k)throw Error(u(150));h=k.call(h);
if(null==h)throw Error(u(151));for(var m=k=null,t=g,y=g=0,A=null,q=h.next();null!==t&&!q.done;y++,q=h.next()){t.index>y?(A=t,t=null):A=t.sibling;var D=x(e,t,q.value,l);if(null===D){null===t&&(t=A);break}a&&t&&null===D.alternate&&b(e,t);g=f(D,g,y);null===m?k=D:m.sibling=D;m=D;t=A}if(q.done)return c(e,t),k;if(null===t){for(;!q.done;y++,q=h.next())q=p(e,q.value,l),null!==q&&(g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);return k}for(t=d(e,t);!q.done;y++,q=h.next())q=z(t,e,y,q.value,l),null!==q&&(a&&null!==
q.alternate&&t.delete(null===q.key?y:q.key),g=f(q,g,y),null===m?k=q:m.sibling=q,m=q);a&&t.forEach(function(a){return b(e,a)});return k}return function(a,d,f,h){var k="object"===typeof f&&null!==f&&f.type===ab&&null===f.key;k&&(f=f.props.children);var l="object"===typeof f&&null!==f;if(l)switch(f.$$typeof){case Za:a:{l=f.key;for(k=d;null!==k;){if(k.key===l){switch(k.tag){case 7:if(f.type===ab){c(a,k.sibling);d=e(k,f.props.children);d.return=a;a=d;break a}break;default:if(k.elementType===f.type){c(a,
k.sibling);d=e(k,f.props);d.ref=Pg(a,k,f);d.return=a;a=d;break a}}c(a,k);break}else b(a,k);k=k.sibling}f.type===ab?(d=Wg(f.props.children,a.mode,h,f.key),d.return=a,a=d):(h=Ug(f.type,f.key,f.props,null,a.mode,h),h.ref=Pg(a,d,f),h.return=a,a=h)}return g(a);case $a:a:{for(k=f.key;null!==d;){if(d.key===k)if(4===d.tag&&d.stateNode.containerInfo===f.containerInfo&&d.stateNode.implementation===f.implementation){c(a,d.sibling);d=e(d,f.children||[]);d.return=a;a=d;break a}else{c(a,d);break}else b(a,d);d=
d.sibling}d=Vg(f,a.mode,h);d.return=a;a=d}return g(a)}if("string"===typeof f||"number"===typeof f)return f=""+f,null!==d&&6===d.tag?(c(a,d.sibling),d=e(d,f),d.return=a,a=d):(c(a,d),d=Tg(f,a.mode,h),d.return=a,a=d),g(a);if(Og(f))return ca(a,d,f,h);if(nb(f))return D(a,d,f,h);l&&Qg(a,f);if("undefined"===typeof f&&!k)switch(a.tag){case 1:case 0:throw a=a.type,Error(u(152,a.displayName||a.name||"Component"));}return c(a,d)}}var Xg=Rg(!0),Yg=Rg(!1),Zg={},$g={current:Zg},ah={current:Zg},bh={current:Zg};
function ch(a){if(a===Zg)throw Error(u(174));return a}function dh(a,b){I(bh,b);I(ah,a);I($g,Zg);a=b.nodeType;switch(a){case 9:case 11:b=(b=b.documentElement)?b.namespaceURI:Ob(null,"");break;default:a=8===a?b.parentNode:b,b=a.namespaceURI||null,a=a.tagName,b=Ob(b,a)}H($g);I($g,b)}function eh(){H($g);H(ah);H(bh)}function fh(a){ch(bh.current);var b=ch($g.current);var c=Ob(b,a.type);b!==c&&(I(ah,a),I($g,c))}function gh(a){ah.current===a&&(H($g),H(ah))}var M={current:0};
function hh(a){for(var b=a;null!==b;){if(13===b.tag){var c=b.memoizedState;if(null!==c&&(c=c.dehydrated,null===c||c.data===Bd||c.data===Cd))return b}else if(19===b.tag&&void 0!==b.memoizedProps.revealOrder){if(0!==(b.effectTag&64))return b}else if(null!==b.child){b.child.return=b;b=b.child;continue}if(b===a)break;for(;null===b.sibling;){if(null===b.return||b.return===a)return null;b=b.return}b.sibling.return=b.return;b=b.sibling}return null}function ih(a,b){return{responder:a,props:b}}
var jh=Wa.ReactCurrentDispatcher,kh=Wa.ReactCurrentBatchConfig,lh=0,N=null,O=null,P=null,mh=!1;function Q(){throw Error(u(321));}function nh(a,b){if(null===b)return!1;for(var c=0;c<b.length&&c<a.length;c++)if(!$e(a[c],b[c]))return!1;return!0}
function oh(a,b,c,d,e,f){lh=f;N=b;b.memoizedState=null;b.updateQueue=null;b.expirationTime=0;jh.current=null===a||null===a.memoizedState?ph:qh;a=c(d,e);if(b.expirationTime===lh){f=0;do{b.expirationTime=0;if(!(25>f))throw Error(u(301));f+=1;P=O=null;b.updateQueue=null;jh.current=rh;a=c(d,e)}while(b.expirationTime===lh)}jh.current=sh;b=null!==O&&null!==O.next;lh=0;P=O=N=null;mh=!1;if(b)throw Error(u(300));return a}
function th(){var a={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};null===P?N.memoizedState=P=a:P=P.next=a;return P}function uh(){if(null===O){var a=N.alternate;a=null!==a?a.memoizedState:null}else a=O.next;var b=null===P?N.memoizedState:P.next;if(null!==b)P=b,O=a;else{if(null===a)throw Error(u(310));O=a;a={memoizedState:O.memoizedState,baseState:O.baseState,baseQueue:O.baseQueue,queue:O.queue,next:null};null===P?N.memoizedState=P=a:P=P.next=a}return P}
function vh(a,b){return"function"===typeof b?b(a):b}
function wh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=O,e=d.baseQueue,f=c.pending;if(null!==f){if(null!==e){var g=e.next;e.next=f.next;f.next=g}d.baseQueue=e=f;c.pending=null}if(null!==e){e=e.next;d=d.baseState;var h=g=f=null,k=e;do{var l=k.expirationTime;if(l<lh){var m={expirationTime:k.expirationTime,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null};null===h?(g=h=m,f=d):h=h.next=m;l>N.expirationTime&&
(N.expirationTime=l,Bg(l))}else null!==h&&(h=h.next={expirationTime:1073741823,suspenseConfig:k.suspenseConfig,action:k.action,eagerReducer:k.eagerReducer,eagerState:k.eagerState,next:null}),Ag(l,k.suspenseConfig),d=k.eagerReducer===a?k.eagerState:a(d,k.action);k=k.next}while(null!==k&&k!==e);null===h?f=d:h.next=g;$e(d,b.memoizedState)||(rg=!0);b.memoizedState=d;b.baseState=f;b.baseQueue=h;c.lastRenderedState=d}return[b.memoizedState,c.dispatch]}
function xh(a){var b=uh(),c=b.queue;if(null===c)throw Error(u(311));c.lastRenderedReducer=a;var d=c.dispatch,e=c.pending,f=b.memoizedState;if(null!==e){c.pending=null;var g=e=e.next;do f=a(f,g.action),g=g.next;while(g!==e);$e(f,b.memoizedState)||(rg=!0);b.memoizedState=f;null===b.baseQueue&&(b.baseState=f);c.lastRenderedState=f}return[f,d]}
function yh(a){var b=th();"function"===typeof a&&(a=a());b.memoizedState=b.baseState=a;a=b.queue={pending:null,dispatch:null,lastRenderedReducer:vh,lastRenderedState:a};a=a.dispatch=zh.bind(null,N,a);return[b.memoizedState,a]}function Ah(a,b,c,d){a={tag:a,create:b,destroy:c,deps:d,next:null};b=N.updateQueue;null===b?(b={lastEffect:null},N.updateQueue=b,b.lastEffect=a.next=a):(c=b.lastEffect,null===c?b.lastEffect=a.next=a:(d=c.next,c.next=a,a.next=d,b.lastEffect=a));return a}
function Bh(){return uh().memoizedState}function Ch(a,b,c,d){var e=th();N.effectTag|=a;e.memoizedState=Ah(1|b,c,void 0,void 0===d?null:d)}function Dh(a,b,c,d){var e=uh();d=void 0===d?null:d;var f=void 0;if(null!==O){var g=O.memoizedState;f=g.destroy;if(null!==d&&nh(d,g.deps)){Ah(b,c,f,d);return}}N.effectTag|=a;e.memoizedState=Ah(1|b,c,f,d)}function Eh(a,b){return Ch(516,4,a,b)}function Fh(a,b){return Dh(516,4,a,b)}function Gh(a,b){return Dh(4,2,a,b)}
function Hh(a,b){if("function"===typeof b)return a=a(),b(a),function(){b(null)};if(null!==b&&void 0!==b)return a=a(),b.current=a,function(){b.current=null}}function Ih(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Dh(4,2,Hh.bind(null,b,a),c)}function Jh(){}function Kh(a,b){th().memoizedState=[a,void 0===b?null:b];return a}function Lh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];c.memoizedState=[a,b];return a}
function Mh(a,b){var c=uh();b=void 0===b?null:b;var d=c.memoizedState;if(null!==d&&null!==b&&nh(b,d[1]))return d[0];a=a();c.memoizedState=[a,b];return a}function Nh(a,b,c){var d=ag();cg(98>d?98:d,function(){a(!0)});cg(97<d?97:d,function(){var d=kh.suspense;kh.suspense=void 0===b?null:b;try{a(!1),c()}finally{kh.suspense=d}})}
function zh(a,b,c){var d=Gg(),e=Dg.suspense;d=Hg(d,a,e);e={expirationTime:d,suspenseConfig:e,action:c,eagerReducer:null,eagerState:null,next:null};var f=b.pending;null===f?e.next=e:(e.next=f.next,f.next=e);b.pending=e;f=a.alternate;if(a===N||null!==f&&f===N)mh=!0,e.expirationTime=lh,N.expirationTime=lh;else{if(0===a.expirationTime&&(null===f||0===f.expirationTime)&&(f=b.lastRenderedReducer,null!==f))try{var g=b.lastRenderedState,h=f(g,c);e.eagerReducer=f;e.eagerState=h;if($e(h,g))return}catch(k){}finally{}Ig(a,
d)}}
var sh={readContext:sg,useCallback:Q,useContext:Q,useEffect:Q,useImperativeHandle:Q,useLayoutEffect:Q,useMemo:Q,useReducer:Q,useRef:Q,useState:Q,useDebugValue:Q,useResponder:Q,useDeferredValue:Q,useTransition:Q},ph={readContext:sg,useCallback:Kh,useContext:sg,useEffect:Eh,useImperativeHandle:function(a,b,c){c=null!==c&&void 0!==c?c.concat([a]):null;return Ch(4,2,Hh.bind(null,b,a),c)},useLayoutEffect:function(a,b){return Ch(4,2,a,b)},useMemo:function(a,b){var c=th();b=void 0===b?null:b;a=a();c.memoizedState=[a,
b];return a},useReducer:function(a,b,c){var d=th();b=void 0!==c?c(b):b;d.memoizedState=d.baseState=b;a=d.queue={pending:null,dispatch:null,lastRenderedReducer:a,lastRenderedState:b};a=a.dispatch=zh.bind(null,N,a);return[d.memoizedState,a]},useRef:function(a){var b=th();a={current:a};return b.memoizedState=a},useState:yh,useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=yh(a),d=c[0],e=c[1];Eh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=
c}},[a,b]);return d},useTransition:function(a){var b=yh(!1),c=b[0];b=b[1];return[Kh(Nh.bind(null,b,a),[b,a]),c]}},qh={readContext:sg,useCallback:Lh,useContext:sg,useEffect:Fh,useImperativeHandle:Ih,useLayoutEffect:Gh,useMemo:Mh,useReducer:wh,useRef:Bh,useState:function(){return wh(vh)},useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=wh(vh),d=c[0],e=c[1];Fh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=c}},[a,b]);return d},useTransition:function(a){var b=
wh(vh),c=b[0];b=b[1];return[Lh(Nh.bind(null,b,a),[b,a]),c]}},rh={readContext:sg,useCallback:Lh,useContext:sg,useEffect:Fh,useImperativeHandle:Ih,useLayoutEffect:Gh,useMemo:Mh,useReducer:xh,useRef:Bh,useState:function(){return xh(vh)},useDebugValue:Jh,useResponder:ih,useDeferredValue:function(a,b){var c=xh(vh),d=c[0],e=c[1];Fh(function(){var c=kh.suspense;kh.suspense=void 0===b?null:b;try{e(a)}finally{kh.suspense=c}},[a,b]);return d},useTransition:function(a){var b=xh(vh),c=b[0];b=b[1];return[Lh(Nh.bind(null,
b,a),[b,a]),c]}},Oh=null,Ph=null,Qh=!1;function Rh(a,b){var c=Sh(5,null,null,0);c.elementType="DELETED";c.type="DELETED";c.stateNode=b;c.return=a;c.effectTag=8;null!==a.lastEffect?(a.lastEffect.nextEffect=c,a.lastEffect=c):a.firstEffect=a.lastEffect=c}
function Th(a,b){switch(a.tag){case 5:var c=a.type;b=1!==b.nodeType||c.toLowerCase()!==b.nodeName.toLowerCase()?null:b;return null!==b?(a.stateNode=b,!0):!1;case 6:return b=""===a.pendingProps||3!==b.nodeType?null:b,null!==b?(a.stateNode=b,!0):!1;case 13:return!1;default:return!1}}
function Uh(a){if(Qh){var b=Ph;if(b){var c=b;if(!Th(a,b)){b=Jd(c.nextSibling);if(!b||!Th(a,b)){a.effectTag=a.effectTag&-1025|2;Qh=!1;Oh=a;return}Rh(Oh,c)}Oh=a;Ph=Jd(b.firstChild)}else a.effectTag=a.effectTag&-1025|2,Qh=!1,Oh=a}}function Vh(a){for(a=a.return;null!==a&&5!==a.tag&&3!==a.tag&&13!==a.tag;)a=a.return;Oh=a}
function Wh(a){if(a!==Oh)return!1;if(!Qh)return Vh(a),Qh=!0,!1;var b=a.type;if(5!==a.tag||"head"!==b&&"body"!==b&&!Gd(b,a.memoizedProps))for(b=Ph;b;)Rh(a,b),b=Jd(b.nextSibling);Vh(a);if(13===a.tag){a=a.memoizedState;a=null!==a?a.dehydrated:null;if(!a)throw Error(u(317));a:{a=a.nextSibling;for(b=0;a;){if(8===a.nodeType){var c=a.data;if(c===Ad){if(0===b){Ph=Jd(a.nextSibling);break a}b--}else c!==zd&&c!==Cd&&c!==Bd||b++}a=a.nextSibling}Ph=null}}else Ph=Oh?Jd(a.stateNode.nextSibling):null;return!0}
function Xh(){Ph=Oh=null;Qh=!1}var Yh=Wa.ReactCurrentOwner,rg=!1;function R(a,b,c,d){b.child=null===a?Yg(b,null,c,d):Xg(b,a.child,c,d)}function Zh(a,b,c,d,e){c=c.render;var f=b.ref;qg(b,e);d=oh(a,b,c,d,f,e);if(null!==a&&!rg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),$h(a,b,e);b.effectTag|=1;R(a,b,d,e);return b.child}
function ai(a,b,c,d,e,f){if(null===a){var g=c.type;if("function"===typeof g&&!bi(g)&&void 0===g.defaultProps&&null===c.compare&&void 0===c.defaultProps)return b.tag=15,b.type=g,ci(a,b,g,d,e,f);a=Ug(c.type,null,d,null,b.mode,f);a.ref=b.ref;a.return=b;return b.child=a}g=a.child;if(e<f&&(e=g.memoizedProps,c=c.compare,c=null!==c?c:bf,c(e,d)&&a.ref===b.ref))return $h(a,b,f);b.effectTag|=1;a=Sg(g,d);a.ref=b.ref;a.return=b;return b.child=a}
function ci(a,b,c,d,e,f){return null!==a&&bf(a.memoizedProps,d)&&a.ref===b.ref&&(rg=!1,e<f)?(b.expirationTime=a.expirationTime,$h(a,b,f)):di(a,b,c,d,f)}function ei(a,b){var c=b.ref;if(null===a&&null!==c||null!==a&&a.ref!==c)b.effectTag|=128}function di(a,b,c,d,e){var f=L(c)?Bf:J.current;f=Cf(b,f);qg(b,e);c=oh(a,b,c,d,f,e);if(null!==a&&!rg)return b.updateQueue=a.updateQueue,b.effectTag&=-517,a.expirationTime<=e&&(a.expirationTime=0),$h(a,b,e);b.effectTag|=1;R(a,b,c,e);return b.child}
function fi(a,b,c,d,e){if(L(c)){var f=!0;Gf(b)}else f=!1;qg(b,e);if(null===b.stateNode)null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),Lg(b,c,d),Ng(b,c,d,e),d=!0;else if(null===a){var g=b.stateNode,h=b.memoizedProps;g.props=h;var k=g.context,l=c.contextType;"object"===typeof l&&null!==l?l=sg(l):(l=L(c)?Bf:J.current,l=Cf(b,l));var m=c.getDerivedStateFromProps,p="function"===typeof m||"function"===typeof g.getSnapshotBeforeUpdate;p||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&
"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Mg(b,g,d,l);tg=!1;var x=b.memoizedState;g.state=x;zg(b,d,g,e);k=b.memoizedState;h!==d||x!==k||K.current||tg?("function"===typeof m&&(Fg(b,c,m,d),k=b.memoizedState),(h=tg||Kg(b,c,h,d,x,k,l))?(p||"function"!==typeof g.UNSAFE_componentWillMount&&"function"!==typeof g.componentWillMount||("function"===typeof g.componentWillMount&&g.componentWillMount(),"function"===typeof g.UNSAFE_componentWillMount&&g.UNSAFE_componentWillMount()),"function"===
typeof g.componentDidMount&&(b.effectTag|=4)):("function"===typeof g.componentDidMount&&(b.effectTag|=4),b.memoizedProps=d,b.memoizedState=k),g.props=d,g.state=k,g.context=l,d=h):("function"===typeof g.componentDidMount&&(b.effectTag|=4),d=!1)}else g=b.stateNode,vg(a,b),h=b.memoizedProps,g.props=b.type===b.elementType?h:ig(b.type,h),k=g.context,l=c.contextType,"object"===typeof l&&null!==l?l=sg(l):(l=L(c)?Bf:J.current,l=Cf(b,l)),m=c.getDerivedStateFromProps,(p="function"===typeof m||"function"===
typeof g.getSnapshotBeforeUpdate)||"function"!==typeof g.UNSAFE_componentWillReceiveProps&&"function"!==typeof g.componentWillReceiveProps||(h!==d||k!==l)&&Mg(b,g,d,l),tg=!1,k=b.memoizedState,g.state=k,zg(b,d,g,e),x=b.memoizedState,h!==d||k!==x||K.current||tg?("function"===typeof m&&(Fg(b,c,m,d),x=b.memoizedState),(m=tg||Kg(b,c,h,d,k,x,l))?(p||"function"!==typeof g.UNSAFE_componentWillUpdate&&"function"!==typeof g.componentWillUpdate||("function"===typeof g.componentWillUpdate&&g.componentWillUpdate(d,
x,l),"function"===typeof g.UNSAFE_componentWillUpdate&&g.UNSAFE_componentWillUpdate(d,x,l)),"function"===typeof g.componentDidUpdate&&(b.effectTag|=4),"function"===typeof g.getSnapshotBeforeUpdate&&(b.effectTag|=256)):("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),b.memoizedProps=d,b.memoizedState=x),g.props=d,g.state=x,g.context=l,d=m):
("function"!==typeof g.componentDidUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=4),"function"!==typeof g.getSnapshotBeforeUpdate||h===a.memoizedProps&&k===a.memoizedState||(b.effectTag|=256),d=!1);return gi(a,b,c,d,f,e)}
function gi(a,b,c,d,e,f){ei(a,b);var g=0!==(b.effectTag&64);if(!d&&!g)return e&&Hf(b,c,!1),$h(a,b,f);d=b.stateNode;Yh.current=b;var h=g&&"function"!==typeof c.getDerivedStateFromError?null:d.render();b.effectTag|=1;null!==a&&g?(b.child=Xg(b,a.child,null,f),b.child=Xg(b,null,h,f)):R(a,b,h,f);b.memoizedState=d.state;e&&Hf(b,c,!0);return b.child}function hi(a){var b=a.stateNode;b.pendingContext?Ef(a,b.pendingContext,b.pendingContext!==b.context):b.context&&Ef(a,b.context,!1);dh(a,b.containerInfo)}
var ii={dehydrated:null,retryTime:0};
function ji(a,b,c){var d=b.mode,e=b.pendingProps,f=M.current,g=!1,h;(h=0!==(b.effectTag&64))||(h=0!==(f&2)&&(null===a||null!==a.memoizedState));h?(g=!0,b.effectTag&=-65):null!==a&&null===a.memoizedState||void 0===e.fallback||!0===e.unstable_avoidThisFallback||(f|=1);I(M,f&1);if(null===a){void 0!==e.fallback&&Uh(b);if(g){g=e.fallback;e=Wg(null,d,0,null);e.return=b;if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==a;)a.return=e,a=a.sibling;c=Wg(g,d,c,null);c.return=
b;e.sibling=c;b.memoizedState=ii;b.child=e;return c}d=e.children;b.memoizedState=null;return b.child=Yg(b,null,d,c)}if(null!==a.memoizedState){a=a.child;d=a.sibling;if(g){e=e.fallback;c=Sg(a,a.pendingProps);c.return=b;if(0===(b.mode&2)&&(g=null!==b.memoizedState?b.child.child:b.child,g!==a.child))for(c.child=g;null!==g;)g.return=c,g=g.sibling;d=Sg(d,e);d.return=b;c.sibling=d;c.childExpirationTime=0;b.memoizedState=ii;b.child=c;return d}c=Xg(b,a.child,e.children,c);b.memoizedState=null;return b.child=
c}a=a.child;if(g){g=e.fallback;e=Wg(null,d,0,null);e.return=b;e.child=a;null!==a&&(a.return=e);if(0===(b.mode&2))for(a=null!==b.memoizedState?b.child.child:b.child,e.child=a;null!==a;)a.return=e,a=a.sibling;c=Wg(g,d,c,null);c.return=b;e.sibling=c;c.effectTag|=2;e.childExpirationTime=0;b.memoizedState=ii;b.child=e;return c}b.memoizedState=null;return b.child=Xg(b,a,e.children,c)}
function ki(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);pg(a.return,b)}function li(a,b,c,d,e,f){var g=a.memoizedState;null===g?a.memoizedState={isBackwards:b,rendering:null,renderingStartTime:0,last:d,tail:c,tailExpiration:0,tailMode:e,lastEffect:f}:(g.isBackwards=b,g.rendering=null,g.renderingStartTime=0,g.last=d,g.tail=c,g.tailExpiration=0,g.tailMode=e,g.lastEffect=f)}
function mi(a,b,c){var d=b.pendingProps,e=d.revealOrder,f=d.tail;R(a,b,d.children,c);d=M.current;if(0!==(d&2))d=d&1|2,b.effectTag|=64;else{if(null!==a&&0!==(a.effectTag&64))a:for(a=b.child;null!==a;){if(13===a.tag)null!==a.memoizedState&&ki(a,c);else if(19===a.tag)ki(a,c);else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===b)break a;for(;null===a.sibling;){if(null===a.return||a.return===b)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}d&=1}I(M,d);if(0===(b.mode&2))b.memoizedState=
null;else switch(e){case "forwards":c=b.child;for(e=null;null!==c;)a=c.alternate,null!==a&&null===hh(a)&&(e=c),c=c.sibling;c=e;null===c?(e=b.child,b.child=null):(e=c.sibling,c.sibling=null);li(b,!1,e,c,f,b.lastEffect);break;case "backwards":c=null;e=b.child;for(b.child=null;null!==e;){a=e.alternate;if(null!==a&&null===hh(a)){b.child=e;break}a=e.sibling;e.sibling=c;c=e;e=a}li(b,!0,c,null,f,b.lastEffect);break;case "together":li(b,!1,null,null,void 0,b.lastEffect);break;default:b.memoizedState=null}return b.child}
function $h(a,b,c){null!==a&&(b.dependencies=a.dependencies);var d=b.expirationTime;0!==d&&Bg(d);if(b.childExpirationTime<c)return null;if(null!==a&&b.child!==a.child)throw Error(u(153));if(null!==b.child){a=b.child;c=Sg(a,a.pendingProps);b.child=c;for(c.return=b;null!==a.sibling;)a=a.sibling,c=c.sibling=Sg(a,a.pendingProps),c.return=b;c.sibling=null}return b.child}var ni,oi,pi,qi;
ni=function(a,b){for(var c=b.child;null!==c;){if(5===c.tag||6===c.tag)a.appendChild(c.stateNode);else if(4!==c.tag&&null!==c.child){c.child.return=c;c=c.child;continue}if(c===b)break;for(;null===c.sibling;){if(null===c.return||c.return===b)return;c=c.return}c.sibling.return=c.return;c=c.sibling}};oi=function(){};
pi=function(a,b,c,d,e){var f=a.memoizedProps;if(f!==d){var g=b.stateNode;ch($g.current);a=null;switch(c){case "input":f=zb(g,f);d=zb(g,d);a=[];break;case "option":f=Gb(g,f);d=Gb(g,d);a=[];break;case "select":f=n({},f,{value:void 0});d=n({},d,{value:void 0});a=[];break;case "textarea":f=Ib(g,f);d=Ib(g,d);a=[];break;default:"function"!==typeof f.onClick&&"function"===typeof d.onClick&&(g.onclick=sd)}od(c,d);var h,k;c=null;for(h in f)if(!d.hasOwnProperty(h)&&f.hasOwnProperty(h)&&null!=f[h])if("style"===
h)for(k in g=f[h],g)g.hasOwnProperty(k)&&(c||(c={}),c[k]="");else"dangerouslySetInnerHTML"!==h&&"children"!==h&&"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&"autoFocus"!==h&&(va.hasOwnProperty(h)?a||(a=[]):(a=a||[]).push(h,null));for(h in d){var l=d[h];g=null!=f?f[h]:void 0;if(d.hasOwnProperty(h)&&l!==g&&(null!=l||null!=g))if("style"===h)if(g){for(k in g)!g.hasOwnProperty(k)||l&&l.hasOwnProperty(k)||(c||(c={}),c[k]="");for(k in l)l.hasOwnProperty(k)&&g[k]!==l[k]&&(c||(c={}),
c[k]=l[k])}else c||(a||(a=[]),a.push(h,c)),c=l;else"dangerouslySetInnerHTML"===h?(l=l?l.__html:void 0,g=g?g.__html:void 0,null!=l&&g!==l&&(a=a||[]).push(h,l)):"children"===h?g===l||"string"!==typeof l&&"number"!==typeof l||(a=a||[]).push(h,""+l):"suppressContentEditableWarning"!==h&&"suppressHydrationWarning"!==h&&(va.hasOwnProperty(h)?(null!=l&&rd(e,h),a||g===l||(a=[])):(a=a||[]).push(h,l))}c&&(a=a||[]).push("style",c);e=a;if(b.updateQueue=e)b.effectTag|=4}};
qi=function(a,b,c,d){c!==d&&(b.effectTag|=4)};function ri(a,b){switch(a.tailMode){case "hidden":b=a.tail;for(var c=null;null!==b;)null!==b.alternate&&(c=b),b=b.sibling;null===c?a.tail=null:c.sibling=null;break;case "collapsed":c=a.tail;for(var d=null;null!==c;)null!==c.alternate&&(d=c),c=c.sibling;null===d?b||null===a.tail?a.tail=null:a.tail.sibling=null:d.sibling=null}}
function si(a,b,c){var d=b.pendingProps;switch(b.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return null;case 1:return L(b.type)&&Df(),null;case 3:return eh(),H(K),H(J),c=b.stateNode,c.pendingContext&&(c.context=c.pendingContext,c.pendingContext=null),null!==a&&null!==a.child||!Wh(b)||(b.effectTag|=4),oi(b),null;case 5:gh(b);c=ch(bh.current);var e=b.type;if(null!==a&&null!=b.stateNode)pi(a,b,e,d,c),a.ref!==b.ref&&(b.effectTag|=128);else{if(!d){if(null===b.stateNode)throw Error(u(166));
return null}a=ch($g.current);if(Wh(b)){d=b.stateNode;e=b.type;var f=b.memoizedProps;d[Md]=b;d[Nd]=f;switch(e){case "iframe":case "object":case "embed":F("load",d);break;case "video":case "audio":for(a=0;a<ac.length;a++)F(ac[a],d);break;case "source":F("error",d);break;case "img":case "image":case "link":F("error",d);F("load",d);break;case "form":F("reset",d);F("submit",d);break;case "details":F("toggle",d);break;case "input":Ab(d,f);F("invalid",d);rd(c,"onChange");break;case "select":d._wrapperState=
{wasMultiple:!!f.multiple};F("invalid",d);rd(c,"onChange");break;case "textarea":Jb(d,f),F("invalid",d),rd(c,"onChange")}od(e,f);a=null;for(var g in f)if(f.hasOwnProperty(g)){var h=f[g];"children"===g?"string"===typeof h?d.textContent!==h&&(a=["children",h]):"number"===typeof h&&d.textContent!==""+h&&(a=["children",""+h]):va.hasOwnProperty(g)&&null!=h&&rd(c,g)}switch(e){case "input":xb(d);Eb(d,f,!0);break;case "textarea":xb(d);Lb(d);break;case "select":case "option":break;default:"function"===typeof f.onClick&&
(d.onclick=sd)}c=a;b.updateQueue=c;null!==c&&(b.effectTag|=4)}else{g=9===c.nodeType?c:c.ownerDocument;a===qd&&(a=Nb(e));a===qd?"script"===e?(a=g.createElement("div"),a.innerHTML="<script>\x3c/script>",a=a.removeChild(a.firstChild)):"string"===typeof d.is?a=g.createElement(e,{is:d.is}):(a=g.createElement(e),"select"===e&&(g=a,d.multiple?g.multiple=!0:d.size&&(g.size=d.size))):a=g.createElementNS(a,e);a[Md]=b;a[Nd]=d;ni(a,b,!1,!1);b.stateNode=a;g=pd(e,d);switch(e){case "iframe":case "object":case "embed":F("load",
a);h=d;break;case "video":case "audio":for(h=0;h<ac.length;h++)F(ac[h],a);h=d;break;case "source":F("error",a);h=d;break;case "img":case "image":case "link":F("error",a);F("load",a);h=d;break;case "form":F("reset",a);F("submit",a);h=d;break;case "details":F("toggle",a);h=d;break;case "input":Ab(a,d);h=zb(a,d);F("invalid",a);rd(c,"onChange");break;case "option":h=Gb(a,d);break;case "select":a._wrapperState={wasMultiple:!!d.multiple};h=n({},d,{value:void 0});F("invalid",a);rd(c,"onChange");break;case "textarea":Jb(a,
d);h=Ib(a,d);F("invalid",a);rd(c,"onChange");break;default:h=d}od(e,h);var k=h;for(f in k)if(k.hasOwnProperty(f)){var l=k[f];"style"===f?md(a,l):"dangerouslySetInnerHTML"===f?(l=l?l.__html:void 0,null!=l&&Qb(a,l)):"children"===f?"string"===typeof l?("textarea"!==e||""!==l)&&Rb(a,l):"number"===typeof l&&Rb(a,""+l):"suppressContentEditableWarning"!==f&&"suppressHydrationWarning"!==f&&"autoFocus"!==f&&(va.hasOwnProperty(f)?null!=l&&rd(c,f):null!=l&&Xa(a,f,l,g))}switch(e){case "input":xb(a);Eb(a,d,!1);
break;case "textarea":xb(a);Lb(a);break;case "option":null!=d.value&&a.setAttribute("value",""+rb(d.value));break;case "select":a.multiple=!!d.multiple;c=d.value;null!=c?Hb(a,!!d.multiple,c,!1):null!=d.defaultValue&&Hb(a,!!d.multiple,d.defaultValue,!0);break;default:"function"===typeof h.onClick&&(a.onclick=sd)}Fd(e,d)&&(b.effectTag|=4)}null!==b.ref&&(b.effectTag|=128)}return null;case 6:if(a&&null!=b.stateNode)qi(a,b,a.memoizedProps,d);else{if("string"!==typeof d&&null===b.stateNode)throw Error(u(166));
c=ch(bh.current);ch($g.current);Wh(b)?(c=b.stateNode,d=b.memoizedProps,c[Md]=b,c.nodeValue!==d&&(b.effectTag|=4)):(c=(9===c.nodeType?c:c.ownerDocument).createTextNode(d),c[Md]=b,b.stateNode=c)}return null;case 13:H(M);d=b.memoizedState;if(0!==(b.effectTag&64))return b.expirationTime=c,b;c=null!==d;d=!1;null===a?void 0!==b.memoizedProps.fallback&&Wh(b):(e=a.memoizedState,d=null!==e,c||null===e||(e=a.child.sibling,null!==e&&(f=b.firstEffect,null!==f?(b.firstEffect=e,e.nextEffect=f):(b.firstEffect=b.lastEffect=
e,e.nextEffect=null),e.effectTag=8)));if(c&&!d&&0!==(b.mode&2))if(null===a&&!0!==b.memoizedProps.unstable_avoidThisFallback||0!==(M.current&1))S===ti&&(S=ui);else{if(S===ti||S===ui)S=vi;0!==wi&&null!==T&&(xi(T,U),yi(T,wi))}if(c||d)b.effectTag|=4;return null;case 4:return eh(),oi(b),null;case 10:return og(b),null;case 17:return L(b.type)&&Df(),null;case 19:H(M);d=b.memoizedState;if(null===d)return null;e=0!==(b.effectTag&64);f=d.rendering;if(null===f)if(e)ri(d,!1);else{if(S!==ti||null!==a&&0!==(a.effectTag&
64))for(f=b.child;null!==f;){a=hh(f);if(null!==a){b.effectTag|=64;ri(d,!1);e=a.updateQueue;null!==e&&(b.updateQueue=e,b.effectTag|=4);null===d.lastEffect&&(b.firstEffect=null);b.lastEffect=d.lastEffect;for(d=b.child;null!==d;)e=d,f=c,e.effectTag&=2,e.nextEffect=null,e.firstEffect=null,e.lastEffect=null,a=e.alternate,null===a?(e.childExpirationTime=0,e.expirationTime=f,e.child=null,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null):(e.childExpirationTime=a.childExpirationTime,
e.expirationTime=a.expirationTime,e.child=a.child,e.memoizedProps=a.memoizedProps,e.memoizedState=a.memoizedState,e.updateQueue=a.updateQueue,f=a.dependencies,e.dependencies=null===f?null:{expirationTime:f.expirationTime,firstContext:f.firstContext,responders:f.responders}),d=d.sibling;I(M,M.current&1|2);return b.child}f=f.sibling}}else{if(!e)if(a=hh(f),null!==a){if(b.effectTag|=64,e=!0,c=a.updateQueue,null!==c&&(b.updateQueue=c,b.effectTag|=4),ri(d,!0),null===d.tail&&"hidden"===d.tailMode&&!f.alternate)return b=
b.lastEffect=d.lastEffect,null!==b&&(b.nextEffect=null),null}else 2*$f()-d.renderingStartTime>d.tailExpiration&&1<c&&(b.effectTag|=64,e=!0,ri(d,!1),b.expirationTime=b.childExpirationTime=c-1);d.isBackwards?(f.sibling=b.child,b.child=f):(c=d.last,null!==c?c.sibling=f:b.child=f,d.last=f)}return null!==d.tail?(0===d.tailExpiration&&(d.tailExpiration=$f()+500),c=d.tail,d.rendering=c,d.tail=c.sibling,d.lastEffect=b.lastEffect,d.renderingStartTime=$f(),c.sibling=null,b=M.current,I(M,e?b&1|2:b&1),c):null}throw Error(u(156,
b.tag));}function zi(a){switch(a.tag){case 1:L(a.type)&&Df();var b=a.effectTag;return b&4096?(a.effectTag=b&-4097|64,a):null;case 3:eh();H(K);H(J);b=a.effectTag;if(0!==(b&64))throw Error(u(285));a.effectTag=b&-4097|64;return a;case 5:return gh(a),null;case 13:return H(M),b=a.effectTag,b&4096?(a.effectTag=b&-4097|64,a):null;case 19:return H(M),null;case 4:return eh(),null;case 10:return og(a),null;default:return null}}function Ai(a,b){return{value:a,source:b,stack:qb(b)}}
var Bi="function"===typeof WeakSet?WeakSet:Set;function Ci(a,b){var c=b.source,d=b.stack;null===d&&null!==c&&(d=qb(c));null!==c&&pb(c.type);b=b.value;null!==a&&1===a.tag&&pb(a.type);try{console.error(b)}catch(e){setTimeout(function(){throw e;})}}function Di(a,b){try{b.props=a.memoizedProps,b.state=a.memoizedState,b.componentWillUnmount()}catch(c){Ei(a,c)}}function Fi(a){var b=a.ref;if(null!==b)if("function"===typeof b)try{b(null)}catch(c){Ei(a,c)}else b.current=null}
function Gi(a,b){switch(b.tag){case 0:case 11:case 15:case 22:return;case 1:if(b.effectTag&256&&null!==a){var c=a.memoizedProps,d=a.memoizedState;a=b.stateNode;b=a.getSnapshotBeforeUpdate(b.elementType===b.type?c:ig(b.type,c),d);a.__reactInternalSnapshotBeforeUpdate=b}return;case 3:case 5:case 6:case 4:case 17:return}throw Error(u(163));}
function Hi(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.destroy;c.destroy=void 0;void 0!==d&&d()}c=c.next}while(c!==b)}}function Ii(a,b){b=b.updateQueue;b=null!==b?b.lastEffect:null;if(null!==b){var c=b=b.next;do{if((c.tag&a)===a){var d=c.create;c.destroy=d()}c=c.next}while(c!==b)}}
function Ji(a,b,c){switch(c.tag){case 0:case 11:case 15:case 22:Ii(3,c);return;case 1:a=c.stateNode;if(c.effectTag&4)if(null===b)a.componentDidMount();else{var d=c.elementType===c.type?b.memoizedProps:ig(c.type,b.memoizedProps);a.componentDidUpdate(d,b.memoizedState,a.__reactInternalSnapshotBeforeUpdate)}b=c.updateQueue;null!==b&&Cg(c,b,a);return;case 3:b=c.updateQueue;if(null!==b){a=null;if(null!==c.child)switch(c.child.tag){case 5:a=c.child.stateNode;break;case 1:a=c.child.stateNode}Cg(c,b,a)}return;
case 5:a=c.stateNode;null===b&&c.effectTag&4&&Fd(c.type,c.memoizedProps)&&a.focus();return;case 6:return;case 4:return;case 12:return;case 13:null===c.memoizedState&&(c=c.alternate,null!==c&&(c=c.memoizedState,null!==c&&(c=c.dehydrated,null!==c&&Vc(c))));return;case 19:case 17:case 20:case 21:return}throw Error(u(163));}
function Ki(a,b,c){"function"===typeof Li&&Li(b);switch(b.tag){case 0:case 11:case 14:case 15:case 22:a=b.updateQueue;if(null!==a&&(a=a.lastEffect,null!==a)){var d=a.next;cg(97<c?97:c,function(){var a=d;do{var c=a.destroy;if(void 0!==c){var g=b;try{c()}catch(h){Ei(g,h)}}a=a.next}while(a!==d)})}break;case 1:Fi(b);c=b.stateNode;"function"===typeof c.componentWillUnmount&&Di(b,c);break;case 5:Fi(b);break;case 4:Mi(a,b,c)}}
function Ni(a){var b=a.alternate;a.return=null;a.child=null;a.memoizedState=null;a.updateQueue=null;a.dependencies=null;a.alternate=null;a.firstEffect=null;a.lastEffect=null;a.pendingProps=null;a.memoizedProps=null;a.stateNode=null;null!==b&&Ni(b)}function Oi(a){return 5===a.tag||3===a.tag||4===a.tag}
function Pi(a){a:{for(var b=a.return;null!==b;){if(Oi(b)){var c=b;break a}b=b.return}throw Error(u(160));}b=c.stateNode;switch(c.tag){case 5:var d=!1;break;case 3:b=b.containerInfo;d=!0;break;case 4:b=b.containerInfo;d=!0;break;default:throw Error(u(161));}c.effectTag&16&&(Rb(b,""),c.effectTag&=-17);a:b:for(c=a;;){for(;null===c.sibling;){if(null===c.return||Oi(c.return)){c=null;break a}c=c.return}c.sibling.return=c.return;for(c=c.sibling;5!==c.tag&&6!==c.tag&&18!==c.tag;){if(c.effectTag&2)continue b;
if(null===c.child||4===c.tag)continue b;else c.child.return=c,c=c.child}if(!(c.effectTag&2)){c=c.stateNode;break a}}d?Qi(a,c,b):Ri(a,c,b)}
function Qi(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?8===c.nodeType?c.parentNode.insertBefore(a,b):c.insertBefore(a,b):(8===c.nodeType?(b=c.parentNode,b.insertBefore(a,c)):(b=c,b.appendChild(a)),c=c._reactRootContainer,null!==c&&void 0!==c||null!==b.onclick||(b.onclick=sd));else if(4!==d&&(a=a.child,null!==a))for(Qi(a,b,c),a=a.sibling;null!==a;)Qi(a,b,c),a=a.sibling}
function Ri(a,b,c){var d=a.tag,e=5===d||6===d;if(e)a=e?a.stateNode:a.stateNode.instance,b?c.insertBefore(a,b):c.appendChild(a);else if(4!==d&&(a=a.child,null!==a))for(Ri(a,b,c),a=a.sibling;null!==a;)Ri(a,b,c),a=a.sibling}
function Mi(a,b,c){for(var d=b,e=!1,f,g;;){if(!e){e=d.return;a:for(;;){if(null===e)throw Error(u(160));f=e.stateNode;switch(e.tag){case 5:g=!1;break a;case 3:f=f.containerInfo;g=!0;break a;case 4:f=f.containerInfo;g=!0;break a}e=e.return}e=!0}if(5===d.tag||6===d.tag){a:for(var h=a,k=d,l=c,m=k;;)if(Ki(h,m,l),null!==m.child&&4!==m.tag)m.child.return=m,m=m.child;else{if(m===k)break a;for(;null===m.sibling;){if(null===m.return||m.return===k)break a;m=m.return}m.sibling.return=m.return;m=m.sibling}g?(h=
f,k=d.stateNode,8===h.nodeType?h.parentNode.removeChild(k):h.removeChild(k)):f.removeChild(d.stateNode)}else if(4===d.tag){if(null!==d.child){f=d.stateNode.containerInfo;g=!0;d.child.return=d;d=d.child;continue}}else if(Ki(a,d,c),null!==d.child){d.child.return=d;d=d.child;continue}if(d===b)break;for(;null===d.sibling;){if(null===d.return||d.return===b)return;d=d.return;4===d.tag&&(e=!1)}d.sibling.return=d.return;d=d.sibling}}
function Si(a,b){switch(b.tag){case 0:case 11:case 14:case 15:case 22:Hi(3,b);return;case 1:return;case 5:var c=b.stateNode;if(null!=c){var d=b.memoizedProps,e=null!==a?a.memoizedProps:d;a=b.type;var f=b.updateQueue;b.updateQueue=null;if(null!==f){c[Nd]=d;"input"===a&&"radio"===d.type&&null!=d.name&&Bb(c,d);pd(a,e);b=pd(a,d);for(e=0;e<f.length;e+=2){var g=f[e],h=f[e+1];"style"===g?md(c,h):"dangerouslySetInnerHTML"===g?Qb(c,h):"children"===g?Rb(c,h):Xa(c,g,h,b)}switch(a){case "input":Cb(c,d);break;
case "textarea":Kb(c,d);break;case "select":b=c._wrapperState.wasMultiple,c._wrapperState.wasMultiple=!!d.multiple,a=d.value,null!=a?Hb(c,!!d.multiple,a,!1):b!==!!d.multiple&&(null!=d.defaultValue?Hb(c,!!d.multiple,d.defaultValue,!0):Hb(c,!!d.multiple,d.multiple?[]:"",!1))}}}return;case 6:if(null===b.stateNode)throw Error(u(162));b.stateNode.nodeValue=b.memoizedProps;return;case 3:b=b.stateNode;b.hydrate&&(b.hydrate=!1,Vc(b.containerInfo));return;case 12:return;case 13:c=b;null===b.memoizedState?
d=!1:(d=!0,c=b.child,Ti=$f());if(null!==c)a:for(a=c;;){if(5===a.tag)f=a.stateNode,d?(f=f.style,"function"===typeof f.setProperty?f.setProperty("display","none","important"):f.display="none"):(f=a.stateNode,e=a.memoizedProps.style,e=void 0!==e&&null!==e&&e.hasOwnProperty("display")?e.display:null,f.style.display=ld("display",e));else if(6===a.tag)a.stateNode.nodeValue=d?"":a.memoizedProps;else if(13===a.tag&&null!==a.memoizedState&&null===a.memoizedState.dehydrated){f=a.child.sibling;f.return=a;a=
f;continue}else if(null!==a.child){a.child.return=a;a=a.child;continue}if(a===c)break;for(;null===a.sibling;){if(null===a.return||a.return===c)break a;a=a.return}a.sibling.return=a.return;a=a.sibling}Ui(b);return;case 19:Ui(b);return;case 17:return}throw Error(u(163));}function Ui(a){var b=a.updateQueue;if(null!==b){a.updateQueue=null;var c=a.stateNode;null===c&&(c=a.stateNode=new Bi);b.forEach(function(b){var d=Vi.bind(null,a,b);c.has(b)||(c.add(b),b.then(d,d))})}}
var Wi="function"===typeof WeakMap?WeakMap:Map;function Xi(a,b,c){c=wg(c,null);c.tag=3;c.payload={element:null};var d=b.value;c.callback=function(){Yi||(Yi=!0,Zi=d);Ci(a,b)};return c}
function $i(a,b,c){c=wg(c,null);c.tag=3;var d=a.type.getDerivedStateFromError;if("function"===typeof d){var e=b.value;c.payload=function(){Ci(a,b);return d(e)}}var f=a.stateNode;null!==f&&"function"===typeof f.componentDidCatch&&(c.callback=function(){"function"!==typeof d&&(null===aj?aj=new Set([this]):aj.add(this),Ci(a,b));var c=b.stack;this.componentDidCatch(b.value,{componentStack:null!==c?c:""})});return c}
var bj=Math.ceil,cj=Wa.ReactCurrentDispatcher,dj=Wa.ReactCurrentOwner,V=0,ej=8,fj=16,gj=32,ti=0,hj=1,ij=2,ui=3,vi=4,jj=5,W=V,T=null,X=null,U=0,S=ti,kj=null,lj=1073741823,mj=1073741823,nj=null,wi=0,oj=!1,Ti=0,pj=500,Y=null,Yi=!1,Zi=null,aj=null,qj=!1,rj=null,sj=90,tj=null,uj=0,vj=null,wj=0;function Gg(){return(W&(fj|gj))!==V?1073741821-($f()/10|0):0!==wj?wj:wj=1073741821-($f()/10|0)}
function Hg(a,b,c){b=b.mode;if(0===(b&2))return 1073741823;var d=ag();if(0===(b&4))return 99===d?1073741823:1073741822;if((W&fj)!==V)return U;if(null!==c)a=hg(a,c.timeoutMs|0||5E3,250);else switch(d){case 99:a=1073741823;break;case 98:a=hg(a,150,100);break;case 97:case 96:a=hg(a,5E3,250);break;case 95:a=2;break;default:throw Error(u(326));}null!==T&&a===U&&--a;return a}
function Ig(a,b){if(50<uj)throw uj=0,vj=null,Error(u(185));a=xj(a,b);if(null!==a){var c=ag();1073741823===b?(W&ej)!==V&&(W&(fj|gj))===V?yj(a):(Z(a),W===V&&gg()):Z(a);(W&4)===V||98!==c&&99!==c||(null===tj?tj=new Map([[a,b]]):(c=tj.get(a),(void 0===c||c>b)&&tj.set(a,b)))}}
function xj(a,b){a.expirationTime<b&&(a.expirationTime=b);var c=a.alternate;null!==c&&c.expirationTime<b&&(c.expirationTime=b);var d=a.return,e=null;if(null===d&&3===a.tag)e=a.stateNode;else for(;null!==d;){c=d.alternate;d.childExpirationTime<b&&(d.childExpirationTime=b);null!==c&&c.childExpirationTime<b&&(c.childExpirationTime=b);if(null===d.return&&3===d.tag){e=d.stateNode;break}d=d.return}null!==e&&(T===e&&(Bg(b),S===vi&&xi(e,U)),yi(e,b));return e}
function zj(a){var b=a.lastExpiredTime;if(0!==b)return b;b=a.firstPendingTime;if(!Aj(a,b))return b;var c=a.lastPingedTime;a=a.nextKnownPendingLevel;a=c>a?c:a;return 2>=a&&b!==a?0:a}
function Z(a){if(0!==a.lastExpiredTime)a.callbackExpirationTime=1073741823,a.callbackPriority=99,a.callbackNode=eg(yj.bind(null,a));else{var b=zj(a),c=a.callbackNode;if(0===b)null!==c&&(a.callbackNode=null,a.callbackExpirationTime=0,a.callbackPriority=90);else{var d=Gg();1073741823===b?d=99:1===b||2===b?d=95:(d=10*(1073741821-b)-10*(1073741821-d),d=0>=d?99:250>=d?98:5250>=d?97:95);if(null!==c){var e=a.callbackPriority;if(a.callbackExpirationTime===b&&e>=d)return;c!==Tf&&Kf(c)}a.callbackExpirationTime=
b;a.callbackPriority=d;b=1073741823===b?eg(yj.bind(null,a)):dg(d,Bj.bind(null,a),{timeout:10*(1073741821-b)-$f()});a.callbackNode=b}}}
function Bj(a,b){wj=0;if(b)return b=Gg(),Cj(a,b),Z(a),null;var c=zj(a);if(0!==c){b=a.callbackNode;if((W&(fj|gj))!==V)throw Error(u(327));Dj();a===T&&c===U||Ej(a,c);if(null!==X){var d=W;W|=fj;var e=Fj();do try{Gj();break}catch(h){Hj(a,h)}while(1);ng();W=d;cj.current=e;if(S===hj)throw b=kj,Ej(a,c),xi(a,c),Z(a),b;if(null===X)switch(e=a.finishedWork=a.current.alternate,a.finishedExpirationTime=c,d=S,T=null,d){case ti:case hj:throw Error(u(345));case ij:Cj(a,2<c?2:c);break;case ui:xi(a,c);d=a.lastSuspendedTime;
c===d&&(a.nextKnownPendingLevel=Ij(e));if(1073741823===lj&&(e=Ti+pj-$f(),10<e)){if(oj){var f=a.lastPingedTime;if(0===f||f>=c){a.lastPingedTime=c;Ej(a,c);break}}f=zj(a);if(0!==f&&f!==c)break;if(0!==d&&d!==c){a.lastPingedTime=d;break}a.timeoutHandle=Hd(Jj.bind(null,a),e);break}Jj(a);break;case vi:xi(a,c);d=a.lastSuspendedTime;c===d&&(a.nextKnownPendingLevel=Ij(e));if(oj&&(e=a.lastPingedTime,0===e||e>=c)){a.lastPingedTime=c;Ej(a,c);break}e=zj(a);if(0!==e&&e!==c)break;if(0!==d&&d!==c){a.lastPingedTime=
d;break}1073741823!==mj?d=10*(1073741821-mj)-$f():1073741823===lj?d=0:(d=10*(1073741821-lj)-5E3,e=$f(),c=10*(1073741821-c)-e,d=e-d,0>d&&(d=0),d=(120>d?120:480>d?480:1080>d?1080:1920>d?1920:3E3>d?3E3:4320>d?4320:1960*bj(d/1960))-d,c<d&&(d=c));if(10<d){a.timeoutHandle=Hd(Jj.bind(null,a),d);break}Jj(a);break;case jj:if(1073741823!==lj&&null!==nj){f=lj;var g=nj;d=g.busyMinDurationMs|0;0>=d?d=0:(e=g.busyDelayMs|0,f=$f()-(10*(1073741821-f)-(g.timeoutMs|0||5E3)),d=f<=e?0:e+d-f);if(10<d){xi(a,c);a.timeoutHandle=
Hd(Jj.bind(null,a),d);break}}Jj(a);break;default:throw Error(u(329));}Z(a);if(a.callbackNode===b)return Bj.bind(null,a)}}return null}
function yj(a){var b=a.lastExpiredTime;b=0!==b?b:1073741823;if((W&(fj|gj))!==V)throw Error(u(327));Dj();a===T&&b===U||Ej(a,b);if(null!==X){var c=W;W|=fj;var d=Fj();do try{Kj();break}catch(e){Hj(a,e)}while(1);ng();W=c;cj.current=d;if(S===hj)throw c=kj,Ej(a,b),xi(a,b),Z(a),c;if(null!==X)throw Error(u(261));a.finishedWork=a.current.alternate;a.finishedExpirationTime=b;T=null;Jj(a);Z(a)}return null}function Lj(){if(null!==tj){var a=tj;tj=null;a.forEach(function(a,c){Cj(c,a);Z(c)});gg()}}
function Mj(a,b){var c=W;W|=1;try{return a(b)}finally{W=c,W===V&&gg()}}function Nj(a,b){var c=W;W&=-2;W|=ej;try{return a(b)}finally{W=c,W===V&&gg()}}
function Ej(a,b){a.finishedWork=null;a.finishedExpirationTime=0;var c=a.timeoutHandle;-1!==c&&(a.timeoutHandle=-1,Id(c));if(null!==X)for(c=X.return;null!==c;){var d=c;switch(d.tag){case 1:d=d.type.childContextTypes;null!==d&&void 0!==d&&Df();break;case 3:eh();H(K);H(J);break;case 5:gh(d);break;case 4:eh();break;case 13:H(M);break;case 19:H(M);break;case 10:og(d)}c=c.return}T=a;X=Sg(a.current,null);U=b;S=ti;kj=null;mj=lj=1073741823;nj=null;wi=0;oj=!1}
function Hj(a,b){do{try{ng();jh.current=sh;if(mh)for(var c=N.memoizedState;null!==c;){var d=c.queue;null!==d&&(d.pending=null);c=c.next}lh=0;P=O=N=null;mh=!1;if(null===X||null===X.return)return S=hj,kj=b,X=null;a:{var e=a,f=X.return,g=X,h=b;b=U;g.effectTag|=2048;g.firstEffect=g.lastEffect=null;if(null!==h&&"object"===typeof h&&"function"===typeof h.then){var k=h;if(0===(g.mode&2)){var l=g.alternate;l?(g.updateQueue=l.updateQueue,g.memoizedState=l.memoizedState,g.expirationTime=l.expirationTime):(g.updateQueue=
null,g.memoizedState=null)}var m=0!==(M.current&1),p=f;do{var x;if(x=13===p.tag){var z=p.memoizedState;if(null!==z)x=null!==z.dehydrated?!0:!1;else{var ca=p.memoizedProps;x=void 0===ca.fallback?!1:!0!==ca.unstable_avoidThisFallback?!0:m?!1:!0}}if(x){var D=p.updateQueue;if(null===D){var t=new Set;t.add(k);p.updateQueue=t}else D.add(k);if(0===(p.mode&2)){p.effectTag|=64;g.effectTag&=-2981;if(1===g.tag)if(null===g.alternate)g.tag=17;else{var y=wg(1073741823,null);y.tag=2;xg(g,y)}g.expirationTime=1073741823;
break a}h=void 0;g=b;var A=e.pingCache;null===A?(A=e.pingCache=new Wi,h=new Set,A.set(k,h)):(h=A.get(k),void 0===h&&(h=new Set,A.set(k,h)));if(!h.has(g)){h.add(g);var q=Oj.bind(null,e,k,g);k.then(q,q)}p.effectTag|=4096;p.expirationTime=b;break a}p=p.return}while(null!==p);h=Error((pb(g.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+qb(g))}S!==
jj&&(S=ij);h=Ai(h,g);p=f;do{switch(p.tag){case 3:k=h;p.effectTag|=4096;p.expirationTime=b;var B=Xi(p,k,b);yg(p,B);break a;case 1:k=h;var w=p.type,ub=p.stateNode;if(0===(p.effectTag&64)&&("function"===typeof w.getDerivedStateFromError||null!==ub&&"function"===typeof ub.componentDidCatch&&(null===aj||!aj.has(ub)))){p.effectTag|=4096;p.expirationTime=b;var vb=$i(p,k,b);yg(p,vb);break a}}p=p.return}while(null!==p)}X=Pj(X)}catch(Xc){b=Xc;continue}break}while(1)}
function Fj(){var a=cj.current;cj.current=sh;return null===a?sh:a}function Ag(a,b){a<lj&&2<a&&(lj=a);null!==b&&a<mj&&2<a&&(mj=a,nj=b)}function Bg(a){a>wi&&(wi=a)}function Kj(){for(;null!==X;)X=Qj(X)}function Gj(){for(;null!==X&&!Uf();)X=Qj(X)}function Qj(a){var b=Rj(a.alternate,a,U);a.memoizedProps=a.pendingProps;null===b&&(b=Pj(a));dj.current=null;return b}
function Pj(a){X=a;do{var b=X.alternate;a=X.return;if(0===(X.effectTag&2048)){b=si(b,X,U);if(1===U||1!==X.childExpirationTime){for(var c=0,d=X.child;null!==d;){var e=d.expirationTime,f=d.childExpirationTime;e>c&&(c=e);f>c&&(c=f);d=d.sibling}X.childExpirationTime=c}if(null!==b)return b;null!==a&&0===(a.effectTag&2048)&&(null===a.firstEffect&&(a.firstEffect=X.firstEffect),null!==X.lastEffect&&(null!==a.lastEffect&&(a.lastEffect.nextEffect=X.firstEffect),a.lastEffect=X.lastEffect),1<X.effectTag&&(null!==
a.lastEffect?a.lastEffect.nextEffect=X:a.firstEffect=X,a.lastEffect=X))}else{b=zi(X);if(null!==b)return b.effectTag&=2047,b;null!==a&&(a.firstEffect=a.lastEffect=null,a.effectTag|=2048)}b=X.sibling;if(null!==b)return b;X=a}while(null!==X);S===ti&&(S=jj);return null}function Ij(a){var b=a.expirationTime;a=a.childExpirationTime;return b>a?b:a}function Jj(a){var b=ag();cg(99,Sj.bind(null,a,b));return null}
function Sj(a,b){do Dj();while(null!==rj);if((W&(fj|gj))!==V)throw Error(u(327));var c=a.finishedWork,d=a.finishedExpirationTime;if(null===c)return null;a.finishedWork=null;a.finishedExpirationTime=0;if(c===a.current)throw Error(u(177));a.callbackNode=null;a.callbackExpirationTime=0;a.callbackPriority=90;a.nextKnownPendingLevel=0;var e=Ij(c);a.firstPendingTime=e;d<=a.lastSuspendedTime?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:d<=a.firstSuspendedTime&&(a.firstSuspendedTime=
d-1);d<=a.lastPingedTime&&(a.lastPingedTime=0);d<=a.lastExpiredTime&&(a.lastExpiredTime=0);a===T&&(X=T=null,U=0);1<c.effectTag?null!==c.lastEffect?(c.lastEffect.nextEffect=c,e=c.firstEffect):e=c:e=c.firstEffect;if(null!==e){var f=W;W|=gj;dj.current=null;Dd=fd;var g=xd();if(yd(g)){if("selectionStart"in g)var h={start:g.selectionStart,end:g.selectionEnd};else a:{h=(h=g.ownerDocument)&&h.defaultView||window;var k=h.getSelection&&h.getSelection();if(k&&0!==k.rangeCount){h=k.anchorNode;var l=k.anchorOffset,
m=k.focusNode;k=k.focusOffset;try{h.nodeType,m.nodeType}catch(wb){h=null;break a}var p=0,x=-1,z=-1,ca=0,D=0,t=g,y=null;b:for(;;){for(var A;;){t!==h||0!==l&&3!==t.nodeType||(x=p+l);t!==m||0!==k&&3!==t.nodeType||(z=p+k);3===t.nodeType&&(p+=t.nodeValue.length);if(null===(A=t.firstChild))break;y=t;t=A}for(;;){if(t===g)break b;y===h&&++ca===l&&(x=p);y===m&&++D===k&&(z=p);if(null!==(A=t.nextSibling))break;t=y;y=t.parentNode}t=A}h=-1===x||-1===z?null:{start:x,end:z}}else h=null}h=h||{start:0,end:0}}else h=
null;Ed={activeElementDetached:null,focusedElem:g,selectionRange:h};fd=!1;Y=e;do try{Tj()}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb);Y=Y.nextEffect}while(null!==Y);Y=e;do try{for(g=a,h=b;null!==Y;){var q=Y.effectTag;q&16&&Rb(Y.stateNode,"");if(q&128){var B=Y.alternate;if(null!==B){var w=B.ref;null!==w&&("function"===typeof w?w(null):w.current=null)}}switch(q&1038){case 2:Pi(Y);Y.effectTag&=-3;break;case 6:Pi(Y);Y.effectTag&=-3;Si(Y.alternate,Y);break;case 1024:Y.effectTag&=-1025;break;case 1028:Y.effectTag&=
-1025;Si(Y.alternate,Y);break;case 4:Si(Y.alternate,Y);break;case 8:l=Y,Mi(g,l,h),Ni(l)}Y=Y.nextEffect}}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb);Y=Y.nextEffect}while(null!==Y);w=Ed;B=xd();q=w.focusedElem;h=w.selectionRange;if(B!==q&&q&&q.ownerDocument&&wd(q.ownerDocument.documentElement,q)){null!==h&&yd(q)&&(B=h.start,w=h.end,void 0===w&&(w=B),"selectionStart"in q?(q.selectionStart=B,q.selectionEnd=Math.min(w,q.value.length)):(w=(B=q.ownerDocument||document)&&B.defaultView||window,w.getSelection&&
(w=w.getSelection(),l=q.textContent.length,g=Math.min(h.start,l),h=void 0===h.end?g:Math.min(h.end,l),!w.extend&&g>h&&(l=h,h=g,g=l),l=vd(q,g),m=vd(q,h),l&&m&&(1!==w.rangeCount||w.anchorNode!==l.node||w.anchorOffset!==l.offset||w.focusNode!==m.node||w.focusOffset!==m.offset)&&(B=B.createRange(),B.setStart(l.node,l.offset),w.removeAllRanges(),g>h?(w.addRange(B),w.extend(m.node,m.offset)):(B.setEnd(m.node,m.offset),w.addRange(B))))));B=[];for(w=q;w=w.parentNode;)1===w.nodeType&&B.push({element:w,left:w.scrollLeft,
top:w.scrollTop});"function"===typeof q.focus&&q.focus();for(q=0;q<B.length;q++)w=B[q],w.element.scrollLeft=w.left,w.element.scrollTop=w.top}fd=!!Dd;Ed=Dd=null;a.current=c;Y=e;do try{for(q=a;null!==Y;){var ub=Y.effectTag;ub&36&&Ji(q,Y.alternate,Y);if(ub&128){B=void 0;var vb=Y.ref;if(null!==vb){var Xc=Y.stateNode;switch(Y.tag){case 5:B=Xc;break;default:B=Xc}"function"===typeof vb?vb(B):vb.current=B}}Y=Y.nextEffect}}catch(wb){if(null===Y)throw Error(u(330));Ei(Y,wb);Y=Y.nextEffect}while(null!==Y);Y=
null;Vf();W=f}else a.current=c;if(qj)qj=!1,rj=a,sj=b;else for(Y=e;null!==Y;)b=Y.nextEffect,Y.nextEffect=null,Y=b;b=a.firstPendingTime;0===b&&(aj=null);1073741823===b?a===vj?uj++:(uj=0,vj=a):uj=0;"function"===typeof Uj&&Uj(c.stateNode,d);Z(a);if(Yi)throw Yi=!1,a=Zi,Zi=null,a;if((W&ej)!==V)return null;gg();return null}function Tj(){for(;null!==Y;){var a=Y.effectTag;0!==(a&256)&&Gi(Y.alternate,Y);0===(a&512)||qj||(qj=!0,dg(97,function(){Dj();return null}));Y=Y.nextEffect}}
function Dj(){if(90!==sj){var a=97<sj?97:sj;sj=90;return cg(a,Vj)}}function Vj(){if(null===rj)return!1;var a=rj;rj=null;if((W&(fj|gj))!==V)throw Error(u(331));var b=W;W|=gj;for(a=a.current.firstEffect;null!==a;){try{var c=a;if(0!==(c.effectTag&512))switch(c.tag){case 0:case 11:case 15:case 22:Hi(5,c),Ii(5,c)}}catch(d){if(null===a)throw Error(u(330));Ei(a,d)}c=a.nextEffect;a.nextEffect=null;a=c}W=b;gg();return!0}
function Wj(a,b,c){b=Ai(c,b);b=Xi(a,b,1073741823);xg(a,b);a=xj(a,1073741823);null!==a&&Z(a)}function Ei(a,b){if(3===a.tag)Wj(a,a,b);else for(var c=a.return;null!==c;){if(3===c.tag){Wj(c,a,b);break}else if(1===c.tag){var d=c.stateNode;if("function"===typeof c.type.getDerivedStateFromError||"function"===typeof d.componentDidCatch&&(null===aj||!aj.has(d))){a=Ai(b,a);a=$i(c,a,1073741823);xg(c,a);c=xj(c,1073741823);null!==c&&Z(c);break}}c=c.return}}
function Oj(a,b,c){var d=a.pingCache;null!==d&&d.delete(b);T===a&&U===c?S===vi||S===ui&&1073741823===lj&&$f()-Ti<pj?Ej(a,U):oj=!0:Aj(a,c)&&(b=a.lastPingedTime,0!==b&&b<c||(a.lastPingedTime=c,Z(a)))}function Vi(a,b){var c=a.stateNode;null!==c&&c.delete(b);b=0;0===b&&(b=Gg(),b=Hg(b,a,null));a=xj(a,b);null!==a&&Z(a)}var Rj;
Rj=function(a,b,c){var d=b.expirationTime;if(null!==a){var e=b.pendingProps;if(a.memoizedProps!==e||K.current)rg=!0;else{if(d<c){rg=!1;switch(b.tag){case 3:hi(b);Xh();break;case 5:fh(b);if(b.mode&4&&1!==c&&e.hidden)return b.expirationTime=b.childExpirationTime=1,null;break;case 1:L(b.type)&&Gf(b);break;case 4:dh(b,b.stateNode.containerInfo);break;case 10:d=b.memoizedProps.value;e=b.type._context;I(jg,e._currentValue);e._currentValue=d;break;case 13:if(null!==b.memoizedState){d=b.child.childExpirationTime;
if(0!==d&&d>=c)return ji(a,b,c);I(M,M.current&1);b=$h(a,b,c);return null!==b?b.sibling:null}I(M,M.current&1);break;case 19:d=b.childExpirationTime>=c;if(0!==(a.effectTag&64)){if(d)return mi(a,b,c);b.effectTag|=64}e=b.memoizedState;null!==e&&(e.rendering=null,e.tail=null);I(M,M.current);if(!d)return null}return $h(a,b,c)}rg=!1}}else rg=!1;b.expirationTime=0;switch(b.tag){case 2:d=b.type;null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;e=Cf(b,J.current);qg(b,c);e=oh(null,
b,d,a,e,c);b.effectTag|=1;if("object"===typeof e&&null!==e&&"function"===typeof e.render&&void 0===e.$$typeof){b.tag=1;b.memoizedState=null;b.updateQueue=null;if(L(d)){var f=!0;Gf(b)}else f=!1;b.memoizedState=null!==e.state&&void 0!==e.state?e.state:null;ug(b);var g=d.getDerivedStateFromProps;"function"===typeof g&&Fg(b,d,g,a);e.updater=Jg;b.stateNode=e;e._reactInternalFiber=b;Ng(b,d,a,c);b=gi(null,b,d,!0,f,c)}else b.tag=0,R(null,b,e,c),b=b.child;return b;case 16:a:{e=b.elementType;null!==a&&(a.alternate=
null,b.alternate=null,b.effectTag|=2);a=b.pendingProps;ob(e);if(1!==e._status)throw e._result;e=e._result;b.type=e;f=b.tag=Xj(e);a=ig(e,a);switch(f){case 0:b=di(null,b,e,a,c);break a;case 1:b=fi(null,b,e,a,c);break a;case 11:b=Zh(null,b,e,a,c);break a;case 14:b=ai(null,b,e,ig(e.type,a),d,c);break a}throw Error(u(306,e,""));}return b;case 0:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),di(a,b,d,e,c);case 1:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),fi(a,b,d,e,c);
case 3:hi(b);d=b.updateQueue;if(null===a||null===d)throw Error(u(282));d=b.pendingProps;e=b.memoizedState;e=null!==e?e.element:null;vg(a,b);zg(b,d,null,c);d=b.memoizedState.element;if(d===e)Xh(),b=$h(a,b,c);else{if(e=b.stateNode.hydrate)Ph=Jd(b.stateNode.containerInfo.firstChild),Oh=b,e=Qh=!0;if(e)for(c=Yg(b,null,d,c),b.child=c;c;)c.effectTag=c.effectTag&-3|1024,c=c.sibling;else R(a,b,d,c),Xh();b=b.child}return b;case 5:return fh(b),null===a&&Uh(b),d=b.type,e=b.pendingProps,f=null!==a?a.memoizedProps:
null,g=e.children,Gd(d,e)?g=null:null!==f&&Gd(d,f)&&(b.effectTag|=16),ei(a,b),b.mode&4&&1!==c&&e.hidden?(b.expirationTime=b.childExpirationTime=1,b=null):(R(a,b,g,c),b=b.child),b;case 6:return null===a&&Uh(b),null;case 13:return ji(a,b,c);case 4:return dh(b,b.stateNode.containerInfo),d=b.pendingProps,null===a?b.child=Xg(b,null,d,c):R(a,b,d,c),b.child;case 11:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),Zh(a,b,d,e,c);case 7:return R(a,b,b.pendingProps,c),b.child;case 8:return R(a,
b,b.pendingProps.children,c),b.child;case 12:return R(a,b,b.pendingProps.children,c),b.child;case 10:a:{d=b.type._context;e=b.pendingProps;g=b.memoizedProps;f=e.value;var h=b.type._context;I(jg,h._currentValue);h._currentValue=f;if(null!==g)if(h=g.value,f=$e(h,f)?0:("function"===typeof d._calculateChangedBits?d._calculateChangedBits(h,f):1073741823)|0,0===f){if(g.children===e.children&&!K.current){b=$h(a,b,c);break a}}else for(h=b.child,null!==h&&(h.return=b);null!==h;){var k=h.dependencies;if(null!==
k){g=h.child;for(var l=k.firstContext;null!==l;){if(l.context===d&&0!==(l.observedBits&f)){1===h.tag&&(l=wg(c,null),l.tag=2,xg(h,l));h.expirationTime<c&&(h.expirationTime=c);l=h.alternate;null!==l&&l.expirationTime<c&&(l.expirationTime=c);pg(h.return,c);k.expirationTime<c&&(k.expirationTime=c);break}l=l.next}}else g=10===h.tag?h.type===b.type?null:h.child:h.child;if(null!==g)g.return=h;else for(g=h;null!==g;){if(g===b){g=null;break}h=g.sibling;if(null!==h){h.return=g.return;g=h;break}g=g.return}h=
g}R(a,b,e.children,c);b=b.child}return b;case 9:return e=b.type,f=b.pendingProps,d=f.children,qg(b,c),e=sg(e,f.unstable_observedBits),d=d(e),b.effectTag|=1,R(a,b,d,c),b.child;case 14:return e=b.type,f=ig(e,b.pendingProps),f=ig(e.type,f),ai(a,b,e,f,d,c);case 15:return ci(a,b,b.type,b.pendingProps,d,c);case 17:return d=b.type,e=b.pendingProps,e=b.elementType===d?e:ig(d,e),null!==a&&(a.alternate=null,b.alternate=null,b.effectTag|=2),b.tag=1,L(d)?(a=!0,Gf(b)):a=!1,qg(b,c),Lg(b,d,e),Ng(b,d,e,c),gi(null,
b,d,!0,a,c);case 19:return mi(a,b,c)}throw Error(u(156,b.tag));};var Uj=null,Li=null;function Yj(a){if("undefined"===typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var b=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(b.isDisabled||!b.supportsFiber)return!0;try{var c=b.inject(a);Uj=function(a){try{b.onCommitFiberRoot(c,a,void 0,64===(a.current.effectTag&64))}catch(e){}};Li=function(a){try{b.onCommitFiberUnmount(c,a)}catch(e){}}}catch(d){}return!0}
function Zj(a,b,c,d){this.tag=a;this.key=c;this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null;this.index=0;this.ref=null;this.pendingProps=b;this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null;this.mode=d;this.effectTag=0;this.lastEffect=this.firstEffect=this.nextEffect=null;this.childExpirationTime=this.expirationTime=0;this.alternate=null}function Sh(a,b,c,d){return new Zj(a,b,c,d)}
function bi(a){a=a.prototype;return!(!a||!a.isReactComponent)}function Xj(a){if("function"===typeof a)return bi(a)?1:0;if(void 0!==a&&null!==a){a=a.$$typeof;if(a===gb)return 11;if(a===jb)return 14}return 2}
function Sg(a,b){var c=a.alternate;null===c?(c=Sh(a.tag,b,a.key,a.mode),c.elementType=a.elementType,c.type=a.type,c.stateNode=a.stateNode,c.alternate=a,a.alternate=c):(c.pendingProps=b,c.effectTag=0,c.nextEffect=null,c.firstEffect=null,c.lastEffect=null);c.childExpirationTime=a.childExpirationTime;c.expirationTime=a.expirationTime;c.child=a.child;c.memoizedProps=a.memoizedProps;c.memoizedState=a.memoizedState;c.updateQueue=a.updateQueue;b=a.dependencies;c.dependencies=null===b?null:{expirationTime:b.expirationTime,
firstContext:b.firstContext,responders:b.responders};c.sibling=a.sibling;c.index=a.index;c.ref=a.ref;return c}
function Ug(a,b,c,d,e,f){var g=2;d=a;if("function"===typeof a)bi(a)&&(g=1);else if("string"===typeof a)g=5;else a:switch(a){case ab:return Wg(c.children,e,f,b);case fb:g=8;e|=7;break;case bb:g=8;e|=1;break;case cb:return a=Sh(12,c,b,e|8),a.elementType=cb,a.type=cb,a.expirationTime=f,a;case hb:return a=Sh(13,c,b,e),a.type=hb,a.elementType=hb,a.expirationTime=f,a;case ib:return a=Sh(19,c,b,e),a.elementType=ib,a.expirationTime=f,a;default:if("object"===typeof a&&null!==a)switch(a.$$typeof){case db:g=
10;break a;case eb:g=9;break a;case gb:g=11;break a;case jb:g=14;break a;case kb:g=16;d=null;break a;case lb:g=22;break a}throw Error(u(130,null==a?a:typeof a,""));}b=Sh(g,c,b,e);b.elementType=a;b.type=d;b.expirationTime=f;return b}function Wg(a,b,c,d){a=Sh(7,a,d,b);a.expirationTime=c;return a}function Tg(a,b,c){a=Sh(6,a,null,b);a.expirationTime=c;return a}
function Vg(a,b,c){b=Sh(4,null!==a.children?a.children:[],a.key,b);b.expirationTime=c;b.stateNode={containerInfo:a.containerInfo,pendingChildren:null,implementation:a.implementation};return b}
function ak(a,b,c){this.tag=b;this.current=null;this.containerInfo=a;this.pingCache=this.pendingChildren=null;this.finishedExpirationTime=0;this.finishedWork=null;this.timeoutHandle=-1;this.pendingContext=this.context=null;this.hydrate=c;this.callbackNode=null;this.callbackPriority=90;this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}
function Aj(a,b){var c=a.firstSuspendedTime;a=a.lastSuspendedTime;return 0!==c&&c>=b&&a<=b}function xi(a,b){var c=a.firstSuspendedTime,d=a.lastSuspendedTime;c<b&&(a.firstSuspendedTime=b);if(d>b||0===c)a.lastSuspendedTime=b;b<=a.lastPingedTime&&(a.lastPingedTime=0);b<=a.lastExpiredTime&&(a.lastExpiredTime=0)}
function yi(a,b){b>a.firstPendingTime&&(a.firstPendingTime=b);var c=a.firstSuspendedTime;0!==c&&(b>=c?a.firstSuspendedTime=a.lastSuspendedTime=a.nextKnownPendingLevel=0:b>=a.lastSuspendedTime&&(a.lastSuspendedTime=b+1),b>a.nextKnownPendingLevel&&(a.nextKnownPendingLevel=b))}function Cj(a,b){var c=a.lastExpiredTime;if(0===c||c>b)a.lastExpiredTime=b}
function bk(a,b,c,d){var e=b.current,f=Gg(),g=Dg.suspense;f=Hg(f,e,g);a:if(c){c=c._reactInternalFiber;b:{if(dc(c)!==c||1!==c.tag)throw Error(u(170));var h=c;do{switch(h.tag){case 3:h=h.stateNode.context;break b;case 1:if(L(h.type)){h=h.stateNode.__reactInternalMemoizedMergedChildContext;break b}}h=h.return}while(null!==h);throw Error(u(171));}if(1===c.tag){var k=c.type;if(L(k)){c=Ff(c,k,h);break a}}c=h}else c=Af;null===b.context?b.context=c:b.pendingContext=c;b=wg(f,g);b.payload={element:a};d=void 0===
d?null:d;null!==d&&(b.callback=d);xg(e,b);Ig(e,f);return f}function ck(a){a=a.current;if(!a.child)return null;switch(a.child.tag){case 5:return a.child.stateNode;default:return a.child.stateNode}}function dk(a,b){a=a.memoizedState;null!==a&&null!==a.dehydrated&&a.retryTime<b&&(a.retryTime=b)}function ek(a,b){dk(a,b);(a=a.alternate)&&dk(a,b)}
function fk(a,b,c){c=null!=c&&!0===c.hydrate;var d=new ak(a,b,c),e=Sh(3,null,null,2===b?7:1===b?3:0);d.current=e;e.stateNode=d;ug(e);a[Od]=d.current;c&&0!==b&&Jc(a,9===a.nodeType?a:a.ownerDocument);this._internalRoot=d}fk.prototype.render=function(a){bk(a,this._internalRoot,null,null)};fk.prototype.unmount=function(){var a=this._internalRoot,b=a.containerInfo;bk(null,a,null,function(){b[Od]=null})};
function gk(a){return!(!a||1!==a.nodeType&&9!==a.nodeType&&11!==a.nodeType&&(8!==a.nodeType||" react-mount-point-unstable "!==a.nodeValue))}function hk(a,b){b||(b=a?9===a.nodeType?a.documentElement:a.firstChild:null,b=!(!b||1!==b.nodeType||!b.hasAttribute("data-reactroot")));if(!b)for(var c;c=a.lastChild;)a.removeChild(c);return new fk(a,0,b?{hydrate:!0}:void 0)}
function ik(a,b,c,d,e){var f=c._reactRootContainer;if(f){var g=f._internalRoot;if("function"===typeof e){var h=e;e=function(){var a=ck(g);h.call(a)}}bk(b,g,a,e)}else{f=c._reactRootContainer=hk(c,d);g=f._internalRoot;if("function"===typeof e){var k=e;e=function(){var a=ck(g);k.call(a)}}Nj(function(){bk(b,g,a,e)})}return ck(g)}function jk(a,b,c){var d=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:$a,key:null==d?null:""+d,children:a,containerInfo:b,implementation:c}}
wc=function(a){if(13===a.tag){var b=hg(Gg(),150,100);Ig(a,b);ek(a,b)}};xc=function(a){13===a.tag&&(Ig(a,3),ek(a,3))};yc=function(a){if(13===a.tag){var b=Gg();b=Hg(b,a,null);Ig(a,b);ek(a,b)}};
za=function(a,b,c){switch(b){case "input":Cb(a,c);b=c.name;if("radio"===c.type&&null!=b){for(c=a;c.parentNode;)c=c.parentNode;c=c.querySelectorAll("input[name="+JSON.stringify(""+b)+'][type="radio"]');for(b=0;b<c.length;b++){var d=c[b];if(d!==a&&d.form===a.form){var e=Qd(d);if(!e)throw Error(u(90));yb(d);Cb(d,e)}}}break;case "textarea":Kb(a,c);break;case "select":b=c.value,null!=b&&Hb(a,!!c.multiple,b,!1)}};Fa=Mj;
Ga=function(a,b,c,d,e){var f=W;W|=4;try{return cg(98,a.bind(null,b,c,d,e))}finally{W=f,W===V&&gg()}};Ha=function(){(W&(1|fj|gj))===V&&(Lj(),Dj())};Ia=function(a,b){var c=W;W|=2;try{return a(b)}finally{W=c,W===V&&gg()}};function kk(a,b){var c=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;if(!gk(b))throw Error(u(200));return jk(a,b,null,c)}var lk={Events:[Nc,Pd,Qd,xa,ta,Xd,function(a){jc(a,Wd)},Da,Ea,id,mc,Dj,{current:!1}]};
(function(a){var b=a.findFiberByHostInstance;return Yj(n({},a,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Wa.ReactCurrentDispatcher,findHostInstanceByFiber:function(a){a=hc(a);return null===a?null:a.stateNode},findFiberByHostInstance:function(a){return b?b(a):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null}))})({findFiberByHostInstance:tc,bundleType:0,version:"16.13.1",
rendererPackageName:"react-dom"});exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=lk;exports.createPortal=kk;exports.findDOMNode=function(a){if(null==a)return null;if(1===a.nodeType)return a;var b=a._reactInternalFiber;if(void 0===b){if("function"===typeof a.render)throw Error(u(188));throw Error(u(268,Object.keys(a)));}a=hc(b);a=null===a?null:a.stateNode;return a};
exports.flushSync=function(a,b){if((W&(fj|gj))!==V)throw Error(u(187));var c=W;W|=1;try{return cg(99,a.bind(null,b))}finally{W=c,gg()}};exports.hydrate=function(a,b,c){if(!gk(b))throw Error(u(200));return ik(null,a,b,!0,c)};exports.render=function(a,b,c){if(!gk(b))throw Error(u(200));return ik(null,a,b,!1,c)};
exports.unmountComponentAtNode=function(a){if(!gk(a))throw Error(u(40));return a._reactRootContainer?(Nj(function(){ik(null,null,a,!1,function(){a._reactRootContainer=null;a[Od]=null})}),!0):!1};exports.unstable_batchedUpdates=Mj;exports.unstable_createPortal=function(a,b){return kk(a,b,2<arguments.length&&void 0!==arguments[2]?arguments[2]:null)};
exports.unstable_renderSubtreeIntoContainer=function(a,b,c,d){if(!gk(c))throw Error(u(200));if(null==a||void 0===a._reactInternalFiber)throw Error(u(38));return ik(a,b,c,!1,d)};exports.version="16.13.1";


/***/ }),
/* 423 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


if (true) {
  module.exports = __webpack_require__(424);
} else {}


/***/ }),
/* 424 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/** @license React v0.19.1
 * scheduler.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

var f,g,h,k,l;
if("undefined"===typeof window||"function"!==typeof MessageChannel){var p=null,q=null,t=function(){if(null!==p)try{var a=exports.unstable_now();p(!0,a);p=null}catch(b){throw setTimeout(t,0),b;}},u=Date.now();exports.unstable_now=function(){return Date.now()-u};f=function(a){null!==p?setTimeout(f,0,a):(p=a,setTimeout(t,0))};g=function(a,b){q=setTimeout(a,b)};h=function(){clearTimeout(q)};k=function(){return!1};l=exports.unstable_forceFrameRate=function(){}}else{var w=window.performance,x=window.Date,
y=window.setTimeout,z=window.clearTimeout;if("undefined"!==typeof console){var A=window.cancelAnimationFrame;"function"!==typeof window.requestAnimationFrame&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills");"function"!==typeof A&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills")}if("object"===
typeof w&&"function"===typeof w.now)exports.unstable_now=function(){return w.now()};else{var B=x.now();exports.unstable_now=function(){return x.now()-B}}var C=!1,D=null,E=-1,F=5,G=0;k=function(){return exports.unstable_now()>=G};l=function(){};exports.unstable_forceFrameRate=function(a){0>a||125<a?console.error("forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported"):F=0<a?Math.floor(1E3/a):5};var H=new MessageChannel,I=H.port2;H.port1.onmessage=
function(){if(null!==D){var a=exports.unstable_now();G=a+F;try{D(!0,a)?I.postMessage(null):(C=!1,D=null)}catch(b){throw I.postMessage(null),b;}}else C=!1};f=function(a){D=a;C||(C=!0,I.postMessage(null))};g=function(a,b){E=y(function(){a(exports.unstable_now())},b)};h=function(){z(E);E=-1}}function J(a,b){var c=a.length;a.push(b);a:for(;;){var d=c-1>>>1,e=a[d];if(void 0!==e&&0<K(e,b))a[d]=b,a[c]=e,c=d;else break a}}function L(a){a=a[0];return void 0===a?null:a}
function M(a){var b=a[0];if(void 0!==b){var c=a.pop();if(c!==b){a[0]=c;a:for(var d=0,e=a.length;d<e;){var m=2*(d+1)-1,n=a[m],v=m+1,r=a[v];if(void 0!==n&&0>K(n,c))void 0!==r&&0>K(r,n)?(a[d]=r,a[v]=c,d=v):(a[d]=n,a[m]=c,d=m);else if(void 0!==r&&0>K(r,c))a[d]=r,a[v]=c,d=v;else break a}}return b}return null}function K(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}var N=[],O=[],P=1,Q=null,R=3,S=!1,T=!1,U=!1;
function V(a){for(var b=L(O);null!==b;){if(null===b.callback)M(O);else if(b.startTime<=a)M(O),b.sortIndex=b.expirationTime,J(N,b);else break;b=L(O)}}function W(a){U=!1;V(a);if(!T)if(null!==L(N))T=!0,f(X);else{var b=L(O);null!==b&&g(W,b.startTime-a)}}
function X(a,b){T=!1;U&&(U=!1,h());S=!0;var c=R;try{V(b);for(Q=L(N);null!==Q&&(!(Q.expirationTime>b)||a&&!k());){var d=Q.callback;if(null!==d){Q.callback=null;R=Q.priorityLevel;var e=d(Q.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?Q.callback=e:Q===L(N)&&M(N);V(b)}else M(N);Q=L(N)}if(null!==Q)var m=!0;else{var n=L(O);null!==n&&g(W,n.startTime-b);m=!1}return m}finally{Q=null,R=c,S=!1}}
function Y(a){switch(a){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1E4;default:return 5E3}}var Z=l;exports.unstable_IdlePriority=5;exports.unstable_ImmediatePriority=1;exports.unstable_LowPriority=4;exports.unstable_NormalPriority=3;exports.unstable_Profiling=null;exports.unstable_UserBlockingPriority=2;exports.unstable_cancelCallback=function(a){a.callback=null};exports.unstable_continueExecution=function(){T||S||(T=!0,f(X))};
exports.unstable_getCurrentPriorityLevel=function(){return R};exports.unstable_getFirstCallbackNode=function(){return L(N)};exports.unstable_next=function(a){switch(R){case 1:case 2:case 3:var b=3;break;default:b=R}var c=R;R=b;try{return a()}finally{R=c}};exports.unstable_pauseExecution=function(){};exports.unstable_requestPaint=Z;exports.unstable_runWithPriority=function(a,b){switch(a){case 1:case 2:case 3:case 4:case 5:break;default:a=3}var c=R;R=a;try{return b()}finally{R=c}};
exports.unstable_scheduleCallback=function(a,b,c){var d=exports.unstable_now();if("object"===typeof c&&null!==c){var e=c.delay;e="number"===typeof e&&0<e?d+e:d;c="number"===typeof c.timeout?c.timeout:Y(a)}else c=Y(a),e=d;c=e+c;a={id:P++,callback:b,priorityLevel:a,startTime:e,expirationTime:c,sortIndex:-1};e>d?(a.sortIndex=e,J(O,a),null===L(N)&&a===L(O)&&(U?h():U=!0,g(W,e-d))):(a.sortIndex=c,J(N,a),T||S||(T=!0,f(X)));return a};
exports.unstable_shouldYield=function(){var a=exports.unstable_now();V(a);var b=L(N);return b!==Q&&null!==Q&&null!==b&&null!==b.callback&&b.startTime<=a&&b.expirationTime<Q.expirationTime||k()};exports.unstable_wrapCallback=function(a){var b=R;return function(){var c=R;R=b;try{return a.apply(this,arguments)}finally{R=c}}};


/***/ }),
/* 425 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "VolumeStreamingCustomControls", function() { return VolumeStreamingCustomControls; });
/* harmony import */ var tslib__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(0);
/* harmony import */ var _base__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(32);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(3);
/* harmony import */ var react__WEBPACK_IMPORTED_MODULE_2___default = /*#__PURE__*/__webpack_require__.n(react__WEBPACK_IMPORTED_MODULE_2__);
/* harmony import */ var _mol_plugin_behavior_dynamic_volume_streaming_behavior__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(160);
/* harmony import */ var _controls_common__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(19);
/* harmony import */ var _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(2);
/* harmony import */ var _controls_parameters__WEBPACK_IMPORTED_MODULE_6__ = __webpack_require__(66);
/* harmony import */ var _controls_slider__WEBPACK_IMPORTED_MODULE_7__ = __webpack_require__(328);
/* harmony import */ var _mol_model_volume__WEBPACK_IMPORTED_MODULE_8__ = __webpack_require__(36);
/* harmony import */ var _mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__ = __webpack_require__(1);
/* harmony import */ var _mol_util_color_names__WEBPACK_IMPORTED_MODULE_10__ = __webpack_require__(47);
/* harmony import */ var _mol_util_number__WEBPACK_IMPORTED_MODULE_11__ = __webpack_require__(174);
/* harmony import */ var _mol_state__WEBPACK_IMPORTED_MODULE_12__ = __webpack_require__(13);
/* harmony import */ var _mol_plugin_behavior_static_state__WEBPACK_IMPORTED_MODULE_13__ = __webpack_require__(216);
/* harmony import */ var _controls_icons__WEBPACK_IMPORTED_MODULE_14__ = __webpack_require__(14);
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */















var ChannelParams = {
    color: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Color(_mol_util_color_names__WEBPACK_IMPORTED_MODULE_10__[/* ColorNames */ "a"].black, { description: 'Display color of the volume.' }),
    wireframe: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(false, { description: 'Control display of the volume as a wireframe.' }),
    opacity: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Numeric(0.3, { min: 0, max: 1, step: 0.01 }, { description: 'Opacity of the volume.' })
};
var Bounds = new Map([
    ['em', [-5, 5]],
    ['2fo-fc', [0, 3]],
    ['fo-fc(+ve)', [1, 5]],
    ['fo-fc(-ve)', [-5, -1]],
]);
var Channel = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Channel, _super);
    function Channel() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.ref = _mol_state__WEBPACK_IMPORTED_MODULE_12__["StateSelection"].findTagInSubtree(_this.plugin.state.data.tree, _this.props.bCell.transform.ref, _this.props.name);
        _this.getVisible = function () {
            var state = _this.plugin.state.data;
            var ref = _this.ref;
            if (!ref)
                return false;
            return !state.cells.get(ref).state.isHidden;
        };
        _this.toggleVisible = function () {
            var state = _this.plugin.state.data;
            var ref = _this.ref;
            if (!ref)
                return;
            Object(_mol_plugin_behavior_static_state__WEBPACK_IMPORTED_MODULE_13__["setSubtreeVisibility"])(state, ref, !state.cells.get(ref).state.isHidden);
        };
        return _this;
    }
    Channel.prototype.componentDidUpdate = function () {
        this.ref = _mol_state__WEBPACK_IMPORTED_MODULE_12__["StateSelection"].findTagInSubtree(this.plugin.state.data.tree, this.props.bCell.transform.ref, this.props.name);
    };
    Channel.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.data.events.cell.stateUpdated, function (e) {
            if (_this.ref === e.ref)
                _this.forceUpdate();
        });
    };
    Channel.prototype.render = function () {
        var props = this.props;
        var isRelative = props.isRelative, stats = props.stats;
        var channel = props.channels[props.name];
        var min = stats.min, max = stats.max, mean = stats.mean, sigma = stats.sigma;
        var value = Math.round(100 * (channel.isoValue.kind === 'relative' ? channel.isoValue.relativeValue : channel.isoValue.absoluteValue)) / 100;
        var relMin = (min - mean) / sigma;
        var relMax = (max - mean) / sigma;
        if (!this.props.isUnbounded) {
            var bounds = Bounds.get(this.props.name);
            if (this.props.name === 'em') {
                relMin = Math.max(bounds[0], relMin);
                relMax = Math.min(bounds[1], relMax);
            }
            else {
                relMin = bounds[0];
                relMax = bounds[1];
            }
        }
        var vMin = mean + sigma * relMin, vMax = mean + sigma * relMax;
        var step = Object(_mol_util_number__WEBPACK_IMPORTED_MODULE_11__[/* toPrecision */ "e"])(isRelative ? Math.round(((vMax - vMin) / sigma)) / 100 : sigma / 100, 2);
        var ctrlMin = isRelative ? relMin : vMin;
        var ctrlMax = isRelative ? relMax : vMax;
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_4__["ExpandableControlRow"], { label: props.label + (props.isRelative ? ' \u03C3' : ''), colorStripe: channel.color, pivot: react__WEBPACK_IMPORTED_MODULE_2__["createElement"]("div", { className: 'msp-volume-channel-inline-controls' },
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_slider__WEBPACK_IMPORTED_MODULE_7__[/* Slider */ "a"], { value: value, min: ctrlMin, max: ctrlMax, step: step, onChange: function (v) { return props.changeIso(props.name, v, isRelative); }, disabled: props.params.isDisabled, onEnter: props.params.events.onEnter }),
                react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_common__WEBPACK_IMPORTED_MODULE_4__["IconButton"], { svg: this.getVisible() ? _controls_icons__WEBPACK_IMPORTED_MODULE_14__["VisibilityOutlinedSvg"] : _controls_icons__WEBPACK_IMPORTED_MODULE_14__["VisibilityOffOutlinedSvg"], onClick: this.toggleVisible, toggleState: false, disabled: props.params.isDisabled })), controls: react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_6__["ParameterControls"], { onChange: function (_a) {
                    var name = _a.name, value = _a.value;
                    return props.changeParams(props.name, name, value);
                }, params: ChannelParams, values: channel, onEnter: props.params.events.onEnter, isDisabled: props.params.isDisabled }) });
    };
    return Channel;
}(_base__WEBPACK_IMPORTED_MODULE_1__["PluginUIComponent"]));
var VolumeStreamingCustomControls = /** @class */ (function (_super) {
    Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(VolumeStreamingCustomControls, _super);
    function VolumeStreamingCustomControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.changeIso = function (name, value, isRelative) {
            var _a;
            var old = _this.props.params;
            _this.newParams(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { entry: {
                    name: old.entry.name,
                    params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params), { channels: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params.channels), (_a = {}, _a[name] = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params.channels[name]), { isoValue: isRelative ? _mol_model_volume__WEBPACK_IMPORTED_MODULE_8__[/* Volume */ "b"].IsoValue.relative(value) : _mol_model_volume__WEBPACK_IMPORTED_MODULE_8__[/* Volume */ "b"].IsoValue.absolute(value) }), _a)) })
                } }));
        };
        _this.changeParams = function (name, param, value) {
            var _a, _b;
            var old = _this.props.params;
            _this.newParams(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { entry: {
                    name: old.entry.name,
                    params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params), { channels: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params.channels), (_a = {}, _a[name] = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params.channels[name]), (_b = {}, _b[param] = value, _b)), _a)) })
                } }));
        };
        _this.changeOption = function (_a) {
            var name = _a.name, value = _a.value;
            var old = _this.props.params;
            if (name === 'entry') {
                _this.newParams(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { entry: {
                        name: value,
                        params: old.entry.params,
                    } }));
            }
            else {
                var b = _this.props.b.data;
                var isEM = b.info.kind === 'em';
                var isRelative = value.params.isRelative;
                var sampling = b.info.header.sampling[0];
                var oldChannels = old.entry.params.channels;
                var oldView = old.entry.params.view.name === value.name
                    ? old.entry.params.view.params
                    : _this.props.info.params
                        .entry.map(old.entry.name)
                        .params
                        .view.map(value.name).defaultValue;
                var viewParams = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, oldView);
                if (value.name === 'selection-box') {
                    viewParams.radius = value.params.radius;
                }
                else if (value.name === 'box') {
                    viewParams.bottomLeft = value.params.bottomLeft;
                    viewParams.topRight = value.params.topRight;
                }
                viewParams.isUnbounded = !!value.params.isUnbounded;
                _this.newParams(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old), { entry: {
                        name: old.entry.name,
                        params: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, old.entry.params), { view: {
                                name: value.name,
                                params: viewParams
                            }, detailLevel: value.params.detailLevel, channels: isEM
                                ? { em: _this.convert(oldChannels.em, sampling.valuesInfo[0], isRelative) }
                                : {
                                    '2fo-fc': _this.convert(oldChannels['2fo-fc'], sampling.valuesInfo[0], isRelative),
                                    'fo-fc(+ve)': _this.convert(oldChannels['fo-fc(+ve)'], sampling.valuesInfo[1], isRelative),
                                    'fo-fc(-ve)': _this.convert(oldChannels['fo-fc(-ve)'], sampling.valuesInfo[1], isRelative)
                                } })
                    } }));
            }
        };
        return _this;
    }
    VolumeStreamingCustomControls.prototype.areInitial = function (params) {
        return _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].areEqual(this.props.info.params, params, this.props.info.initialValues);
    };
    VolumeStreamingCustomControls.prototype.newParams = function (params) {
        this.props.events.onChange(params, this.areInitial(params));
    };
    VolumeStreamingCustomControls.prototype.convert = function (channel, stats, isRelative) {
        return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])(Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__assign"])({}, channel), { isoValue: isRelative
                ? _mol_model_volume__WEBPACK_IMPORTED_MODULE_8__[/* Volume */ "b"].IsoValue.toRelative(channel.isoValue, stats)
                : _mol_model_volume__WEBPACK_IMPORTED_MODULE_8__[/* Volume */ "b"].IsoValue.toAbsolute(channel.isoValue, stats) });
    };
    VolumeStreamingCustomControls.prototype.render = function () {
        if (!this.props.b)
            return null;
        var b = this.props.b.data;
        var isEM = b.info.kind === 'em';
        var pivot = isEM ? 'em' : '2fo-fc';
        var params = this.props.params;
        var detailLevel = this.props.info.params
            .entry.map(params.entry.name).params.detailLevel;
        var isRelative = params.entry.params.channels[pivot].isoValue.kind === 'relative';
        var sampling = b.info.header.sampling[0];
        var isRelativeParam = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(isRelative, { description: 'Use normalized or absolute isocontour scale.', label: 'Normalized' });
        var isUnbounded = !!params.entry.params.view.params.isUnbounded;
        var isUnboundedParam = _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(isUnbounded, { description: 'Show full/limited range of iso-values for more fine-grained control.', label: 'Unbounded' });
        var isOff = params.entry.params.view.name === 'off';
        // TODO: factor common things out, cache
        var OptionsParams = {
            entry: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Select(params.entry.name, b.data.entries.map(function (info) { return [info.dataId, info.dataId]; }), { isHidden: isOff, description: 'Which entry with volume data to display.' }),
            view: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].MappedStatic(params.entry.params.view.name, {
                'off': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({
                    isRelative: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(isRelative, { isHidden: true }),
                    isUnbounded: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Boolean(isUnbounded, { isHidden: true }),
                }, { description: 'Display off.' }),
                'box': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({
                    bottomLeft: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__["Vec3"].zero()),
                    topRight: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Vec3(_mol_math_linear_algebra__WEBPACK_IMPORTED_MODULE_9__["Vec3"].zero()),
                    detailLevel: detailLevel,
                    isRelative: isRelativeParam,
                    isUnbounded: isUnboundedParam,
                }, { description: 'Static box defined by cartesian coords.' }),
                'selection-box': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({
                    radius: _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Numeric(5, { min: 0, max: 50, step: 0.5 }, { description: 'Radius in \u212B within which the volume is shown.' }),
                    detailLevel: detailLevel,
                    isRelative: isRelativeParam,
                    isUnbounded: isUnboundedParam,
                }, { description: 'Box around focused element.' }),
                'cell': _mol_util_param_definition__WEBPACK_IMPORTED_MODULE_5__["ParamDefinition"].Group({
                    detailLevel: detailLevel,
                    isRelative: isRelativeParam,
                    isUnbounded: isUnboundedParam,
                }, { description: 'Box around the structure\'s bounding box.' }),
            }, { options: _mol_plugin_behavior_dynamic_volume_streaming_behavior__WEBPACK_IMPORTED_MODULE_3__[/* VolumeStreaming */ "a"].ViewTypeOptions, description: 'Controls what of the volume is displayed. "Off" hides the volume alltogether. "Bounded box" shows the volume inside the given box. "Around Focus" shows the volume around the element/atom last interacted with. "Whole Structure" shows the volume for the whole structure.' })
        };
        var options = {
            entry: params.entry.name,
            view: {
                name: params.entry.params.view.name,
                params: {
                    detailLevel: params.entry.params.detailLevel,
                    radius: params.entry.params.view.params.radius,
                    bottomLeft: params.entry.params.view.params.bottomLeft,
                    topRight: params.entry.params.view.params.topRight,
                    isRelative: isRelative,
                    isUnbounded: isUnbounded
                }
            }
        };
        if (isOff) {
            return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_6__["ParameterControls"], { onChange: this.changeOption, params: OptionsParams, values: options, onEnter: this.props.events.onEnter, isDisabled: this.props.isDisabled });
        }
        return react__WEBPACK_IMPORTED_MODULE_2__["createElement"](react__WEBPACK_IMPORTED_MODULE_2__["Fragment"], null,
            !isEM && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](Channel, { label: '2Fo-Fc', name: '2fo-fc', bCell: this.props.bCell, channels: params.entry.params.channels, changeIso: this.changeIso, changeParams: this.changeParams, isRelative: isRelative, params: this.props, stats: sampling.valuesInfo[0], isUnbounded: isUnbounded }),
            !isEM && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](Channel, { label: 'Fo-Fc(+ve)', name: 'fo-fc(+ve)', bCell: this.props.bCell, channels: params.entry.params.channels, changeIso: this.changeIso, changeParams: this.changeParams, isRelative: isRelative, params: this.props, stats: sampling.valuesInfo[1], isUnbounded: isUnbounded }),
            !isEM && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](Channel, { label: 'Fo-Fc(-ve)', name: 'fo-fc(-ve)', bCell: this.props.bCell, channels: params.entry.params.channels, changeIso: this.changeIso, changeParams: this.changeParams, isRelative: isRelative, params: this.props, stats: sampling.valuesInfo[1], isUnbounded: isUnbounded }),
            isEM && react__WEBPACK_IMPORTED_MODULE_2__["createElement"](Channel, { label: 'EM', name: 'em', bCell: this.props.bCell, channels: params.entry.params.channels, changeIso: this.changeIso, changeParams: this.changeParams, isRelative: isRelative, params: this.props, stats: sampling.valuesInfo[0], isUnbounded: isUnbounded }),
            react__WEBPACK_IMPORTED_MODULE_2__["createElement"](_controls_parameters__WEBPACK_IMPORTED_MODULE_6__["ParameterControls"], { onChange: this.changeOption, params: OptionsParams, values: options, onEnter: this.props.events.onEnter, isDisabled: this.props.isDisabled }));
    };
    return VolumeStreamingCustomControls;
}(_base__WEBPACK_IMPORTED_MODULE_1__["PluginUIComponent"]));

//# sourceMappingURL=volume.js.map

/***/ }),
/* 426 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
 * The buffer module from node.js, for the browser.
 *
 * @author   Feross Aboukhadijeh <http://feross.org>
 * @license  MIT
 */
/* eslint-disable no-proto */



var base64 = __webpack_require__(427)
var ieee754 = __webpack_require__(428)
var isArray = __webpack_require__(429)

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 ' + str + '>'
}

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(this, __webpack_require__(382)))

/***/ }),
/* 427 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";


exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray

var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array

var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
  lookup[i] = code[i]
  revLookup[code.charCodeAt(i)] = i
}

// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63

function getLens (b64) {
  var len = b64.length

  if (len % 4 > 0) {
    throw new Error('Invalid string. Length must be a multiple of 4')
  }

  // Trim off extra bytes after placeholder bytes are found
  // See: https://github.com/beatgammit/base64-js/issues/42
  var validLen = b64.indexOf('=')
  if (validLen === -1) validLen = len

  var placeHoldersLen = validLen === len
    ? 0
    : 4 - (validLen % 4)

  return [validLen, placeHoldersLen]
}

// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function _byteLength (b64, validLen, placeHoldersLen) {
  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}

function toByteArray (b64) {
  var tmp
  var lens = getLens(b64)
  var validLen = lens[0]
  var placeHoldersLen = lens[1]

  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))

  var curByte = 0

  // if there are placeholders, only get up to the last complete 4 chars
  var len = placeHoldersLen > 0
    ? validLen - 4
    : validLen

  var i
  for (i = 0; i < len; i += 4) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 18) |
      (revLookup[b64.charCodeAt(i + 1)] << 12) |
      (revLookup[b64.charCodeAt(i + 2)] << 6) |
      revLookup[b64.charCodeAt(i + 3)]
    arr[curByte++] = (tmp >> 16) & 0xFF
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 2) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 2) |
      (revLookup[b64.charCodeAt(i + 1)] >> 4)
    arr[curByte++] = tmp & 0xFF
  }

  if (placeHoldersLen === 1) {
    tmp =
      (revLookup[b64.charCodeAt(i)] << 10) |
      (revLookup[b64.charCodeAt(i + 1)] << 4) |
      (revLookup[b64.charCodeAt(i + 2)] >> 2)
    arr[curByte++] = (tmp >> 8) & 0xFF
    arr[curByte++] = tmp & 0xFF
  }

  return arr
}

function tripletToBase64 (num) {
  return lookup[num >> 18 & 0x3F] +
    lookup[num >> 12 & 0x3F] +
    lookup[num >> 6 & 0x3F] +
    lookup[num & 0x3F]
}

function encodeChunk (uint8, start, end) {
  var tmp
  var output = []
  for (var i = start; i < end; i += 3) {
    tmp =
      ((uint8[i] << 16) & 0xFF0000) +
      ((uint8[i + 1] << 8) & 0xFF00) +
      (uint8[i + 2] & 0xFF)
    output.push(tripletToBase64(tmp))
  }
  return output.join('')
}

function fromByteArray (uint8) {
  var tmp
  var len = uint8.length
  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  var parts = []
  var maxChunkLength = 16383 // must be multiple of 3

  // go through the array every three bytes, we'll deal with trailing stuff later
  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
    parts.push(encodeChunk(
      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
    ))
  }

  // pad the end with zeros, but make sure to not forget the extra bytes
  if (extraBytes === 1) {
    tmp = uint8[len - 1]
    parts.push(
      lookup[tmp >> 2] +
      lookup[(tmp << 4) & 0x3F] +
      '=='
    )
  } else if (extraBytes === 2) {
    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
    parts.push(
      lookup[tmp >> 10] +
      lookup[(tmp >> 4) & 0x3F] +
      lookup[(tmp << 2) & 0x3F] +
      '='
    )
  }

  return parts.join('')
}


/***/ }),
/* 428 */
/***/ (function(module, exports) {

exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  var e, m
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var nBits = -7
  var i = isLE ? (nBytes - 1) : 0
  var d = isLE ? -1 : 1
  var s = buffer[offset + i]

  i += d

  e = s & ((1 << (-nBits)) - 1)
  s >>= (-nBits)
  nBits += eLen
  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  m = e & ((1 << (-nBits)) - 1)
  e >>= (-nBits)
  nBits += mLen
  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}

  if (e === 0) {
    e = 1 - eBias
  } else if (e === eMax) {
    return m ? NaN : ((s ? -1 : 1) * Infinity)
  } else {
    m = m + Math.pow(2, mLen)
    e = e - eBias
  }
  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}

exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  var e, m, c
  var eLen = (nBytes * 8) - mLen - 1
  var eMax = (1 << eLen) - 1
  var eBias = eMax >> 1
  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  var i = isLE ? 0 : (nBytes - 1)
  var d = isLE ? 1 : -1
  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0

  value = Math.abs(value)

  if (isNaN(value) || value === Infinity) {
    m = isNaN(value) ? 1 : 0
    e = eMax
  } else {
    e = Math.floor(Math.log(value) / Math.LN2)
    if (value * (c = Math.pow(2, -e)) < 1) {
      e--
      c *= 2
    }
    if (e + eBias >= 1) {
      value += rt / c
    } else {
      value += rt * Math.pow(2, 1 - eBias)
    }
    if (value * c >= 2) {
      e++
      c /= 2
    }

    if (e + eBias >= eMax) {
      m = 0
      e = eMax
    } else if (e + eBias >= 1) {
      m = ((value * c) - 1) * Math.pow(2, mLen)
      e = e + eBias
    } else {
      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
      e = 0
    }
  }

  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}

  e = (e << mLen) | m
  eLen += mLen
  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}

  buffer[offset + i - d] |= s * 128
}


/***/ }),
/* 429 */
/***/ (function(module, exports) {

var toString = {}.toString;

module.exports = Array.isArray || function (arr) {
  return toString.call(arr) == '[object Array]';
};


/***/ }),
/* 430 */
/***/ (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 <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();

    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();

    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();

    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();

    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
}(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));

/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(382), __webpack_require__(383)))

/***/ }),
/* 431 */
/***/ (function(module, exports) {

module.exports = XMLHttpRequest;


/***/ }),
/* 432 */
/***/ (function(module, exports) {



/***/ }),
/* 433 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PDBeLociLabelProvider = void 0;
var behavior_1 = __webpack_require__(170);
var structure_1 = __webpack_require__(4);
var label_1 = __webpack_require__(72);
exports.PDBeLociLabelProvider = behavior_1.PluginBehavior.create({
    name: 'pdbe-loci-label-provider',
    category: 'interaction',
    ctor: /** @class */ (function () {
        function class_1(ctx) {
            var _this = this;
            this.ctx = ctx;
            this.f = {
                label: function (loci) {
                    var customState = (_this.ctx.customState);
                    var superpositionView = (customState && customState.initParams.superposition) ? true : false;
                    var label = [];
                    if (!superpositionView && structure_1.StructureElement.Loci.is(loci) && loci.elements.length === 1) {
                        var u = loci.elements[0].unit;
                        var l = structure_1.StructureElement.Location.create(loci.structure, u, u.elements[0]);
                        var name_1 = structure_1.StructureProperties.entity.pdbx_description(l).join(', ');
                        label.push(name_1);
                    }
                    label.push(label_1.lociLabel(loci));
                    return label.filter(function (l) { return !!l; }).join('</br>');
                },
                group: function (label) { return label.toString().replace(/Model [0-9]+/g, 'Models'); },
                priority: 100
            };
        }
        class_1.prototype.register = function () { this.ctx.managers.lociLabels.addProvider(this.f); };
        class_1.prototype.unregister = function () { this.ctx.managers.lociLabels.removeProvider(this.f); };
        return class_1;
    }()),
    display: { name: 'Provide PDBe Loci Label' }
});
//# sourceMappingURL=labels.js.map

/***/ }),
/* 434 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PDBeAfViewStructureTools = exports.PDBeSuperpositionStructureTools = exports.PDBeLigandViewStructureTools = exports.PDBeStructureTools = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var base_1 = __webpack_require__(32);
var components_1 = __webpack_require__(322);
var measurements_1 = __webpack_require__(386);
var source_1 = __webpack_require__(391);
var volume_1 = __webpack_require__(371);
var annotation_controls_1 = __webpack_require__(435);
var af_confidence_controls_1 = __webpack_require__(436);
var icons_1 = __webpack_require__(14);
var superposition_components_1 = __webpack_require__(437);
var PDBeStructureTools = /** @class */ (function (_super) {
    tslib_1.__extends(PDBeStructureTools, _super);
    function PDBeStructureTools() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PDBeStructureTools.prototype.render = function () {
        return React.createElement(React.Fragment, null,
            React.createElement("div", { className: 'msp-section-header' },
                React.createElement(icons_1.Icon, { svg: icons_1.BuildSvg }),
                "Structure Tools"),
            React.createElement(source_1.StructureSourceControls, null),
            React.createElement(annotation_controls_1.AnnotationsComponentControls, null),
            React.createElement(components_1.StructureComponentControls, null),
            React.createElement(volume_1.VolumeStreamingControls, null),
            React.createElement(volume_1.VolumeSourceControls, null),
            React.createElement(measurements_1.StructureMeasurementsControls, null));
    };
    return PDBeStructureTools;
}(base_1.PluginUIComponent));
exports.PDBeStructureTools = PDBeStructureTools;
var PDBeLigandViewStructureTools = /** @class */ (function (_super) {
    tslib_1.__extends(PDBeLigandViewStructureTools, _super);
    function PDBeLigandViewStructureTools() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PDBeLigandViewStructureTools.prototype.render = function () {
        return React.createElement(React.Fragment, null,
            React.createElement("div", { className: 'msp-section-header' },
                React.createElement(icons_1.Icon, { svg: icons_1.BuildSvg }),
                "Structure Tools"),
            React.createElement(components_1.StructureComponentControls, null),
            React.createElement(volume_1.VolumeStreamingControls, null),
            React.createElement(measurements_1.StructureMeasurementsControls, null));
    };
    return PDBeLigandViewStructureTools;
}(base_1.PluginUIComponent));
exports.PDBeLigandViewStructureTools = PDBeLigandViewStructureTools;
var PDBeSuperpositionStructureTools = /** @class */ (function (_super) {
    tslib_1.__extends(PDBeSuperpositionStructureTools, _super);
    function PDBeSuperpositionStructureTools() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PDBeSuperpositionStructureTools.prototype.render = function () {
        return React.createElement(React.Fragment, null,
            React.createElement("div", { className: 'msp-section-header' },
                React.createElement(icons_1.Icon, { svg: icons_1.BuildSvg }),
                "Structure Tools"),
            React.createElement(superposition_components_1.SuperpositionComponentControls, null),
            React.createElement(measurements_1.StructureMeasurementsControls, null));
    };
    return PDBeSuperpositionStructureTools;
}(base_1.PluginUIComponent));
exports.PDBeSuperpositionStructureTools = PDBeSuperpositionStructureTools;
var PDBeAfViewStructureTools = /** @class */ (function (_super) {
    tslib_1.__extends(PDBeAfViewStructureTools, _super);
    function PDBeAfViewStructureTools() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PDBeAfViewStructureTools.prototype.render = function () {
        return React.createElement(React.Fragment, null,
            React.createElement("div", { className: 'msp-section-header' },
                React.createElement(icons_1.Icon, { svg: icons_1.BuildSvg }),
                "Structure Tools"),
            React.createElement(components_1.StructureComponentControls, null),
            React.createElement(af_confidence_controls_1.AFConfidenceComponentControls, null),
            React.createElement(measurements_1.StructureMeasurementsControls, null));
    };
    return PDBeAfViewStructureTools;
}(base_1.PluginUIComponent));
exports.PDBeAfViewStructureTools = PDBeAfViewStructureTools;
//# sourceMappingURL=pdbe-structure-controls.js.map

/***/ }),
/* 435 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AnnotationsComponentControls = exports.TextsmsOutlinedSvg = void 0;
var tslib_1 = __webpack_require__(0);
// import TextsmsOutlined from '@material-ui/icons/TextsmsOutlined';
var React = tslib_1.__importStar(__webpack_require__(3));
var common_1 = __webpack_require__(19);
var base_1 = __webpack_require__(32);
var color_1 = __webpack_require__(377);
var mol_state_1 = __webpack_require__(13);
var parameters_1 = __webpack_require__(66);
var color_2 = __webpack_require__(406);
var behavior_1 = __webpack_require__(385);
var behavior_2 = __webpack_require__(408);
var icons_1 = __webpack_require__(14);
var hierarchy_1 = __webpack_require__(255);
var _TextsmsOutlined = React.createElement("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }),
    React.createElement("g", null,
        React.createElement("path", { d: "M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z" }),
        React.createElement("path", { d: "M7 9h2v2H7zM11 9h2v2h-2zM15 9h2v2h-2z" })));
function TextsmsOutlinedSvg() { return _TextsmsOutlined; }
exports.TextsmsOutlinedSvg = TextsmsOutlinedSvg;
var AnnotationsComponentControls = /** @class */ (function (_super) {
    tslib_1.__extends(AnnotationsComponentControls, _super);
    function AnnotationsComponentControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isCollapsed: false,
            validationApplied: false,
            domainAtnApplied: false,
            validationOptions: false,
            domainAtnOptions: false
        };
        _this.getOptionParams = function () {
            var validationAnnotationCtrl = false;
            var domainAnnotationCtrl = false;
            var customState = _this.plugin.customState;
            if (customState && customState.initParams) {
                if (customState.initParams.validationAnnotation)
                    validationAnnotationCtrl = true;
                if (customState.initParams.domainAnnotation)
                    domainAnnotationCtrl = true;
            }
            if ((validationAnnotationCtrl && !_this.state.validationParams) || (domainAnnotationCtrl && !_this.state.domainAtnParams)) {
                var groupRef = mol_state_1.StateSelection.findTagInSubtree(_this.plugin.state.data.tree, mol_state_1.StateTransform.RootRef, 'structure-component-static-polymer');
                if (groupRef) {
                    var struct = _this.plugin.state.data.select(groupRef)[0].obj;
                    if (struct) {
                        var themeDataCtx = { structure: struct.data };
                        if (validationAnnotationCtrl && !_this.state.validationParams) {
                            var validationActionsParams = color_1.StructureQualityReportColorThemeProvider.getParams(themeDataCtx);
                            if (validationActionsParams) {
                                _this.setState({ validationParams: {
                                        params: validationActionsParams,
                                        values: { type: validationActionsParams.type.defaultValue }
                                    } });
                            }
                        }
                        if (domainAnnotationCtrl && !_this.state.domainAtnParams) {
                            var domainActionsParams = color_2.DomainAnnotationsColorThemeProvider.getParams(themeDataCtx);
                            if (domainActionsParams) {
                                _this.setState({ domainAtnParams: {
                                        params: domainActionsParams,
                                        values: { type: domainActionsParams.type.defaultValue }
                                    } });
                            }
                        }
                    }
                }
            }
        };
        _this.toggleCollapsed = function () {
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
        };
        _this.toggleOptions = function (type) {
            if (type === 0)
                _this.setState({ validationOptions: !_this.state.validationOptions });
            if (type === 1)
                _this.setState({ domainAtnOptions: !_this.state.domainAtnOptions });
        };
        _this.applyAnnotation = function (type, visibleState, params) {
            // Defaults
            var themeName = 'polymer-id';
            var themePropsToAdd = behavior_1.PDBeStructureQualityReport;
            var themePropsToRemove = _this.state.domainAtnParams ? behavior_2.PDBeDomainAnnotations : void 0;
            // Set Theme Params
            if (type === 0) {
                if (visibleState) {
                    themeName = 'pdbe-structure-quality-report';
                }
                _this.setState({ validationApplied: visibleState });
                _this.setState({ domainAtnApplied: false });
            }
            else {
                themePropsToAdd = behavior_2.PDBeDomainAnnotations;
                themePropsToRemove = _this.state.validationParams ? behavior_1.PDBeStructureQualityReport : void 0;
                if (visibleState)
                    themeName = 'pdbe-domain-annotations';
                _this.setState({ domainAtnApplied: visibleState });
                _this.setState({ validationApplied: false });
            }
            // Update Tooltip
            if (visibleState && themeName !== 'polymer-id') {
                var addTooltipUpdate = _this.plugin.state.behaviors.build().to(themePropsToAdd.id).update(themePropsToAdd, function (old) { old.showTooltip = true; });
                _this.plugin.runTask(_this.plugin.state.behaviors.updateTree(addTooltipUpdate));
                if (themePropsToRemove) {
                    var removeTooltipUpdate = _this.plugin.state.behaviors.build().to(themePropsToRemove.id).update(themePropsToRemove, function (old) { old.showTooltip = false; });
                    _this.plugin.runTask(_this.plugin.state.behaviors.updateTree(removeTooltipUpdate));
                }
            }
            var polymerGroup;
            var componentGroups = _this.plugin.managers.structure.hierarchy.currentComponentGroups;
            componentGroups.forEach(function (compGrp) {
                if (compGrp[0].key === 'structure-component-static-polymer')
                    polymerGroup = compGrp;
            });
            if (polymerGroup) {
                _this.plugin.managers.structure.component.updateRepresentationsTheme(polymerGroup, { color: themeName, colorParams: params ? params : void 0 });
            }
        };
        _this.initApplyAnnotation = function (type) {
            if (type === 0)
                _this.applyAnnotation(0, !_this.state.validationApplied, _this.state.validationParams.values);
            if (type === 1)
                _this.applyAnnotation(1, !_this.state.domainAtnApplied, _this.state.domainAtnParams.values);
        };
        _this.updateValidationParams = function (val) {
            var updatedParams = tslib_1.__assign({}, _this.state.validationParams);
            updatedParams.values = val;
            _this.setState({ validationParams: updatedParams });
            if (_this.state.validationApplied)
                _this.applyAnnotation(0, _this.state.validationApplied, val);
        };
        _this.updateDomainAtnParams = function (val) {
            var updatedParams = tslib_1.__assign({}, _this.state.domainAtnParams);
            updatedParams.values = val;
            _this.setState({ domainAtnParams: updatedParams });
            if (_this.state.domainAtnApplied)
                _this.applyAnnotation(1, _this.state.domainAtnApplied, val);
        };
        return _this;
    }
    AnnotationsComponentControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () {
            _this.getOptionParams();
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) { return _this.setState({
            description: hierarchy_1.StructureHierarchyManager.getSelectedStructuresDescription(_this.plugin)
        }); });
    };
    AnnotationsComponentControls.prototype.render = function () {
        var _this = this;
        if (!this.state.validationParams && !this.state.domainAtnParams)
            return React.createElement(React.Fragment, null);
        var brand = {
            accent: 'green',
            svg: TextsmsOutlinedSvg
        };
        var wrapClass = this.state.isCollapsed
            ? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
            : 'msp-transform-wrapper';
        return React.createElement("div", { className: wrapClass },
            React.createElement("div", { className: 'msp-transform-header' },
                React.createElement(common_1.Button, { icon: brand ? void 0 : this.state.isCollapsed ? icons_1.ArrowRightSvg : icons_1.ArrowDropDownSvg, noOverflow: true, onClick: this.toggleCollapsed, className: brand ? "msp-transform-header-brand msp-transform-header-brand-" + brand.accent : void 0, title: "Click to " + (this.state.isCollapsed ? 'expand' : 'collapse') },
                    React.createElement(icons_1.Icon, { svg: brand === null || brand === void 0 ? void 0 : brand.svg, inline: true }),
                    "Annotations",
                    React.createElement("small", { style: { margin: '0 6px' } }, this.state.isCollapsed ? '' : this.state.description))),
            !this.state.isCollapsed && this.state.validationParams &&
                React.createElement("div", { className: 'msp-flex-row' },
                    React.createElement(common_1.Button, { noOverflow: true, className: 'msp-control-button-label', title: "Validation Report Annotations.", style: { textAlign: 'left' } }, "Validation Report"),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.initApplyAnnotation(0); }, toggleState: false, svg: !this.state.validationApplied ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, title: "Click to " + (this.state.validationApplied ? 'Hide' : 'Show') + " Validation Report Annotation", small: true, className: 'msp-form-control', flex: true }),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.toggleOptions(0); }, svg: icons_1.MoreHorizSvg, title: 'Actions', toggleState: this.state.validationOptions, className: 'msp-form-control', flex: true })),
            !this.state.isCollapsed && this.state.validationParams && this.state.validationOptions && React.createElement("div", { style: { marginBottom: '6px' } },
                React.createElement("div", { className: "msp-accent-offset" },
                    React.createElement("div", { className: 'msp-representation-entry' },
                        React.createElement(parameters_1.ParameterControls, { params: this.state.validationParams.params, values: this.state.validationParams.values, onChangeValues: this.updateValidationParams })))),
            !this.state.isCollapsed && this.state.domainAtnParams &&
                React.createElement("div", { className: 'msp-flex-row' },
                    React.createElement(common_1.Button, { noOverflow: true, className: 'msp-control-button-label', title: "Domain Annotations.", style: { textAlign: 'left' } }, "Domains"),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.initApplyAnnotation(1); }, toggleState: false, svg: !this.state.domainAtnApplied ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, title: "Click to " + (this.state.domainAtnApplied ? 'Hide' : 'Show') + " Domain Annotation", small: true, className: 'msp-form-control', flex: true }),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.toggleOptions(1); }, svg: icons_1.MoreHorizSvg, title: 'Actions', toggleState: this.state.domainAtnOptions, className: 'msp-form-control', flex: true })),
            !this.state.isCollapsed && this.state.domainAtnParams && this.state.domainAtnOptions && React.createElement("div", { style: { marginBottom: '6px' } },
                React.createElement("div", { className: "msp-accent-offset" },
                    React.createElement("div", { className: 'msp-representation-entry' },
                        React.createElement(parameters_1.ParameterControls, { params: this.state.domainAtnParams.params, values: this.state.domainAtnParams.values, onChangeValues: this.updateDomainAtnParams })))));
    };
    return AnnotationsComponentControls;
}(base_1.PurePluginUIComponent));
exports.AnnotationsComponentControls = AnnotationsComponentControls;
//# sourceMappingURL=annotation-controls.js.map

/***/ }),
/* 436 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.AFConfidenceComponentControls = exports.TextsmsOutlinedSvg = void 0;
var tslib_1 = __webpack_require__(0);
// import TextsmsOutlined from '@material-ui/icons/TextsmsOutlined';
var React = tslib_1.__importStar(__webpack_require__(3));
var common_1 = __webpack_require__(19);
var base_1 = __webpack_require__(32);
// import { StructureQualityReportColorThemeProvider } from 'Molstar/extensions/pdbe/structure-quality-report/color';
var mol_state_1 = __webpack_require__(13);
var parameters_1 = __webpack_require__(66);
// import { DomainAnnotationsColorThemeProvider } from '../domain-annotations/color';
// import { PDBeStructureQualityReport } from 'Molstar/extensions/pdbe/structure-quality-report/behavior';
// import { PDBeDomainAnnotations } from '../domain-annotations/behavior';
var behavior_1 = __webpack_require__(409);
var color_1 = __webpack_require__(411);
var icons_1 = __webpack_require__(14);
var hierarchy_1 = __webpack_require__(255);
// import { StructureComponentManager } from 'Molstar/mol-plugin-state/manager/structure/component';
var _TextsmsOutlined = React.createElement("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    React.createElement("path", { fill: "none", d: "M0 0h24v24H0V0z" }),
    React.createElement("g", null,
        React.createElement("path", { d: "M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z" }),
        React.createElement("path", { d: "M7 9h2v2H7zM11 9h2v2h-2zM15 9h2v2h-2z" })));
function TextsmsOutlinedSvg() { return _TextsmsOutlined; }
exports.TextsmsOutlinedSvg = TextsmsOutlinedSvg;
var AFConfidenceComponentControls = /** @class */ (function (_super) {
    tslib_1.__extends(AFConfidenceComponentControls, _super);
    function AFConfidenceComponentControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isCollapsed: false,
            annotationApplied: false,
            displayOptions: false
        };
        _this.getOptionParams = function () {
            if (!_this.state.afConfParams) {
                // const themeParams = StructureComponentManager.getThemeParams(this.plugin, this.plugin.managers.structure.component.pivotStructure);
                // console.log(themeParams.representations)
                var groupRef = mol_state_1.StateSelection.findTagInSubtree(_this.plugin.state.data.tree, mol_state_1.StateTransform.RootRef, 'structure-component-static-polymer');
                if (groupRef) {
                    var struct = _this.plugin.state.data.select(groupRef)[0].obj;
                    if (struct) {
                        var themeDataCtx = { structure: struct.data };
                        var actionsParams = color_1.AfConfidenceColorThemeProvider.getParams(themeDataCtx);
                        console.log('aa', struct.data);
                        if (actionsParams) {
                            _this.setState({ afConfParams: {
                                    params: actionsParams,
                                    values: { type: actionsParams.type.defaultValue }
                                } });
                        }
                    }
                }
            }
        };
        _this.toggleCollapsed = function () {
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
        };
        _this.toggleOptions = function () {
            _this.setState({ displayOptions: !_this.state.displayOptions });
        };
        _this.applyAnnotation = function (visibleState, params) {
            // Defaults
            var themeName = 'polymer-id';
            if (visibleState) {
                themeName = 'af-confidence';
                _this.setState({ annotationApplied: true });
            }
            else {
                _this.setState({ annotationApplied: false });
            }
            // Update Tooltip
            var tooltipUpdate = _this.plugin.state.behaviors.build().to(behavior_1.AfConfidenceScore.id).update(behavior_1.AfConfidenceScore, function (old) { old.showTooltip = visibleState ? true : false; });
            _this.plugin.runTask(_this.plugin.state.behaviors.updateTree(tooltipUpdate));
            var polymerGroup;
            var componentGroups = _this.plugin.managers.structure.hierarchy.currentComponentGroups;
            componentGroups.forEach(function (compGrp) {
                if (compGrp[0].key === 'structure-component-static-polymer')
                    polymerGroup = compGrp;
            });
            if (polymerGroup) {
                _this.plugin.managers.structure.component.updateRepresentationsTheme(polymerGroup, { color: themeName, colorParams: params ? params : void 0 });
            }
        };
        _this.initApplyAnnotation = function () {
            _this.applyAnnotation(!_this.state.annotationApplied, _this.state.afConfParams.values);
        };
        _this.updateAfConfParams = function (val) {
            var updatedParams = tslib_1.__assign({}, _this.state.afConfParams);
            updatedParams.values = val;
            _this.setState({ afConfParams: updatedParams });
            if (_this.state.annotationApplied)
                _this.applyAnnotation(_this.state.annotationApplied, val);
        };
        return _this;
    }
    AFConfidenceComponentControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () {
            _this.getOptionParams();
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function (c) { return _this.setState({
            description: hierarchy_1.StructureHierarchyManager.getSelectedStructuresDescription(_this.plugin)
        }); });
    };
    AFConfidenceComponentControls.prototype.render = function () {
        // if(!this.state.validationParams && !this.state.domainAtnParams) return <></>;
        var _this = this;
        var brand = {
            accent: 'green',
            svg: TextsmsOutlinedSvg
        };
        var wrapClass = this.state.isCollapsed
            ? 'msp-transform-wrapper msp-transform-wrapper-collapsed'
            : 'msp-transform-wrapper';
        return React.createElement("div", { className: wrapClass },
            React.createElement("div", { className: 'msp-transform-header' },
                React.createElement(common_1.Button, { icon: brand ? void 0 : this.state.isCollapsed ? icons_1.ArrowRightSvg : icons_1.ArrowDropDownSvg, noOverflow: true, onClick: this.toggleCollapsed, className: brand ? "msp-transform-header-brand msp-transform-header-brand-" + brand.accent : void 0, title: "Click to " + (this.state.isCollapsed ? 'expand' : 'collapse') },
                    React.createElement(icons_1.Icon, { svg: brand === null || brand === void 0 ? void 0 : brand.svg, inline: true }),
                    "Annotations",
                    React.createElement("small", { style: { margin: '0 6px' } }, this.state.isCollapsed ? '' : this.state.description))),
            !this.state.isCollapsed &&
                React.createElement("div", { className: 'msp-flex-row' },
                    React.createElement(common_1.Button, { noOverflow: true, className: 'msp-control-button-label', title: "AlphaFold Confidence Score", style: { textAlign: 'left' } }, "AlphaFold Confidence Score"),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.initApplyAnnotation(); }, toggleState: false, svg: !this.state.annotationApplied ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, title: "Click to " + (this.state.domainAtnApplied ? 'Hide' : 'Show') + " Local Metric Annotation", small: true, className: 'msp-form-control', flex: true }),
                    React.createElement(common_1.IconButton, { onClick: function () { return _this.toggleOptions(); }, svg: icons_1.MoreHorizSvg, title: 'Actions', toggleState: this.state.displayOptions, className: 'msp-form-control', flex: true })),
            !this.state.isCollapsed && this.state.displayOptions && this.state.afConfParams && React.createElement("div", { style: { marginBottom: '6px' } },
                React.createElement("div", { className: "msp-accent-offset" },
                    React.createElement("div", { className: 'msp-representation-entry' },
                        React.createElement(parameters_1.ParameterControls, { params: this.state.afConfParams.params, values: this.state.afConfParams.values, onChangeValues: this.updateAfConfParams })))));
    };
    return AFConfidenceComponentControls;
}(base_1.PurePluginUIComponent));
exports.AFConfidenceComponentControls = AFConfidenceComponentControls;
//# sourceMappingURL=af-confidence-controls.js.map

/***/ }),
/* 437 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SuperpositionComponentControls = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var commands_1 = __webpack_require__(26);
var mol_state_1 = __webpack_require__(13);
var param_definition_1 = __webpack_require__(2);
var base_1 = __webpack_require__(32);
var common_1 = __webpack_require__(19);
var icons_1 = __webpack_require__(14);
var parameters_1 = __webpack_require__(66);
var operators_1 = __webpack_require__(238);
var rxjs_1 = __webpack_require__(139);
var SuperpositionComponentControls = /** @class */ (function (_super) {
    tslib_1.__extends(SuperpositionComponentControls, _super);
    function SuperpositionComponentControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SuperpositionComponentControls.prototype.defaultState = function () {
        return {
            header: 'Components',
            isCollapsed: false,
            isDisabled: false,
            brand: { accent: 'blue', svg: icons_1.CubeOutlineSvg }
        };
    };
    SuperpositionComponentControls.prototype.renderControls = function () {
        return React.createElement(React.Fragment, null,
            React.createElement(ComponentListControls, null));
    };
    return SuperpositionComponentControls;
}(base_1.CollapsableControls));
exports.SuperpositionComponentControls = SuperpositionComponentControls;
;
var ComponentListControls = /** @class */ (function (_super) {
    tslib_1.__extends(ComponentListControls, _super);
    function ComponentListControls() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            segmentWatch: false,
            ligSearchText: '',
            carbSearchText: '',
            componentGroups: { nonLigGroups: [], ligGroups: [], carbGroups: [] },
            ligGroups: [],
            isLigCollapsed: false,
            carbGroups: [],
            isCarbCollapsed: false,
            isBusy: false
        };
        _this.ligInputStream = new rxjs_1.Subject();
        _this.handleLigInputStream = function (inputStr) {
            _this.setState({ ligSearchText: inputStr });
            var filteredRes = _this.state.componentGroups.ligGroups.filter(function (g) {
                var gKeys = g[0].key.split(',');
                var cId1Arr = gKeys[0].split('-');
                return cId1Arr[2].toLowerCase().indexOf(inputStr.toLowerCase()) >= 0;
            });
            _this.setState({ ligGroups: filteredRes });
        };
        _this.carbInputStream = new rxjs_1.Subject();
        _this.handleCarbInputStream = function (inputStr) {
            _this.setState({ carbSearchText: inputStr });
            var filteredRes = _this.state.componentGroups.carbGroups.filter(function (g) {
                var gKeys = g[0].key.split(',');
                var cId1Arr = gKeys[0].split('-');
                cId1Arr.splice(0, 2);
                cId1Arr.pop();
                return cId1Arr.join('-').toLowerCase().indexOf(inputStr.toLowerCase()) >= 0;
            });
            _this.setState({ carbGroups: filteredRes });
        };
        _this.toggleVisible = function (e, action, type) {
            e.preventDefault();
            e.currentTarget.blur();
            var customState = _this.plugin.customState;
            customState.events.isBusy.next(true);
            var visualEntites = (type === 'ligands') ? _this.state.ligGroups : _this.state.carbGroups;
            setTimeout(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                var visualEntites_1, visualEntites_1_1, visualEntity, e_1_1;
                var e_1, _a;
                return tslib_1.__generator(this, function (_b) {
                    switch (_b.label) {
                        case 0:
                            _b.trys.push([0, 5, 6, 11]);
                            visualEntites_1 = tslib_1.__asyncValues(visualEntites);
                            _b.label = 1;
                        case 1: return [4 /*yield*/, visualEntites_1.next()];
                        case 2:
                            if (!(visualEntites_1_1 = _b.sent(), !visualEntites_1_1.done)) return [3 /*break*/, 4];
                            visualEntity = visualEntites_1_1.value;
                            this.plugin.managers.structure.hierarchy.toggleVisibility(visualEntity, action);
                            _b.label = 3;
                        case 3: return [3 /*break*/, 1];
                        case 4: return [3 /*break*/, 11];
                        case 5:
                            e_1_1 = _b.sent();
                            e_1 = { error: e_1_1 };
                            return [3 /*break*/, 11];
                        case 6:
                            _b.trys.push([6, , 9, 10]);
                            if (!(visualEntites_1_1 && !visualEntites_1_1.done && (_a = visualEntites_1.return))) return [3 /*break*/, 8];
                            return [4 /*yield*/, _a.call(visualEntites_1)];
                        case 7:
                            _b.sent();
                            _b.label = 8;
                        case 8: return [3 /*break*/, 10];
                        case 9:
                            if (e_1) throw e_1.error;
                            return [7 /*endfinally*/];
                        case 10: return [7 /*endfinally*/];
                        case 11:
                            ;
                            customState.events.isBusy.next(false);
                            return [2 /*return*/];
                    }
                });
            }); });
        };
        _this.showHideAllControls = function (type) {
            return React.createElement(React.Fragment, null,
                React.createElement(common_1.Button, { icon: icons_1.CheckSvg, flex: true, onClick: function (e) { return _this.toggleVisible(e, 'show', type); }, style: { flex: '0 0 50px', textAlign: 'center', fontSize: '80%', color: '#9cacc3', padding: 0 }, title: "Show all " + type, disabled: false }, "All"),
                React.createElement(common_1.Button, { icon: icons_1.CloseSvg, flex: true, onClick: function (e) { return _this.toggleVisible(e, 'hide', type); }, style: { flex: '0 0 50px', textAlign: 'center', fontSize: '80%', color: '#9cacc3', padding: 0 }, title: "Hide all " + type, disabled: false }, "None"));
        };
        _this.clearLigSearch = function (e) {
            e.preventDefault();
            _this.setState({ ligSearchText: '' });
            _this.ligInputStream.next('');
            e.currentTarget.blur();
        };
        _this.clearCarbSearch = function (e) {
            e.preventDefault();
            _this.setState({ carbSearchText: '' });
            _this.carbInputStream.next('');
            e.currentTarget.blur();
        };
        _this.collapseSection = function (e, type) {
            e.preventDefault();
            e.currentTarget.blur();
            if (type === 'ligands') {
                _this.setState({ isLigCollapsed: !_this.state.isLigCollapsed });
            }
            else {
                _this.setState({ isCarbCollapsed: !_this.state.isCarbCollapsed });
            }
        };
        _this.sectionHeader = function (type) {
            var showHideAllControls = (type === 'ligands') ? _this.showHideAllControls('ligands') : _this.showHideAllControls('carbohydrates');
            var title = (type === 'ligands') ? 'Ligand' : 'Carbohydrates';
            var visibleVisuals = (type === 'ligands') ? _this.state.ligGroups.length : _this.state.carbGroups.length;
            var totalVisuals = (type === 'ligands') ? _this.state.componentGroups.ligGroups.length : _this.state.componentGroups.carbGroups.length;
            return React.createElement("div", { className: 'msp-flex-row', style: { marginTop: '6px' } },
                React.createElement("button", { className: 'msp-form-control msp-control-button-label msp-transform-header-brand-gray', style: { textAlign: 'left' }, onClick: function (e) { return _this.collapseSection(e, type); } },
                    React.createElement("span", null,
                        React.createElement("strong", null, title)),
                    React.createElement("small", { style: { color: '#7d91b0' } },
                        " ( ",
                        visibleVisuals,
                        visibleVisuals < totalVisuals ? " / " + totalVisuals : '',
                        " )")),
                visibleVisuals > 1 && showHideAllControls);
        };
        return _this;
    }
    ComponentListControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, function () {
            _this.categoriseGroups();
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
    };
    ComponentListControls.prototype.componentDidUpdate = function () {
        var _this = this;
        var customState = this.plugin.customState;
        if (customState.events && !this.state.segmentWatch) {
            this.setState({ segmentWatch: true });
            this.subscribe(customState.events.segmentUpdate, function () {
                _this.categoriseGroups();
                _this.forceUpdate();
            });
        }
        this.subscribe(this.ligInputStream.pipe(operators_1.debounceTime(1000 / 24)), function (e) { return _this.handleLigInputStream(e); });
        this.subscribe(this.carbInputStream.pipe(operators_1.debounceTime(1000 / 24)), function (e) { return _this.handleCarbInputStream(e); });
    };
    ComponentListControls.prototype.categoriseGroups = function () {
        var componentGroupsVal = { nonLigGroups: [], ligGroups: [], carbGroups: [] };
        var componentGroups = this.plugin.managers.structure.hierarchy.currentComponentGroups;
        var customState = this.plugin.customState;
        componentGroups.forEach(function (g) {
            var isLigandView = false;
            if (customState.initParams && customState.initParams.superpositionParams && customState.initParams.superpositionParams.ligandView) {
                isLigandView = true;
            }
            if (isLigandView) {
                var gKeys = g[0].key.split(',');
                var cId1Arr = gKeys[0].split('-');
                if (gKeys.indexOf('superposition-focus-surr-sel') === -1) {
                    if (cId1Arr[cId1Arr.length - 1] !== (customState.superpositionState.activeSegment - 1) + '')
                        return;
                    if (gKeys.indexOf('superposition-ligand-sel') >= 0) {
                        componentGroupsVal.ligGroups.push(g);
                    }
                    else if (gKeys.indexOf('superposition-carb-sel') >= 0) {
                        componentGroupsVal.carbGroups.push(g);
                    }
                    else {
                        componentGroupsVal.nonLigGroups.push(g);
                    }
                }
                else {
                    componentGroupsVal.nonLigGroups.push(g);
                }
            }
            else {
                var gKeys = g[0].key.split(',');
                if (gKeys.indexOf('superposition-focus-surr-sel') >= 0 || gKeys.indexOf("Chain-" + (customState.superpositionState.activeSegment - 1)) >= 0) {
                    componentGroupsVal.nonLigGroups.push(g);
                }
            }
        });
        this.setState({ componentGroups: componentGroupsVal, ligGroups: componentGroupsVal.ligGroups, carbGroups: componentGroupsVal.carbGroups, ligSearchText: '', carbSearchText: '' });
    };
    ComponentListControls.prototype.render = function () {
        var _this = this;
        var ligSearchControls = React.createElement("div", { className: 'msp-mapped-parameter-group', style: { fontSize: '90%' } },
            React.createElement("div", { className: 'msp-control-row msp-transform-header-brand-gray', style: { height: '33px' } },
                React.createElement("span", { className: 'msp-control-row-label' }, "Search Ligand"),
                React.createElement("div", { className: 'msp-control-row-ctrl' },
                    React.createElement("input", { type: 'text', placeholder: 'Enter HET code', disabled: this.state.isBusy, onChange: function (e) { return _this.ligInputStream.next(e.target.value); }, value: this.state.ligSearchText, maxLength: 3 }))),
            React.createElement(common_1.IconButton, { svg: icons_1.CloseSvg, flex: true, onClick: this.clearLigSearch, style: { flex: '0 0 24px', padding: 0 }, disabled: this.state.ligSearchText === '' || this.state.isBusy, toggleState: this.state.ligSearchText !== '', title: 'Clear search input' }));
        var carbSearchControls = React.createElement("div", { className: 'msp-mapped-parameter-group', style: { fontSize: '90%' } },
            React.createElement("div", { className: 'msp-control-row msp-transform-header-brand-gray', style: { height: '33px' } },
                React.createElement("span", { className: 'msp-control-row-label' }, "Search Carbohydrate"),
                React.createElement("div", { className: 'msp-control-row-ctrl' },
                    React.createElement("input", { type: 'text', placeholder: 'Enter HET code', disabled: this.state.isBusy, onChange: function (e) { return _this.carbInputStream.next(e.target.value); }, value: this.state.carbSearchText, maxLength: 3 }))),
            React.createElement(common_1.IconButton, { svg: icons_1.CloseSvg, flex: true, onClick: this.clearCarbSearch, style: { flex: '0 0 24px', padding: 0 }, disabled: this.state.carbSearchText === '' || this.state.isBusy, toggleState: this.state.carbSearchText !== '', title: 'Clear search input' }));
        var ligSectionHeader = this.sectionHeader('ligands');
        var carbSectionHeader = this.sectionHeader('carbohydrates');
        return React.createElement(React.Fragment, null,
            (this.state.componentGroups.nonLigGroups.length > 0) && React.createElement("div", null, this.state.componentGroups.nonLigGroups.map(function (g) { return React.createElement(StructureComponentGroup, { key: g[0].cell.transform.ref, group: g, boldHeader: true }); })),
            (this.state.componentGroups.ligGroups.length > 0) && ligSectionHeader,
            (!this.state.isLigCollapsed && this.state.componentGroups.ligGroups.length > 5) && ligSearchControls,
            (this.state.componentGroups.ligGroups.length > 0) && React.createElement("div", { className: 'msp-control-offset', style: { maxHeight: '800px', overflowY: 'auto' } }, !this.state.isLigCollapsed && this.state.ligGroups.map(function (g) { return React.createElement(StructureComponentGroup, { key: g[0].cell.transform.ref, group: g, boldHeader: false }); })),
            (this.state.componentGroups.carbGroups.length > 0) && carbSectionHeader,
            (!this.state.isCarbCollapsed && this.state.componentGroups.carbGroups.length > 5) && carbSearchControls,
            (this.state.componentGroups.carbGroups.length > 0) && React.createElement("div", { className: 'msp-control-offset', style: { maxHeight: '800px', overflowY: 'auto' } }, !this.state.isCarbCollapsed && this.state.carbGroups.map(function (g) { return React.createElement(StructureComponentGroup, { key: g[0].cell.transform.ref, group: g, boldHeader: false }); })));
    };
    return ComponentListControls;
}(base_1.PurePluginUIComponent));
var StructureComponentGroup = /** @class */ (function (_super) {
    tslib_1.__extends(StructureComponentGroup, _super);
    function StructureComponentGroup() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            action: void 0,
            isHidden: false,
            isBusy: false
        };
        _this.checkAllHidden = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var allHidden, _i, _a, c;
            return tslib_1.__generator(this, function (_b) {
                allHidden = true;
                for (_i = 0, _a = this.props.group; _i < _a.length; _i++) {
                    c = _a[_i];
                    if (!c.cell.state.isHidden) {
                        allHidden = false;
                        break;
                    }
                }
                if (allHidden)
                    this.setState({ isHidden: true });
                return [2 /*return*/];
            });
        }); };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            _this.plugin.managers.structure.component.toggleVisibility(_this.props.group);
            _this.setState({ isHidden: !_this.state.isHidden });
        };
        _this.toggleAction = function () { return _this.setState({ action: _this.state.action === 'action' ? void 0 : 'action' }); };
        _this.highlight = function (e) {
            e.preventDefault();
            if (!_this.props.group[0].cell.parent)
                return;
            commands_1.PluginCommands.Interactivity.Object.Highlight(_this.plugin, { state: _this.props.group[0].cell.parent, ref: _this.props.group.map(function (c) { return c.cell.transform.ref; }) });
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            commands_1.PluginCommands.Interactivity.ClearHighlights(_this.plugin);
        };
        _this.focus = function () {
            var allHidden = true;
            for (var _i = 0, _a = _this.props.group; _i < _a.length; _i++) {
                var c = _a[_i];
                if (!c.cell.state.isHidden) {
                    allHidden = false;
                    break;
                }
            }
            if (allHidden) {
                _this.plugin.managers.structure.hierarchy.toggleVisibility(_this.props.group, 'show');
            }
            _this.plugin.managers.camera.focusSpheres(_this.props.group, function (e) {
                var _a;
                if (e.cell.state.isHidden)
                    return;
                return (_a = e.cell.obj) === null || _a === void 0 ? void 0 : _a.data.boundary.sphere;
            });
        };
        return _this;
    }
    Object.defineProperty(StructureComponentGroup.prototype, "pivot", {
        get: function () {
            return this.props.group[0];
        },
        enumerable: false,
        configurable: true
    });
    StructureComponentGroup.prototype.componentDidMount = function () {
        var _this = this;
        this.checkAllHidden();
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            var _a, _b;
            // if (State.ObjectEvent.isCell(e, this.pivot.cell)) this.forceUpdate();
            if (((_a = _this.pivot.cell.obj) === null || _a === void 0 ? void 0 : _a.label) === ((_b = e.cell.obj) === null || _b === void 0 ? void 0 : _b.label)) {
                if (!e.cell.state.isHidden) {
                    _this.setState({ isHidden: false });
                }
                else {
                    _this.checkAllHidden();
                }
            }
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
        this.subscribe(this.plugin.customState.events.isBusy, function (e) {
            _this.setState({ isBusy: e });
        });
    };
    StructureComponentGroup.prototype.render = function () {
        var _this = this;
        var _a;
        var component = this.pivot;
        var cell = component.cell;
        var label = (_a = cell.obj) === null || _a === void 0 ? void 0 : _a.label;
        var labelEle = this.props.boldHeader ? React.createElement("strong", null, label) : label;
        return React.createElement(React.Fragment, null,
            React.createElement("div", { className: 'msp-flex-row' },
                React.createElement(common_1.Button, { noOverflow: true, className: 'msp-control-button-label', title: label + " - Click to focus.", onClick: this.focus, style: { textAlign: 'left' }, disabled: this.state.isBusy }, labelEle),
                React.createElement(common_1.IconButton, { disabled: this.state.isBusy, svg: this.state.isHidden ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, toggleState: false, onClick: this.toggleVisible, title: (this.state.isHidden ? 'Show' : 'Hide') + " component", small: true, className: 'msp-form-control', flex: true }),
                React.createElement(common_1.IconButton, { disabled: this.state.isBusy, svg: icons_1.MoreHorizSvg, onClick: this.toggleAction, title: 'Actions', toggleState: this.state.action === 'action', className: 'msp-form-control', flex: true })),
            this.state.action === 'action' && React.createElement("div", { className: 'msp-accent-offset' },
                React.createElement("div", { style: { marginBottom: '6px' } }, component.representations.map(function (r) { return React.createElement(StructureRepresentationEntry, { group: _this.props.group, key: r.cell.transform.ref, representation: r }); }))));
    };
    return StructureComponentGroup;
}(base_1.PurePluginUIComponent));
var StructureRepresentationEntry = /** @class */ (function (_super) {
    tslib_1.__extends(StructureRepresentationEntry, _super);
    function StructureRepresentationEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isBusy: false,
            clusterVal: { cluster: 'All' }
        };
        _this.remove = function () { return _this.plugin.managers.structure.component.removeRepresentations(_this.props.group, _this.props.representation); };
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            _this.plugin.managers.structure.component.toggleVisibility(_this.props.group, _this.props.representation);
        };
        _this.update = function (params) {
            return _this.updateRepresentations(_this.props.group, _this.props.representation, params);
        };
        _this.selectCluster = function (params) {
            _this.setState({ clusterVal: { cluster: params.cluster } });
        };
        return _this;
    }
    StructureRepresentationEntry.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (mol_state_1.State.ObjectEvent.isCell(e, _this.props.representation.cell))
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.behaviors.state.isBusy, function (v) {
            _this.setState({ isBusy: v });
        });
        this.subscribe(this.plugin.customState.events.isBusy, function (e) {
            _this.setState({ isBusy: e });
        });
    };
    StructureRepresentationEntry.prototype.updateRepresentations = function (components, pivot, params) {
        var _a, _b, _c;
        if (components.length === 0)
            return Promise.resolve();
        var index = components[0].representations.indexOf(pivot);
        if (index < 0)
            return Promise.resolve();
        var superpositionState = this.plugin.customState.superpositionState;
        var filteredComps = [];
        if (this.state.clusterVal.cluster !== 'All') {
            var clusterData = superpositionState.segmentData[superpositionState.activeSegment - 1].clusters[parseInt(this.state.clusterVal.cluster) - 1];
            filteredComps = clusterData.map(function (s) {
                return s.pdb_id + "_" + s.struct_asym_id;
            });
            if (filteredComps.length === 0)
                return;
        }
        var update = this.plugin.state.data.build();
        for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
            var c = components_1[_i];
            // TODO: is it ok to use just the index here? Could possible lead to ugly edge cases, but perhaps not worth the trouble to "fix".
            var repr = c.representations[index];
            if (!repr)
                continue;
            if (repr.cell.transform.transformer !== pivot.cell.transform.transformer)
                continue;
            if (this.state.clusterVal.cluster !== 'All') {
                var rmIndex = filteredComps.indexOf(superpositionState.refMaps[repr.cell.transform.parent]);
                if (rmIndex === -1)
                    continue;
            }
            var updatedParams = {
                type: params.type ? params.type : (_a = repr.cell.params) === null || _a === void 0 ? void 0 : _a.values.type,
                colorTheme: params.colorTheme ? params.colorTheme : (_b = repr.cell.params) === null || _b === void 0 ? void 0 : _b.values.colorTheme,
                sizeTheme: params.sizeTheme ? params.sizeTheme : (_c = repr.cell.params) === null || _c === void 0 ? void 0 : _c.values.sizeTheme
            };
            update.to(repr.cell).update(updatedParams);
        }
        return update.commit({ canUndo: 'Update Representation' });
    };
    StructureRepresentationEntry.prototype.render = function () {
        var _a, _b, _c, _d, _e, _f;
        var repr = this.props.representation.cell;
        var superpositionState = this.plugin.customState.superpositionState;
        var clusterSelectArr = [['All', 'All']];
        superpositionState.segmentData[superpositionState.activeSegment - 1].clusters.forEach(function (c, i) {
            clusterSelectArr.push([(i + 1) + '', (i + 1) + '']);
        });
        var clusterOptions = {
            cluster: param_definition_1.ParamDefinition.Select('All', clusterSelectArr, { label: 'Select Cluster' })
        };
        var isSurrVisual = false;
        if (repr && repr.obj) {
            var reprObj = repr.obj;
            if (reprObj.tags && reprObj.tags.indexOf('superposition-focus-surr-repr') >= 0)
                isSurrVisual = true;
        }
        return React.createElement("div", { className: 'msp-representation-entry' }, repr.parent && React.createElement("div", null,
            (clusterSelectArr.length > 2 && !isSurrVisual) && React.createElement("div", { className: 'msp-representation-entry' },
                React.createElement(parameters_1.ParameterControls, { params: clusterOptions, values: this.state.clusterVal, onChangeValues: this.selectCluster, isDisabled: this.state.isBusy })),
            React.createElement("div", { className: 'msp-representation-entry' },
                React.createElement(parameters_1.ParameterControls, { params: { type: (_a = repr.params) === null || _a === void 0 ? void 0 : _a.definition.type }, values: { type: (_b = repr.params) === null || _b === void 0 ? void 0 : _b.values.type }, onChangeValues: this.update, isDisabled: this.state.isBusy })),
            React.createElement("div", { className: 'msp-representation-entry' },
                React.createElement(parameters_1.ParameterControls, { params: { colorTheme: (_c = repr.params) === null || _c === void 0 ? void 0 : _c.definition.colorTheme }, values: { colorTheme: (_d = repr.params) === null || _d === void 0 ? void 0 : _d.values.colorTheme }, onChangeValues: this.update, isDisabled: this.state.isBusy })),
            React.createElement("div", { className: 'msp-representation-entry' },
                React.createElement(parameters_1.ParameterControls, { params: { sizeTheme: (_e = repr.params) === null || _e === void 0 ? void 0 : _e.definition.sizeTheme }, values: { sizeTheme: (_f = repr.params) === null || _f === void 0 ? void 0 : _f.values.sizeTheme }, onChangeValues: this.update, isDisabled: this.state.isBusy }))));
    };
    return StructureRepresentationEntry;
}(base_1.PurePluginUIComponent));
//# sourceMappingURL=superposition-components.js.map

/***/ }),
/* 438 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.PDBeViewportControls = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var config_1 = __webpack_require__(101);
var common_1 = __webpack_require__(19);
var selection_1 = __webpack_require__(206);
var pdbe_screenshot_controls_1 = __webpack_require__(439);
var simple_settings_1 = __webpack_require__(392);
var viewport_1 = __webpack_require__(323);
var icons_1 = __webpack_require__(14);
var PDBeViewportControls = /** @class */ (function (_super) {
    tslib_1.__extends(PDBeViewportControls, _super);
    function PDBeViewportControls() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PDBeViewportControls.prototype.isBlack = function (customeState) {
        if (customeState && customeState.initParams && customeState.initParams.bgColor) {
            var color = customeState.initParams.bgColor;
            if (color.r === 0 && color.g === 0 && color.b === 0)
                return true;
        }
        return false;
    };
    PDBeViewportControls.prototype.render = function () {
        var customeState = this.plugin.customState;
        var showPDBeLink = false;
        var showControlToggle = true;
        var showControlInfo = true;
        if (customeState && customeState.initParams && customeState.initParams.moleculeId && customeState.initParams.pdbeLink)
            showPDBeLink = true;
        if (customeState && customeState.initParams && customeState.initParams.superposition)
            showPDBeLink = false;
        if (customeState && customeState.initParams && customeState.initParams.hideCanvasControls && customeState.initParams.hideCanvasControls.indexOf('controlToggle') > -1)
            showControlToggle = false;
        if (customeState && customeState.initParams && customeState.initParams.hideCanvasControls && customeState.initParams.hideCanvasControls.indexOf('controlInfo') > -1)
            showControlInfo = false;
        var bgColor = this.isBlack(customeState) ? '#fff' : '#555';
        var pdbeLink = {
            parentStyle: { width: 'auto' },
            containerStyle: { position: 'absolute', right: '10px', top: '10px' },
            style: { display: 'inline-block', fontSize: '14px', color: bgColor, borderBottom: 'none', cursor: 'pointer', textDecoration: 'none' },
            pdbeImg: {
                src: 'https://www.ebi.ac.uk/pdbe/entry/static/images/logos/PDBe/logo_T_64.png',
                alt: 'PDBe logo',
                style: { height: '12px', width: '12px', border: 0, position: 'absolute', margin: '4px 0 0 -13px' }
            }
        };
        var vwpBtnsTopMargin = { marginTop: '22px' };
        return React.createElement(React.Fragment, null,
            showPDBeLink && React.createElement("div", { style: pdbeLink.containerStyle },
                React.createElement("a", { className: 'msp-pdbe-link', style: pdbeLink.style, target: "_blank", href: "https://pdbe.org/" + customeState.initParams.moleculeId },
                    React.createElement("img", { src: pdbeLink.pdbeImg.src, alt: pdbeLink.pdbeImg.alt, style: pdbeLink.pdbeImg.style }),
                    customeState.initParams.moleculeId)),
            React.createElement("div", { className: 'msp-viewport-controls', onMouseMove: this.onMouseMove, style: showPDBeLink ? vwpBtnsTopMargin : void 0 },
                React.createElement("div", { className: 'msp-viewport-controls-buttons' },
                    React.createElement("div", null,
                        React.createElement("div", { className: 'msp-semi-transparent-background' }),
                        this.icon(icons_1.AutorenewSvg, this.resetCamera, 'Reset Camera')),
                    React.createElement("div", null,
                        React.createElement("div", { className: 'msp-semi-transparent-background' }),
                        this.icon(icons_1.CameraOutlinedSvg, this.toggleScreenshotExpanded, 'Screenshot / State Snapshot', this.state.isScreenshotExpanded)),
                    React.createElement("div", null,
                        React.createElement("div", { className: 'msp-semi-transparent-background' }),
                        showControlToggle && this.icon(icons_1.BuildOutlinedSvg, this.toggleControls, 'Toggle Controls Panel', this.plugin.layout.state.showControls),
                        this.plugin.config.get(config_1.PluginConfig.Viewport.ShowExpand) && this.icon(icons_1.FullscreenSvg, this.toggleExpanded, 'Toggle Expanded Viewport', this.plugin.layout.state.isExpanded),
                        showControlInfo && this.icon(icons_1.TuneSvg, this.toggleSettingsExpanded, 'Settings / Controls Info', this.state.isSettingsExpanded)),
                    this.plugin.config.get(config_1.PluginConfig.Viewport.ShowSelectionMode) && React.createElement("div", null,
                        React.createElement("div", { className: 'msp-semi-transparent-background' }),
                        React.createElement(selection_1.ToggleSelectionModeButton, null))),
                this.state.isScreenshotExpanded && React.createElement("div", { className: 'msp-viewport-controls-panel' },
                    React.createElement(common_1.ControlGroup, { header: 'Screenshot / State', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleScreenshotExpanded, topRightIcon: icons_1.CloseSvg, noTopMargin: true, childrenClassName: 'msp-viewport-controls-panel-controls' },
                        React.createElement(pdbe_screenshot_controls_1.DownloadScreenshotControls, { close: this.toggleScreenshotExpanded }))),
                this.state.isSettingsExpanded && React.createElement("div", { className: 'msp-viewport-controls-panel' },
                    React.createElement(common_1.ControlGroup, { header: 'Settings / Controls Info', title: 'Click to close.', initialExpanded: true, hideExpander: true, hideOffset: true, onHeaderClick: this.toggleSettingsExpanded, topRightIcon: icons_1.CloseSvg, noTopMargin: true, childrenClassName: 'msp-viewport-controls-panel-controls' },
                        React.createElement(simple_settings_1.SimpleSettingsControl, null)))));
    };
    return PDBeViewportControls;
}(viewport_1.ViewportControls));
exports.PDBeViewportControls = PDBeViewportControls;
//# sourceMappingURL=pdbe-viewport-controls.js.map

/***/ }),
/* 439 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.DownloadScreenshotControls = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var parameters_1 = __webpack_require__(66);
var base_1 = __webpack_require__(32);
var operators_1 = __webpack_require__(238);
var rxjs_1 = __webpack_require__(139);
var common_1 = __webpack_require__(19);
var commands_1 = __webpack_require__(26);
// import { StateExportImportControls, LocalStateSnapshotParams } from 'Molstar/mol-plugin-ui/state/snapshots';
var icons_1 = __webpack_require__(14);
var DownloadScreenshotControls = /** @class */ (function (_super) {
    tslib_1.__extends(DownloadScreenshotControls, _super);
    function DownloadScreenshotControls() {
        var _a, _b, _c;
        var _this = _super.apply(this, arguments) || this;
        _this.state = {
            showPreview: true,
            isDisabled: false,
            resolution: (_a = _this.plugin.helpers.viewportScreenshot) === null || _a === void 0 ? void 0 : _a.currentResolution,
            transparent: (_b = _this.plugin.helpers.viewportScreenshot) === null || _b === void 0 ? void 0 : _b.transparent,
            axes: (_c = _this.plugin.helpers.viewportScreenshot) === null || _c === void 0 ? void 0 : _c.axes
        };
        _this.imgRef = React.createRef();
        _this.updateQueue = new rxjs_1.Subject();
        _this.preview = function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var _a;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!this.imgRef.current)
                            return [2 /*return*/];
                        _a = this.imgRef.current;
                        return [4 /*yield*/, this.plugin.helpers.viewportScreenshot.imageData()];
                    case 1:
                        _a.src = _b.sent();
                        return [2 /*return*/];
                }
            });
        }); };
        _this.download = function () {
            var _a;
            (_a = _this.plugin.helpers.viewportScreenshot) === null || _a === void 0 ? void 0 : _a.download();
            _this.props.close();
        };
        _this.openTab = function () {
            // modified from https://stackoverflow.com/questions/16245767/creating-a-blob-from-a-base64-string-in-javascript/16245768#16245768
            var base64 = _this.imgRef.current.src;
            var byteCharacters = atob(base64.substr("data:image/png;base64,".length));
            var byteArrays = [];
            var sliceSize = Math.min(byteCharacters.length, 1024 * 1024);
            for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
                var byteNumbers = new Uint8Array(Math.min(sliceSize, byteCharacters.length - offset));
                for (var i = 0, _i = byteNumbers.length; i < _i; i++) {
                    byteNumbers[i] = byteCharacters.charCodeAt(offset + i);
                }
                byteArrays.push(byteNumbers);
            }
            var blob = new Blob(byteArrays, { type: 'image/png' });
            var blobUrl = URL.createObjectURL(blob);
            window.open(blobUrl, '_blank');
            _this.props.close();
        };
        _this.setProps = function (p) {
            if (p.name === 'resolution') {
                _this.plugin.helpers.viewportScreenshot.currentResolution = p.value;
                _this.setState({ resolution: p.value });
            }
            else if (p.name === 'transparent') {
                _this.plugin.helpers.viewportScreenshot.transparent = p.value;
                _this.setState({ transparent: p.value });
            }
            else if (p.name === 'axes') {
                _this.plugin.helpers.viewportScreenshot.axes = p.value;
                _this.setState({ axes: p.value });
            }
        };
        _this.downloadToFileJson = function () {
            commands_1.PluginCommands.State.Snapshots.DownloadToFile(_this.plugin, { type: 'json' });
        };
        _this.downloadToFileZip = function () {
            commands_1.PluginCommands.State.Snapshots.DownloadToFile(_this.plugin, { type: 'zip' });
        };
        _this.open = function (e) {
            if (!e.target.files || !e.target.files[0])
                return;
            commands_1.PluginCommands.State.Snapshots.OpenFile(_this.plugin, { file: e.target.files[0] });
        };
        return _this;
    }
    DownloadScreenshotControls.prototype.handlePreview = function () {
        if (this.state.showPreview) {
            this.preview();
        }
    };
    DownloadScreenshotControls.prototype.componentDidUpdate = function () {
        this.updateQueue.next();
    };
    DownloadScreenshotControls.prototype.componentDidMount = function () {
        var _this = this;
        if (!this.plugin.canvas3d)
            return;
        this.subscribe(operators_1.debounceTime(250)(this.updateQueue), function () { return _this.handlePreview(); });
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () {
            var _a;
            _this.plugin.helpers.viewportScreenshot.imagePass.setProps({
                multiSample: { mode: 'on', sampleLevel: 2 },
                postprocessing: (_a = _this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.props.postprocessing
            });
            _this.updateQueue.next();
        });
        this.subscribe(operators_1.debounceTime(250)(this.plugin.canvas3d.didDraw), function () {
            if (_this.state.isDisabled)
                return;
            _this.updateQueue.next();
        });
        this.subscribe(this.plugin.state.data.behaviors.isUpdating, function (v) {
            _this.setState({ isDisabled: v });
            if (!v)
                _this.updateQueue.next();
        });
        this.handlePreview();
    };
    DownloadScreenshotControls.prototype.render = function () {
        return React.createElement("div", null,
            React.createElement("div", { className: 'msp-image-preview' },
                React.createElement("img", { ref: this.imgRef }),
                React.createElement("br", null),
                React.createElement("span", null, "Right-click the image to Copy.")),
            React.createElement("div", { className: 'msp-flex-row' },
                React.createElement(common_1.Button, { icon: icons_1.GetAppSvg, onClick: this.download, disabled: this.state.isDisabled }, "Download"),
                React.createElement(common_1.Button, { icon: icons_1.LaunchSvg, onClick: this.openTab, disabled: this.state.isDisabled }, "Open in new Tab")),
            React.createElement(parameters_1.ParameterControls, { params: this.plugin.helpers.viewportScreenshot.params, values: this.plugin.helpers.viewportScreenshot.values, onChange: this.setProps, isDisabled: this.state.isDisabled }));
    };
    return DownloadScreenshotControls;
}(base_1.PluginUIComponent));
exports.DownloadScreenshotControls = DownloadScreenshotControls;
//# sourceMappingURL=pdbe-screenshot-controls.js.map

/***/ }),
/* 440 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.subscribeToComponentEvents = void 0;
function subscribeToComponentEvents(wrapperCtx) {
    document.addEventListener('PDB.interactions.click', function (e) {
        if (typeof e.detail !== 'undefined') {
            var data = e.detail.interacting_nodes ? { data: e.detail.interacting_nodes } : { data: [e.detail.selected_node] };
            data.data[0]['focus'] = true;
            wrapperCtx.visual.select(data);
        }
    });
    document.addEventListener('PDB.interactions.mouseover', function (e) {
        if (typeof e.detail !== 'undefined') {
            var data = e.detail.interacting_nodes ? { data: e.detail.interacting_nodes } : { data: [e.detail.selected_node] };
            wrapperCtx.visual.highlight(data);
        }
    });
    document.addEventListener('PDB.interactions.mouseout', function (e) {
        wrapperCtx.visual.clearHighlight();
    });
    document.addEventListener('PDB.topologyViewer.click', function (e) {
        if (typeof e.eventData !== 'undefined') {
            // Create query object from event data
            var highlightQuery = {
                entity_id: e.eventData.entityId,
                struct_asym_id: e.eventData.structAsymId,
                start_residue_number: e.eventData.residueNumber,
                end_residue_number: e.eventData.residueNumber,
                sideChain: true,
                focus: true
            };
            // Call highlightAnnotation
            wrapperCtx.visual.select({ data: [highlightQuery] });
        }
    });
    document.addEventListener('PDB.topologyViewer.mouseover', function (e) {
        if (typeof e.eventData !== 'undefined') {
            // Abort if entryid do not match or viewer type is unipdb
            // if(e.eventData.entryId != scope.pdbId) return;
            // Create query object from event data
            var highlightQuery = {
                entity_id: e.eventData.entityId,
                struct_asym_id: e.eventData.structAsymId,
                start_residue_number: e.eventData.residueNumber,
                end_residue_number: e.eventData.residueNumber
            };
            // Call highlightAnnotation
            wrapperCtx.visual.highlight({ data: [highlightQuery] });
        }
    });
    document.addEventListener('PDB.topologyViewer.mouseout', function (e) {
        wrapperCtx.visual.clearHighlight();
    });
    document.addEventListener('protvista-mouseover', function (e) {
        if (typeof e.detail !== 'undefined') {
            var highlightQuery = undefined;
            // Create query object from event data
            if (e.detail.start && e.detail.end) {
                highlightQuery = {
                    start_residue_number: parseInt(e.detail.start),
                    end_residue_number: parseInt(e.detail.end)
                };
            }
            if (e.detail.feature && e.detail.feature.entityId)
                highlightQuery['entity_id'] = e.detail.feature.entityId + '';
            if (e.detail.feature && e.detail.feature.bestChainId)
                highlightQuery['struct_asym_id'] = e.detail.feature.bestChainId;
            if (highlightQuery)
                wrapperCtx.visual.highlight({ data: [highlightQuery] });
        }
    });
    document.addEventListener('protvista-mouseout', function (e) {
        wrapperCtx.visual.clearHighlight();
    });
    document.addEventListener('protvista-click', function (e) {
        if (typeof e.detail !== 'undefined') {
            var showInteraction = false;
            var highlightQuery = undefined;
            // Create query object from event data
            if (e.detail.start && e.detail.end) {
                highlightQuery = {
                    start_residue_number: parseInt(e.detail.start),
                    end_residue_number: parseInt(e.detail.end)
                };
            }
            if (e.detail.feature && e.detail.feature.entityId)
                highlightQuery['entity_id'] = e.detail.feature.entityId + '';
            if (e.detail.feature && e.detail.feature.bestChainId)
                highlightQuery['struct_asym_id'] = e.detail.feature.bestChainId;
            if (e.detail.feature && e.detail.feature.accession && e.detail.feature.accession.split(' ')[0] === 'Chain' || e.detail.feature.tooltipContent === 'Ligand binding site') {
                showInteraction = true;
            }
            if (e.detail.start === e.detail.end)
                showInteraction = true;
            if (highlightQuery) {
                if (showInteraction) {
                    highlightQuery['sideChain'] = true;
                }
                else {
                    var selColor = undefined;
                    if (e.detail.trackIndex > -1 && e.detail.feature.locations && e.detail.feature.locations[0].fragments[e.detail.trackIndex].color)
                        selColor = e.detail.feature.locations[0].fragments[e.detail.trackIndex].color;
                    if (typeof selColor == 'undefined' && e.detail.feature.color)
                        selColor = e.detail.feature.color;
                    if (typeof selColor == 'undefined' && e.detail.color)
                        selColor = e.detail.color;
                    if (typeof selColor == 'undefined') {
                        selColor = { r: 65, g: 96, b: 91 };
                    }
                    else {
                        var isRgb = /rgb/g;
                        if (isRgb.test(selColor)) {
                            var rgbArr = selColor.substring(4, selColor.length - 1).split(',');
                            selColor = { r: rgbArr[0], g: rgbArr[1], b: rgbArr[2] };
                        }
                    }
                    highlightQuery['color'] = selColor;
                }
                highlightQuery['focus'] = true;
                wrapperCtx.visual.select({ data: [highlightQuery] });
            }
        }
    });
    var elementTypeArrForRange = ['uniprot', 'pfam', 'cath', 'scop', 'strand', 'helice'];
    var elementTypeArrForSingle = ['chain', 'quality', 'quality_outlier', 'binding site', 'alternate conformer'];
    document.addEventListener('PDB.seqViewer.click', function (e) {
        if (typeof e.eventData !== 'undefined') {
            // Abort if entryid and entityid do not match or viewer type is unipdb
            // if(e.eventData.entryId != scope.pdbId) return;
            if (typeof e.eventData.elementData !== 'undefined' && elementTypeArrForSingle.indexOf(e.eventData.elementData.elementType) > -1) {
                // Create query object from event data
                var highlightQuery = {
                    entity_id: e.eventData.entityId,
                    struct_asym_id: e.eventData.elementData.pathData.struct_asym_id,
                    start_residue_number: e.eventData.residueNumber,
                    end_residue_number: e.eventData.residueNumber,
                    sideChain: true,
                    focus: true
                };
                // Call highlightAnnotation
                wrapperCtx.visual.select({ data: [highlightQuery] });
            }
            else if (typeof e.eventData.elementData !== 'undefined' && elementTypeArrForRange.indexOf(e.eventData.elementData.elementType) > -1) {
                var seqColorArray = e.eventData.elementData.color;
                // Create query object from event data
                var highlightQuery = {
                    entity_id: e.eventData.entityId,
                    struct_asym_id: e.eventData.elementData.pathData.struct_asym_id,
                    start_residue_number: e.eventData.elementData.pathData.start.residue_number,
                    end_residue_number: e.eventData.elementData.pathData.end.residue_number,
                    color: { r: seqColorArray[0], g: seqColorArray[1], b: seqColorArray[2] },
                    focus: true
                };
                wrapperCtx.visual.select({ data: [highlightQuery] });
            }
        }
    });
    document.addEventListener('PDB.seqViewer.mouseover', function (e) {
        if (typeof e.eventData !== 'undefined') {
            // Abort if entryid and entityid do not match or viewer type is unipdb
            // if(e.eventData.entryId != scope.pdbId) return;
            if (typeof e.eventData.elementData !== 'undefined' && elementTypeArrForSingle.indexOf(e.eventData.elementData.elementType) > -1) {
                // Create query object from event data
                var highlightQuery = {
                    entity_id: e.eventData.entityId,
                    struct_asym_id: e.eventData.elementData.pathData.struct_asym_id,
                    start_residue_number: e.eventData.residueNumber,
                    end_residue_number: e.eventData.residueNumber,
                    focus: true
                };
                wrapperCtx.visual.select({ data: [highlightQuery] });
            }
            else if (typeof e.eventData.elementData !== 'undefined' && elementTypeArrForRange.indexOf(e.eventData.elementData.elementType) > -1) {
                // Create query object from event data
                var highlightQuery = {
                    entity_id: e.eventData.entityId,
                    struct_asym_id: e.eventData.elementData.pathData.struct_asym_id,
                    start_residue_number: e.eventData.elementData.pathData.start.residue_number,
                    end_residue_number: e.eventData.elementData.pathData.end.residue_number
                };
                // Call highlightAnnotation
                wrapperCtx.visual.highlight({ data: [highlightQuery] });
            }
        }
    });
    document.addEventListener('PDB.seqViewer.mouseout', function (e) {
        wrapperCtx.visual.clearHighlight();
    });
}
exports.subscribeToComponentEvents = subscribeToComponentEvents;
//# sourceMappingURL=subscribe-events.js.map

/***/ }),
/* 441 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.LeftPanelControls = exports.WavesIconSvg = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var canvas3d_1 = __webpack_require__(158);
var commands_1 = __webpack_require__(26);
var mol_state_1 = __webpack_require__(13);
var base_1 = __webpack_require__(32);
var common_1 = __webpack_require__(19);
var parameters_1 = __webpack_require__(66);
var actions_1 = __webpack_require__(387);
var snapshots_1 = __webpack_require__(285);
var tree_1 = __webpack_require__(376);
var help_1 = __webpack_require__(189);
var segment_tree_1 = __webpack_require__(442);
var icons_1 = __webpack_require__(14);
var help_2 = __webpack_require__(189);
var _WavesIcon = React.createElement("svg", { width: '24px', height: '24px', viewBox: '0 0 24 24' },
    React.createElement("path", { d: "M17 16.99c-1.35 0-2.2.42-2.95.8-.65.33-1.18.6-2.05.6-.9 0-1.4-.25-2.05-.6-.75-.38-1.57-.8-2.95-.8s-2.2.42-2.95.8c-.65.33-1.17.6-2.05.6v1.95c1.35 0 2.2-.42 2.95-.8.65-.33 1.17-.6 2.05-.6s1.4.25 2.05.6c.75.38 1.57.8 2.95.8s2.2-.42 2.95-.8c.65-.33 1.18-.6 2.05-.6.9 0 1.4.25 2.05.6.75.38 1.58.8 2.95.8v-1.95c-.9 0-1.4-.25-2.05-.6-.75-.38-1.6-.8-2.95-.8zm0-4.45c-1.35 0-2.2.43-2.95.8-.65.32-1.18.6-2.05.6-.9 0-1.4-.25-2.05-.6-.75-.38-1.57-.8-2.95-.8s-2.2.43-2.95.8c-.65.32-1.17.6-2.05.6v1.95c1.35 0 2.2-.43 2.95-.8.65-.35 1.15-.6 2.05-.6s1.4.25 2.05.6c.75.38 1.57.8 2.95.8s2.2-.43 2.95-.8c.65-.35 1.15-.6 2.05-.6s1.4.25 2.05.6c.75.38 1.58.8 2.95.8v-1.95c-.9 0-1.4-.25-2.05-.6-.75-.38-1.6-.8-2.95-.8zm2.95-8.08c-.75-.38-1.58-.8-2.95-.8s-2.2.42-2.95.8c-.65.32-1.18.6-2.05.6-.9 0-1.4-.25-2.05-.6-.75-.37-1.57-.8-2.95-.8s-2.2.42-2.95.8c-.65.33-1.17.6-2.05.6v1.93c1.35 0 2.2-.43 2.95-.8.65-.33 1.17-.6 2.05-.6s1.4.25 2.05.6c.75.38 1.57.8 2.95.8s2.2-.43 2.95-.8c.65-.32 1.18-.6 2.05-.6.9 0 1.4.25 2.05.6.75.38 1.58.8 2.95.8V5.04c-.9 0-1.4-.25-2.05-.58zM17 8.09c-1.35 0-2.2.43-2.95.8-.65.35-1.15.6-2.05.6s-1.4-.25-2.05-.6c-.75-.38-1.57-.8-2.95-.8s-2.2.43-2.95.8c-.65.35-1.15.6-2.05.6v1.95c1.35 0 2.2-.43 2.95-.8.65-.32 1.18-.6 2.05-.6s1.4.25 2.05.6c.75.38 1.57.8 2.95.8s2.2-.43 2.95-.8c.65-.32 1.18-.6 2.05-.6.9 0 1.4.25 2.05.6.75.38 1.58.8 2.95.8V9.49c-.9 0-1.4-.25-2.05-.6-.75-.38-1.6-.8-2.95-.8z" }));
function WavesIconSvg() { return _WavesIcon; }
exports.WavesIconSvg = WavesIconSvg;
var LeftPanelControls = /** @class */ (function (_super) {
    tslib_1.__extends(LeftPanelControls, _super);
    function LeftPanelControls() {
        var _a;
        var _this = _super.apply(this, arguments) || this;
        _this.state = { tab: _this.plugin.behaviors.layout.leftPanelTabName.value };
        _this.set = function (tab) {
            if (_this.state.tab === tab) {
                _this.setState({ tab: 'none' }, function () { return _this.plugin.behaviors.layout.leftPanelTabName.next('none'); });
                commands_1.PluginCommands.Layout.Update(_this.plugin, { state: { regionState: tslib_1.__assign(tslib_1.__assign({}, _this.plugin.layout.state.regionState), { left: 'collapsed' }) } });
                return;
            }
            _this.setState({ tab: tab }, function () { return _this.plugin.behaviors.layout.leftPanelTabName.next(tab); });
            if (_this.plugin.layout.state.regionState.left !== 'full') {
                commands_1.PluginCommands.Layout.Update(_this.plugin, { state: { regionState: tslib_1.__assign(tslib_1.__assign({}, _this.plugin.layout.state.regionState), { left: 'full' }) } });
            }
        };
        _this.tabs = {
            'none': React.createElement(React.Fragment, null),
            'root': React.createElement(React.Fragment, null,
                React.createElement(common_1.SectionHeader, { icon: icons_1.HomeOutlinedSvg, title: 'Home' }),
                React.createElement(actions_1.StateObjectActions, { state: _this.plugin.state.data, nodeRef: mol_state_1.StateTransform.RootRef, hideHeader: true, initiallyCollapsed: true, alwaysExpandFirst: true }),
                ((_a = _this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.remoteState) !== 'none' && React.createElement(snapshots_1.RemoteStateSnapshots, { listOnly: true })),
            'data': React.createElement(React.Fragment, null,
                React.createElement(common_1.SectionHeader, { icon: icons_1.AccountTreeOutlinedSvg, title: React.createElement(React.Fragment, null,
                        React.createElement(RemoveAllButton, null),
                        " State Tree") }),
                React.createElement(tree_1.StateTree, { state: _this.plugin.state.data })),
            'segments': React.createElement(React.Fragment, null,
                React.createElement(segment_tree_1.SegmentTree, null)),
            'states': React.createElement(snapshots_1.StateSnapshots, null),
            'settings': React.createElement(React.Fragment, null,
                React.createElement(common_1.SectionHeader, { icon: icons_1.TuneSvg, title: 'Plugin Settings' }),
                React.createElement(FullSettings, null)),
            'help': React.createElement(React.Fragment, null,
                React.createElement(common_1.SectionHeader, { icon: icons_1.HelpOutlineSvg, title: 'Help' }),
                React.createElement(help_1.HelpContent, null),
                React.createElement(SuperpositionHelpContent, null))
        };
        return _this;
    }
    LeftPanelControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.layout.leftPanelTabName, function (tab) {
            if (_this.state.tab !== tab)
                _this.setState({ tab: tab });
            if (tab === 'none' && _this.plugin.layout.state.regionState.left !== 'collapsed') {
                commands_1.PluginCommands.Layout.Update(_this.plugin, { state: { regionState: tslib_1.__assign(tslib_1.__assign({}, _this.plugin.layout.state.regionState), { left: 'collapsed' }) } });
            }
        });
        this.subscribe(this.plugin.state.data.events.changed, function (_a) {
            var state = _a.state;
            if (_this.state.tab !== 'data')
                return;
            if (state.cells.size === 1)
                _this.set('root');
        });
    };
    LeftPanelControls.prototype.render = function () {
        var _this = this;
        var tab = this.state.tab;
        var customState = this.plugin.customState;
        return React.createElement("div", { className: 'msp-left-panel-controls' },
            React.createElement("div", { className: 'msp-left-panel-controls-buttons' },
                React.createElement(common_1.IconButton, { svg: icons_1.HelpOutlineSvg, toggleState: tab === 'help', transparent: true, onClick: function () { return _this.set('help'); }, title: 'Help' }),
                customState && customState.initParams && customState.initParams.superposition && React.createElement(common_1.IconButton, { svg: WavesIconSvg, toggleState: tab === 'segments', transparent: true, onClick: function () { return _this.set('segments'); }, title: 'Superpose segments' }),
                React.createElement("div", { className: 'msp-left-panel-controls-buttons-bottom' },
                    React.createElement(common_1.IconButton, { svg: icons_1.TuneSvg, toggleState: tab === 'settings', transparent: true, onClick: function () { return _this.set('settings'); }, title: 'Settings' }))),
            React.createElement("div", { className: 'msp-scrollable-container' }, this.tabs[tab]));
    };
    return LeftPanelControls;
}(base_1.PluginUIComponent));
exports.LeftPanelControls = LeftPanelControls;
// class DataIcon extends PluginUIComponent<{ set: (tab: LeftPanelTabName) => void }, { changed: boolean }> {
//     state = { changed: false };
//     get tab() {
//         return this.plugin.behaviors.layout.leftPanelTabName.value;
//     }
//     componentDidMount() {
//         this.subscribe(this.plugin.behaviors.layout.leftPanelTabName, tab => {
//             if (this.tab === 'data') this.setState({ changed: false });
//             else this.forceUpdate();
//         });
//         this.subscribe(this.plugin.state.data.events.changed, state => {
//             if (this.tab !== 'data') this.setState({ changed: true });
//         });
//     }
//     render() {
//         return <IconButton
//             svg={AccountTreeOutlinedSvg} toggleState={this.tab === 'data'} transparent onClick={() => this.props.set('data')} title='State Tree'
//             style={{ position: 'relative' }} extraContent={this.state.changed ? <div className='msp-left-panel-controls-button-data-dirty' /> : void 0} />;
//     }
// }
var FullSettings = /** @class */ (function (_super) {
    tslib_1.__extends(FullSettings, _super);
    function FullSettings() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.setSettings = function (p) {
            var _a;
            commands_1.PluginCommands.Canvas3D.SetSettings(_this.plugin, { settings: (_a = {}, _a[p.name] = p.value, _a) });
        };
        return _this;
    }
    FullSettings.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.layout.events.updated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.canvas3d.camera.stateChanged, function (state) {
            if (state.radiusMax !== undefined || state.radius !== undefined) {
                _this.forceUpdate();
            }
        });
    };
    FullSettings.prototype.render = function () {
        return React.createElement(React.Fragment, null, this.plugin.canvas3d && React.createElement(React.Fragment, null,
            React.createElement(common_1.SectionHeader, { title: 'Viewport' }),
            React.createElement(parameters_1.ParameterControls, { params: canvas3d_1.Canvas3DParams, values: this.plugin.canvas3d.props, onChange: this.setSettings })));
    };
    return FullSettings;
}(base_1.PluginUIComponent));
var RemoveAllButton = /** @class */ (function (_super) {
    tslib_1.__extends(RemoveAllButton, _super);
    function RemoveAllButton() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.remove = function (e) {
            e.preventDefault();
            commands_1.PluginCommands.State.RemoveObject(_this.plugin, { state: _this.plugin.state.data, ref: mol_state_1.StateTransform.RootRef });
        };
        return _this;
    }
    RemoveAllButton.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.created, function (e) {
            if (e.cell.transform.parent === mol_state_1.StateTransform.RootRef)
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.events.cell.removed, function (e) {
            if (e.parent === mol_state_1.StateTransform.RootRef)
                _this.forceUpdate();
        });
    };
    RemoveAllButton.prototype.render = function () {
        var count = this.plugin.state.data.tree.children.get(mol_state_1.StateTransform.RootRef).size;
        if (count === 0)
            return null;
        return React.createElement(common_1.IconButton, { svg: icons_1.DeleteOutlinedSvg, onClick: this.remove, title: 'Remove All', style: { display: 'inline-block' }, small: true, className: 'msp-no-hover-outline', transparent: true });
    };
    return RemoveAllButton;
}(base_1.PluginUIComponent));
function HelpSection(props) {
    return React.createElement("div", { className: 'msp-simple-help-section' }, props.header);
}
var SuperpositionHelpContent = /** @class */ (function (_super) {
    tslib_1.__extends(SuperpositionHelpContent, _super);
    function SuperpositionHelpContent() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SuperpositionHelpContent.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
    };
    SuperpositionHelpContent.prototype.render = function () {
        return React.createElement("div", null,
            React.createElement(HelpSection, { header: 'Superposition' }),
            React.createElement(help_2.HelpGroup, { header: 'Segment' },
                React.createElement(help_2.HelpText, null,
                    React.createElement("p", null, "Discrete UniProt sequence range mapped to the structure"))),
            React.createElement(help_2.HelpGroup, { header: 'Cluster' },
                React.createElement(help_2.HelpText, null,
                    React.createElement("p", null, "Structural chains that possess significantly close superposition Q-score"))),
            React.createElement(help_2.HelpGroup, { header: 'Representative chain' },
                React.createElement(help_2.HelpText, null,
                    React.createElement("p", null, "The best-ranked chain within a cluster chosen based on the model quality, resolution, observed residues ratio and UniProt sequence coverage"))));
    };
    return SuperpositionHelpContent;
}(base_1.PluginUIComponent));
//# sourceMappingURL=pdbe-left-panel.js.map

/***/ }),
/* 442 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SegmentTree = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var operators_1 = __webpack_require__(238);
var commands_1 = __webpack_require__(26);
var mol_state_1 = __webpack_require__(13);
var base_1 = __webpack_require__(32);
var common_1 = __webpack_require__(19);
var param_definition_1 = __webpack_require__(2);
var parameters_1 = __webpack_require__(66);
var mol_state_2 = __webpack_require__(13);
var superposition_1 = __webpack_require__(412);
var update_transform_1 = __webpack_require__(183);
var icons_1 = __webpack_require__(14);
var lists_1 = __webpack_require__(88);
var color_1 = __webpack_require__(24);
var builder_1 = __webpack_require__(10);
var rxjs_1 = __webpack_require__(139);
var SegmentTree = /** @class */ (function (_super) {
    tslib_1.__extends(SegmentTree, _super);
    function SegmentTree() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.getSegmentParams = function () {
            var customState = _this.customState;
            if (!customState.superpositionState || !customState.superpositionState.segmentData)
                return;
            var segmentData = customState.superpositionState.segmentData;
            var segmentArr = segmentData.map(function (segment, i) {
                var segmentLabel = i + 1 + " ( " + segment.segment_start + " - " + segment.segment_end + " )";
                return [segmentLabel, segmentLabel];
            });
            var segmentOptions = {
                segment: param_definition_1.ParamDefinition.Select('', segmentArr, { label: 'Select Segment', description: 'Select segment to view its clusters below' })
            };
            var segmentIndex = customState.superpositionState.activeSegment - 1;
            _this.setState({ segment: {
                    params: segmentOptions,
                    value: { segment: segmentArr[segmentIndex][0] }
                } });
            _this.setState({ isBusy: false });
        };
        _this.updateSegment = function (val) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var customState, updatedParams;
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                if (!this.state.segment)
                    return [2 /*return*/];
                customState = this.customState;
                customState.events.isBusy.next(true);
                // Hide pervious segement structures
                this.hideStructures(customState.superpositionState.activeSegment - 1);
                updatedParams = tslib_1.__assign({}, this.state.segment);
                updatedParams.value = val;
                this.setState({ segment: updatedParams });
                setTimeout(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                    var updatedSegmentIndex;
                    return tslib_1.__generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                updatedSegmentIndex = parseInt(val.segment.split(' ')[0]);
                                customState.superpositionState.activeSegment = updatedSegmentIndex;
                                // Display current segment visible structures
                                return [4 /*yield*/, this.displayStructures(customState.superpositionState.activeSegment - 1)];
                            case 1:
                                // Display current segment visible structures
                                _a.sent();
                                customState.events.isBusy.next(false);
                                this.plugin.customState.events.segmentUpdate.next(true);
                                return [2 /*return*/];
                        }
                    });
                }); }, 100);
                return [2 /*return*/, false];
            });
        }); };
        _this.hideStructures = function (segmentIndex) {
            // clear selections
            _this.plugin.managers.interactivity.lociSelects.deselectAll();
            // clear Focus
            _this.plugin.managers.structure.focus.clear();
            // remove measurements
            var measurements = _this.plugin.managers.structure.measurement.state;
            var measureTypes = ['labels', 'distances', 'angles', 'dihedrals'];
            var measurementCell = void 0;
            measureTypes.forEach(function (type) {
                if (measurementCell)
                    return;
                if (measurements[type][0]) {
                    measurementCell = _this.plugin.state.data.cells.get(measurements[type][0].transform.parent);
                }
            });
            if (measurementCell) {
                commands_1.PluginCommands.State.RemoveObject(_this.plugin, { state: measurementCell.parent, ref: measurementCell.transform.parent, removeParentGhosts: true });
            }
            // hide structures
            var customState = _this.customState;
            customState.superpositionState.visibleRefs[segmentIndex] = [];
            for (var _i = 0, _a = customState.superpositionState.loadedStructs[segmentIndex]; _i < _a.length; _i++) {
                var struct = _a[_i];
                var structRef = _this.customState.superpositionState.models[struct];
                if (structRef) {
                    var structHierarchy = _this.plugin.managers.structure.hierarchy.current.refs.get(structRef);
                    if (structHierarchy && structHierarchy.components) {
                        for (var _b = 0, _c = structHierarchy.components; _b < _c.length; _b++) {
                            var c = _c[_b];
                            if (c && c.cell && !c.cell.state.isHidden) {
                                customState.superpositionState.visibleRefs[segmentIndex].push(c.cell.transform.ref);
                                commands_1.PluginCommands.State.ToggleVisibility(_this.plugin, { state: c.cell.parent, ref: c.cell.transform.ref });
                            }
                        }
                    }
                }
            }
        };
        _this.displayStructures = function (segmentIndex) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var customState, loadStrs_1, _i, _a, ref, cell;
            var _this = this;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        customState = this.customState;
                        if (!(customState.superpositionState.visibleRefs[segmentIndex].length === 0)) return [3 /*break*/, 3];
                        loadStrs_1 = [];
                        customState.superpositionState.segmentData[segmentIndex].clusters.forEach(function (cluster) {
                            var entryList = [cluster[0]];
                            if (customState.initParams.superpositionParams && customState.initParams.superpositionParams.superposeAll) {
                                entryList = cluster;
                            }
                            entryList.forEach(function (str) {
                                var structStateId = str.pdb_id + "_" + str.struct_asym_id;
                                var structRef = customState.superpositionState.models[structStateId];
                                if (structRef) {
                                    var cell = _this.plugin.state.data.cells.get(structRef);
                                    var isHidden = cell.state.isHidden ? true : false;
                                    if (isHidden) {
                                        commands_1.PluginCommands.State.ToggleVisibility(_this.plugin, { state: cell.parent, ref: structRef });
                                        // PluginCommands.State.ToggleVisibility(this.plugin, { state: cell.parent!, ref: cell.transform.parent });
                                    }
                                }
                                else {
                                    loadStrs_1.push(str);
                                }
                            });
                        });
                        commands_1.PluginCommands.Camera.Reset(this.plugin);
                        if (!(loadStrs_1.length > 0)) return [3 /*break*/, 2];
                        return [4 /*yield*/, superposition_1.renderSuperposition(this.plugin, segmentIndex, loadStrs_1)];
                    case 1:
                        _b.sent();
                        _b.label = 2;
                    case 2: return [3 /*break*/, 4];
                    case 3:
                        for (_i = 0, _a = customState.superpositionState.visibleRefs[segmentIndex]; _i < _a.length; _i++) {
                            ref = _a[_i];
                            cell = this.plugin.state.data.cells.get(ref);
                            if (cell && cell.state.isHidden) {
                                commands_1.PluginCommands.State.ToggleVisibility(this.plugin, { state: cell.parent, ref: ref });
                            }
                        }
                        commands_1.PluginCommands.Camera.Reset(this.plugin);
                        _b.label = 4;
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        return _this;
    }
    SegmentTree.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.customState.events.superpositionInit, function () {
            var customState = _this.customState;
            if (customState && !customState.superpositionError) {
                _this.getSegmentParams();
            }
            _this.forceUpdate();
        });
        this.subscribe(this.plugin.customState.events.isBusy, function (e) {
            _this.setState({ isBusy: e });
            if (e) {
                commands_1.PluginCommands.Toast.Show(_this.plugin, {
                    title: 'Process',
                    message: 'Loading / computing large dataset!',
                    key: 'is-busy-toast'
                });
            }
            else {
                commands_1.PluginCommands.Toast.Hide(_this.plugin, { key: 'is-busy-toast' });
            }
        });
        this.subscribe(this.plugin.behaviors.layout.leftPanelTabName, function (e) {
            if (e !== 'segments')
                return;
            _this.getSegmentParams();
            _this.forceUpdate();
        });
    };
    Object.defineProperty(SegmentTree.prototype, "customState", {
        get: function () {
            return this.plugin.customState;
        },
        enumerable: false,
        configurable: true
    });
    SegmentTree.prototype.render = function () {
        var sectionHeader = React.createElement(common_1.SectionHeader, { title: "Structure clusters" });
        var customState = this.customState;
        if (customState && customState.initParams && !customState.initParams.superposition) {
            return React.createElement(React.Fragment, null,
                sectionHeader,
                React.createElement("div", null, "Functionality unavailable!"));
        }
        else {
            if (customState && customState.initParams && customState.initParams.superposition) {
                sectionHeader = React.createElement(common_1.SectionHeader, { title: "Structure clusters - " + customState.initParams.moleculeId });
                if (customState.superpositionError) {
                    return React.createElement(React.Fragment, null,
                        sectionHeader,
                        React.createElement("div", { style: { textAlign: 'center' } }, customState.superpositionError));
                }
                else if (!customState.superpositionState || !customState.superpositionState.segmentData) {
                    return React.createElement(React.Fragment, null,
                        sectionHeader,
                        React.createElement("div", { style: { textAlign: 'center' } }, "Loading Segment Data!"));
                }
            }
        }
        if (this.state) {
            var segmentIndex_1 = parseInt(this.state.segment.value.segment.split(' ')[0]) - 1;
            var segmentData_1 = customState.superpositionState.segmentData;
            var fullSegmentRange = "( " + segmentData_1[0].segment_start + " - " + segmentData_1[segmentData_1.length - 1].segment_end + " )";
            sectionHeader = React.createElement(common_1.SectionHeader, { title: "Structure clusters " + customState.initParams.moleculeId, desc: fullSegmentRange });
            return React.createElement(React.Fragment, null,
                sectionHeader,
                React.createElement(parameters_1.ParameterControls, { params: this.state.segment.params, values: this.state.segment.value, onChangeValues: this.updateSegment, isDisabled: this.state.isBusy }),
                segmentData_1[segmentIndex_1].clusters.map(function (c, i) { return React.createElement(ClusterNode, { cluster: c, totalClusters: segmentData_1[segmentIndex_1].clusters.length, segmentIndex: segmentIndex_1, clusterIndex: i, key: "cluster-" + segmentIndex_1 + "-" + i }); }));
        }
        return React.createElement(React.Fragment, null);
    };
    return SegmentTree;
}(base_1.PurePluginUIComponent));
exports.SegmentTree = SegmentTree;
var ClusterNode = /** @class */ (function (_super) {
    tslib_1.__extends(ClusterNode, _super);
    function ClusterNode() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            isCollapsed: false,
            showAll: false,
            showNone: false,
            showSearch: false,
            isBusy: false,
            cluster: _this.props.cluster,
            searchText: ''
        };
        _this.inputStream = new rxjs_1.Subject();
        _this.handleInputStream = function (inputStr) {
            _this.setState({ searchText: inputStr });
            var filteredRes = _this.props.cluster.filter(function (item) {
                return item.pdb_id.toLowerCase().indexOf(inputStr.toLowerCase()) >= 0;
            });
            _this.setState({ cluster: filteredRes });
        };
        _this.toggleExpanded = function (e) {
            e.preventDefault();
            _this.setState({ isCollapsed: !_this.state.isCollapsed });
            e.currentTarget.blur();
        };
        _this.selectAll = function (e) {
            e.preventDefault();
            _this.setState({ showAll: !_this.state.showAll, showNone: false });
            e.currentTarget.blur();
        };
        _this.selectNone = function (e) {
            e.preventDefault();
            _this.setState({ showAll: false, showNone: !_this.state.showNone });
            e.currentTarget.blur();
        };
        _this.applyAction = function (e) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var customState, currentState;
            var _this = this;
            return tslib_1.__generator(this, function (_a) {
                e.preventDefault();
                e.currentTarget.blur();
                customState = this.customState;
                customState.events.isBusy.next(true);
                currentState = tslib_1.__assign({}, this.state);
                this.setState({ showAll: false, showNone: false });
                setTimeout(function () { return tslib_1.__awaiter(_this, void 0, void 0, function () {
                    var loadStrs, _a, _b, str, structStateId, structRef, cell, isHidden, e_1_1;
                    var e_1, _c;
                    return tslib_1.__generator(this, function (_d) {
                        switch (_d.label) {
                            case 0:
                                loadStrs = [];
                                _d.label = 1;
                            case 1:
                                _d.trys.push([1, 9, 10, 15]);
                                _a = tslib_1.__asyncValues(this.state.cluster);
                                _d.label = 2;
                            case 2: return [4 /*yield*/, _a.next()];
                            case 3:
                                if (!(_b = _d.sent(), !_b.done)) return [3 /*break*/, 8];
                                str = _b.value;
                                structStateId = str.pdb_id + "_" + str.struct_asym_id;
                                structRef = undefined;
                                if (customState && customState.superpositionState && customState.superpositionState.models[structStateId]) {
                                    structRef = this.customState.superpositionState.models[structStateId];
                                }
                                if (!structRef) return [3 /*break*/, 6];
                                cell = this.plugin.state.data.cells.get(structRef);
                                if (!cell) return [3 /*break*/, 5];
                                isHidden = cell.state.isHidden ? true : false;
                                if (!((isHidden && currentState.showAll) || (!isHidden && currentState.showNone))) return [3 /*break*/, 5];
                                return [4 /*yield*/, commands_1.PluginCommands.State.ToggleVisibility(this.plugin, { state: cell.parent, ref: structRef })];
                            case 4:
                                _d.sent();
                                _d.label = 5;
                            case 5: return [3 /*break*/, 7];
                            case 6:
                                if (currentState.showAll)
                                    loadStrs.push(str);
                                _d.label = 7;
                            case 7: return [3 /*break*/, 2];
                            case 8: return [3 /*break*/, 15];
                            case 9:
                                e_1_1 = _d.sent();
                                e_1 = { error: e_1_1 };
                                return [3 /*break*/, 15];
                            case 10:
                                _d.trys.push([10, , 13, 14]);
                                if (!(_b && !_b.done && (_c = _a.return))) return [3 /*break*/, 12];
                                return [4 /*yield*/, _c.call(_a)];
                            case 11:
                                _d.sent();
                                _d.label = 12;
                            case 12: return [3 /*break*/, 14];
                            case 13:
                                if (e_1) throw e_1.error;
                                return [7 /*endfinally*/];
                            case 14: return [7 /*endfinally*/];
                            case 15:
                                ;
                                commands_1.PluginCommands.Camera.Reset(this.plugin);
                                if (!(loadStrs.length > 0)) return [3 /*break*/, 17];
                                return [4 /*yield*/, superposition_1.renderSuperposition(this.plugin, this.props.segmentIndex, loadStrs)];
                            case 16:
                                _d.sent();
                                _d.label = 17;
                            case 17:
                                customState.events.isBusy.next(false);
                                return [2 /*return*/];
                        }
                    });
                }); });
                return [2 /*return*/];
            });
        }); };
        _this.cancelAction = function (e) {
            e.preventDefault();
            _this.setState({ showAll: false, showNone: false });
            e.currentTarget.blur();
        };
        _this.clearSearch = function (e) {
            e.preventDefault();
            _this.setState({ searchText: '' });
            _this.inputStream.next('');
            e.currentTarget.blur();
        };
        return _this;
    }
    ClusterNode.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.customState.events.isBusy, function (e) {
            _this.setState({ isBusy: e, showAll: false, showNone: false });
        });
        this.subscribe(this.inputStream.pipe(operators_1.debounceTime(1000 / 24)), function (e) { return _this.handleInputStream(e); });
    };
    Object.defineProperty(ClusterNode.prototype, "customState", {
        get: function () {
            return this.plugin.customState;
        },
        enumerable: false,
        configurable: true
    });
    ClusterNode.prototype.render = function () {
        var _this = this;
        var customState = this.customState;
        if (!customState.superpositionState || !customState.superpositionState.segmentData)
            return React.createElement(React.Fragment, null);
        var expand = React.createElement(common_1.IconButton, { svg: this.state.isCollapsed ? icons_1.ArrowRightSvg : icons_1.ArrowDropDownSvg, flex: '20px', onClick: this.toggleExpanded, transparent: true, disabled: this.state.isBusy, className: 'msp-no-hover-outline' });
        var title = "Segment " + customState.superpositionState.activeSegment + " Cluster " + (this.props.clusterIndex + 1);
        var label = React.createElement(common_1.Button, { className: "msp-btn-tree-label", noOverflow: true, title: title, disabled: this.state.isBusy },
            React.createElement("span", null,
                "Cluster ",
                this.props.clusterIndex + 1),
            " ",
            React.createElement("small", null,
                this.state.cluster.length < this.props.cluster.length ? this.state.cluster.length + " / " : '',
                this.props.cluster.length,
                " chain",
                this.props.cluster.length > 1 ? 's' : ''));
        var selectionControls = React.createElement(React.Fragment, null,
            React.createElement(common_1.Button, { icon: icons_1.CheckSvg, flex: true, onClick: this.selectAll, style: { flex: '0 0 50px', textAlign: 'center', fontSize: '80%', color: '#9cacc3', padding: 0 }, disabled: this.state.isBusy, title: "Show all chains" }, "All"),
            React.createElement(common_1.Button, { icon: icons_1.CloseSvg, flex: true, onClick: this.selectNone, style: { flex: '0 0 50px', textAlign: 'center', fontSize: '80%', color: '#9cacc3', padding: 0 }, disabled: this.state.isBusy, title: "Hide all chains" }, "None"));
        var mainRow = React.createElement("div", { className: "msp-flex-row msp-tree-row", style: { marginTop: '10px' } },
            expand,
            label,
            this.props.cluster.length > 1 && selectionControls);
        var searchControls = React.createElement("div", { className: 'msp-mapped-parameter-group', style: { fontSize: '90%' } },
            React.createElement("div", { className: 'msp-control-row msp-transform-header-brand-gray', style: { height: '33px', marginLeft: '30px' } },
                React.createElement("span", { className: 'msp-control-row-label' }, "Search PDB ID"),
                React.createElement("div", { className: 'msp-control-row-ctrl' },
                    React.createElement("input", { type: 'text', placeholder: 'Enter PDB ID..', disabled: this.state.isBusy, onChange: function (e) { return _this.inputStream.next(e.target.value); }, value: this.state.searchText, maxLength: 4 }))),
            React.createElement(common_1.IconButton, { svg: icons_1.CloseSvg, flex: true, onClick: this.clearSearch, style: { flex: '0 0 24px', padding: 0 }, disabled: this.state.isBusy || this.state.searchText === '', toggleState: this.state.searchText !== '', title: 'Clear search input' }));
        return React.createElement(React.Fragment, null,
            mainRow,
            (this.state.showAll || this.state.showNone) && React.createElement("div", null,
                React.createElement("div", { className: "msp-control-row msp-transform-header-brand-" + (this.state.showAll ? 'green' : 'red'), style: { display: 'flex', marginLeft: '20px', height: '35px' } },
                    React.createElement("span", { className: 'msp-control-row-label', style: { flex: '1 1 auto', textAlign: 'left', fontSize: '85%' } },
                        this.state.showAll ? 'Display' : 'Hide',
                        " ",
                        this.state.cluster.length < this.props.cluster.length ? this.state.cluster.length + " / " : 'all ',
                        this.props.cluster.length,
                        " chains"),
                    React.createElement(common_1.Button, { icon: icons_1.CheckSvg, flex: true, onClick: this.applyAction, style: { flex: '0 0 60px', textAlign: 'center', fontSize: '78%', color: '#9cacc3', padding: 0, margin: '0 1px' }, title: "Apply action" }, "Apply"),
                    React.createElement(common_1.Button, { icon: icons_1.CloseSvg, flex: true, onClick: this.cancelAction, style: { flex: '0 0 60px', textAlign: 'center', fontSize: '78%', color: '#9cacc3', padding: 0, margin: '0 1px' }, title: "Cancel action" }, "Cancel"))),
            (!this.state.isCollapsed && this.props.cluster.length > 5) && searchControls,
            !this.state.isCollapsed && React.createElement("div", { className: 'msp-tree-updates-wrapper', style: { maxHeight: (this.props.totalClusters > 1) ? '330px' : '87%', overflowY: 'auto' } }, this.state.cluster.map(function (s, i) { return React.createElement(StructureNode, { segmentIndex: _this.props.segmentIndex, structure: s, isRep: i === 0 ? true : false, key: "str-" + s.pdb_id + s.struct_asym_id + i }); })));
    };
    return ClusterNode;
}(base_1.PluginUIComponent));
var StructureNode = /** @class */ (function (_super) {
    tslib_1.__extends(StructureNode, _super);
    function StructureNode() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = {
            showControls: false,
            isBusy: false,
            isProcessing: false,
            isHidden: true,
        };
        _this.toggleVisible = function (e) { return tslib_1.__awaiter(_this, void 0, void 0, function () {
            var structHierarchy, _i, _a, c, currentHiddenState;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        e.preventDefault();
                        e.currentTarget.blur();
                        this.setState({ isProcessing: true, showControls: false });
                        if (!this.ref) return [3 /*break*/, 1];
                        structHierarchy = this.plugin.managers.structure.hierarchy.current.refs.get(this.ref);
                        if (structHierarchy && structHierarchy.components) {
                            for (_i = 0, _a = structHierarchy.components; _i < _a.length; _i++) {
                                c = _a[_i];
                                currentHiddenState = c.cell.state.isHidden ? true : false;
                                if (currentHiddenState === this.state.isHidden) {
                                    commands_1.PluginCommands.State.ToggleVisibility(this.plugin, { state: c.cell.parent, ref: c.cell.transform.ref });
                                }
                            }
                            this.setState({ isHidden: !this.state.isHidden });
                        }
                        return [3 /*break*/, 3];
                    case 1: return [4 /*yield*/, superposition_1.renderSuperposition(this.plugin, this.props.segmentIndex, [this.props.structure])];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3:
                        this.setState({ isProcessing: false });
                        commands_1.PluginCommands.Camera.Reset(this.plugin);
                        return [2 /*return*/];
                }
            });
        }); };
        _this.selectAction = function (item) {
            if (!item)
                return;
            _this.setState({ showControls: false });
            (item === null || item === void 0 ? void 0 : item.value)();
        };
        _this.highlight = function (e) {
            e.preventDefault();
            if (_this.ref) {
                var cell = _this.plugin.state.data.cells.get(_this.ref);
                commands_1.PluginCommands.Interactivity.Object.Highlight(_this.plugin, { state: cell.parent, ref: _this.ref });
            }
            e.currentTarget.blur();
        };
        _this.clearHighlight = function (e) {
            e.preventDefault();
            commands_1.PluginCommands.Interactivity.ClearHighlights(_this.plugin);
            e.currentTarget.blur();
        };
        _this.toggleControls = function (e) {
            e.preventDefault();
            _this.setState({ showControls: !_this.state.showControls });
            e.currentTarget.blur();
        };
        return _this;
    }
    Object.defineProperty(StructureNode.prototype, "customState", {
        get: function () {
            return this.plugin.customState;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureNode.prototype, "ref", {
        get: function () {
            if (this.customState && this.customState.superpositionState && this.customState.superpositionState.models[this.props.structure.pdb_id + "_" + this.props.structure.struct_asym_id]) {
                return this.customState.superpositionState.models[this.props.structure.pdb_id + "_" + this.props.structure.struct_asym_id];
            }
            else {
                return undefined;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureNode.prototype, "modelCell", {
        get: function () {
            if (this.ref) {
                return this.plugin.state.data.cells.get(this.ref);
            }
            else {
                return undefined;
            }
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureNode.prototype, "isAllHidden", {
        get: function () {
            var isHidden = true;
            if (this.ref) {
                var structHierarchy = this.plugin.managers.structure.hierarchy.current.refs.get(this.ref);
                if (structHierarchy && structHierarchy.components) {
                    for (var _i = 0, _a = structHierarchy.components; _i < _a.length; _i++) {
                        var c = _a[_i];
                        if (c && c.cell && !c.cell.state.isHidden) {
                            isHidden = false;
                            break;
                        }
                    }
                }
                else {
                    isHidden = false;
                }
            }
            return isHidden;
        },
        enumerable: false,
        configurable: true
    });
    StructureNode.prototype.checkRelation = function (ref) {
        var isRelated = false;
        var cell = this.plugin.state.data.cells.get(ref);
        if (cell && cell.transform.parent) {
            if (cell && cell.transform.parent === this.ref) {
                isRelated = true;
            }
            else {
                var pcell = this.plugin.state.data.cells.get(cell.transform.parent);
                if (pcell && pcell.transform.parent === this.ref)
                    isRelated = true;
            }
        }
        else {
            var currentNodeCell = this.plugin.state.data.cells.get(this.ref);
            if (currentNodeCell && currentNodeCell.transform.parent === cell.transform.parent) {
                isRelated = true;
            }
        }
        return isRelated;
    };
    StructureNode.prototype.is = function (e) {
        if (!this.ref)
            return false;
        var isRelated = false;
        if (this.ref && e.ref !== this.ref) {
            isRelated = this.checkRelation(e.ref);
        }
        if (e.ref === this.ref || isRelated) {
            return true;
        }
        else {
            var invalidStruct = (this.customState.superpositionState.invalidStruct.indexOf(this.props.structure.pdb_id + "_" + this.props.structure.struct_asym_id) > -1) ? true : false;
            return invalidStruct ? true : false;
        }
    };
    StructureNode.prototype.componentDidMount = function () {
        var _this = this;
        this.setState({ isHidden: this.isAllHidden });
        this.subscribe(this.plugin.customState.events.isBusy, function (e) {
            _this.setState({ isBusy: e, showControls: false });
        });
        this.subscribe(this.plugin.state.events.cell.stateUpdated.pipe(operators_1.filter(function (e) { return _this.is(e); }), operators_1.debounceTime(33)), function (e) {
            _this.setState({ isHidden: _this.isAllHidden });
            // this.forceUpdate();
        });
    };
    StructureNode.prototype.getTagRefs = function (tags) {
        var TagSet = new Set(tags);
        var tree = this.plugin.state.data.tree;
        return mol_state_2.StateSelection.findUniqueTagsInSubtree(tree, this.modelCell.transform.ref, TagSet);
    };
    StructureNode.prototype.getRandomColor = function () {
        var clList = lists_1.ColorLists;
        var spState = this.plugin.customState.superpositionState;
        var palleteIndex = spState.colorState[this.props.segmentIndex].palleteIndex;
        var colorIndex = spState.colorState[this.props.segmentIndex].colorIndex;
        if (clList[spState.colorPalette[palleteIndex]].list[colorIndex + 1]) {
            colorIndex += 1;
        }
        else {
            colorIndex = 0;
            palleteIndex = spState.colorPalette[palleteIndex + 1] ? palleteIndex + 1 : 0;
        }
        var palleteName = spState.colorPalette[palleteIndex];
        this.plugin.customState.superpositionState.colorState[this.props.segmentIndex].palleteIndex = palleteIndex;
        this.plugin.customState.superpositionState.colorState[this.props.segmentIndex].colorIndex = colorIndex;
        return clList[palleteName].list[colorIndex];
    };
    StructureNode.prototype.addChainRepr = function () {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var uniformColor1, strInstance, query, chainSel;
            return tslib_1.__generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        uniformColor1 = this.getRandomColor();
                        strInstance = this.plugin.state.data.select(this.ref)[0];
                        query = builder_1.MolScriptBuilder.struct.generator.atomGroups({
                            'chain-test': builder_1.MolScriptBuilder.core.rel.eq([builder_1.MolScriptBuilder.struct.atomProperty.macromolecular.label_asym_id(), this.props.structure.struct_asym_id])
                        });
                        return [4 /*yield*/, this.plugin.builders.structure.tryCreateComponentFromExpression(strInstance, query, "Chain-" + this.props.segmentIndex, { label: "Chain", tags: ["superposition-sel"] })];
                    case 1:
                        chainSel = _a.sent();
                        if (!chainSel) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.plugin.builders.structure.representation.addRepresentation(chainSel, { type: 'cartoon', color: 'uniform', colorParams: { value: uniformColor1 } }, { tag: "superposition-visual" })];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    StructureNode.prototype.updates = function () {
        var _this = this;
        var structHierarchy = this.plugin.managers.structure.hierarchy.current.refs.get(this.ref);
        if (structHierarchy && structHierarchy.components) {
            var representations_1 = [];
            var showAddChainBtn_1 = true;
            structHierarchy.components.forEach(function (comps) {
                var gKeys = comps.key.split(',');
                var cId1Arr = gKeys[0].split('-');
                if (cId1Arr[2] === 'Chain')
                    showAddChainBtn_1 = false;
                if (comps.representations) {
                    comps.representations.forEach(function (repr) {
                        representations_1.push(repr);
                    });
                }
            });
            var customState = this.plugin.customState;
            if (customState.initParams && customState.initParams.superpositionParams && !customState.initParams.superpositionParams.ligandView) {
                showAddChainBtn_1 = false;
            }
            if (representations_1.length > 0) {
                return React.createElement("div", { className: 'msp-accent-offset', style: { marginLeft: '40px' } },
                    representations_1.length > 0 && representations_1.map(function (r, i) { return React.createElement(StructureRepresentationEntry, { group: [structHierarchy], key: r.cell.transform.ref + "-" + i, representation: r }); }),
                    showAddChainBtn_1 && React.createElement("div", { className: 'msp-control-group-header', style: { marginTop: '1px' } },
                        React.createElement(common_1.Button, { noOverflow: true, className: 'msp-control-button-label', title: "Click to add chain representaion", onClick: function () { return _this.addChainRepr(); } },
                            "\u00A0\u00A0Add Chain ",
                            this.props.structure.struct_asym_id,
                            " Representation")));
            }
        }
        return React.createElement(React.Fragment, null);
    };
    StructureNode.prototype.getSubtitle = function () {
        var customState = this.plugin.customState;
        var hetList = customState.superpositionState.hets[this.props.structure.pdb_id + "_" + this.props.structure.struct_asym_id];
        var subtitle;
        if (hetList) {
            var hetLimit = this.props.structure.is_representative ? 1 : 4;
            var totalHets = hetList.length;
            var hetStr = hetList.join(', ');
            if (totalHets > hetLimit) {
                hetStr = hetList.slice(0, hetLimit).join(', ');
                hetStr += " + " + (totalHets - hetLimit);
            }
            subtitle = " ( " + hetStr + " )";
            if (this.props.structure.is_representative)
                subtitle = " " + subtitle + " ( Representative )";
        }
        else if (this.props.structure.is_representative) {
            subtitle = ' ( Representative )';
        }
        return subtitle;
    };
    Object.defineProperty(StructureNode.prototype, "panelColor", {
        get: function () {
            var panelColor = '#808080';
            if (!this.state.isHidden) {
                if (this.modelCell) {
                    var refs = this.getTagRefs(["superposition-visual", "superposition-ligand-visual"]);
                    var visualRef = refs["superposition-ligand-visual"] ? refs["superposition-ligand-visual"] : refs["superposition-visual"] ? refs["superposition-visual"] : undefined;
                    if (visualRef) {
                        var visualCell = this.plugin.state.data.cells.get(visualRef);
                        if (visualCell.params && visualCell.params.values && visualCell.params.values.colorTheme) {
                            var colorTheme = visualCell.params.values.colorTheme;
                            if (colorTheme.params && colorTheme.params.value) {
                                panelColor = "" + color_1.Color.toStyle(colorTheme.params.value);
                            }
                            else if (colorTheme.params && colorTheme.params.palette) {
                                var colorList1 = colorTheme.params.palette.params.list.colors;
                                panelColor = "" + color_1.Color.toStyle(colorList1[0]);
                            }
                            else if (colorTheme.params && colorTheme.params.list) {
                                var colorList2 = colorTheme.params.list.colors;
                                panelColor = "" + color_1.Color.toStyle(colorList2[0]);
                            }
                        }
                    }
                }
            }
            return panelColor;
        },
        enumerable: false,
        configurable: true
    });
    StructureNode.prototype.render = function () {
        var superpositionParams = this.customState.initParams.superpositionParams;
        var strutStateId = this.props.structure.pdb_id + "_" + this.props.structure.struct_asym_id;
        var invalidStruct = (this.customState.superpositionState.invalidStruct.indexOf(strutStateId) > -1) ? true : false;
        var noMatrixStruct = (this.customState.superpositionState.noMatrixStruct.indexOf(strutStateId) > -1) ? true : false;
        var subTitle = invalidStruct ? noMatrixStruct ? " Matrix not available!" : " No Ligand found!" : this.getSubtitle();
        var strTitle = this.props.structure.pdb_id + " chain " + this.props.structure.auth_asym_id;
        if (superpositionParams && superpositionParams.ligandView) {
            strTitle = this.props.structure.pdb_id + " " + this.props.structure.struct_asym_id;
        }
        var label = React.createElement(common_1.Button, { className: "msp-btn-tree-label", style: { borderLeftColor: this.panelColor }, noOverflow: true, title: strTitle, disabled: (invalidStruct || this.state.isBusy || this.state.isProcessing) ? true : false, onMouseEnter: this.highlight, onMouseLeave: this.clearHighlight },
            React.createElement("span", null, strTitle),
            subTitle && React.createElement("small", null, subTitle));
        var expand = React.createElement(common_1.IconButton, { svg: !this.state.showControls ? icons_1.ArrowRightSvg : icons_1.ArrowDropDownSvg, flex: '20px', onClick: this.toggleControls, transparent: true, className: 'msp-no-hover-outline', disabled: (invalidStruct || this.state.isBusy || this.state.isProcessing) ? true : false });
        var visibility = React.createElement(common_1.IconButton, { svg: this.state.isHidden ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, toggleState: false, small: true, onClick: this.toggleVisible, disabled: (invalidStruct || this.state.isBusy || this.state.isProcessing) ? true : false, title: this.state.isHidden ? "Show chain" : "Hide chain" });
        var row = React.createElement("div", { className: "msp-flex-row msp-tree-row", style: { marginLeft: !this.state.isHidden ? '10px' : '31px' } },
            !this.state.isHidden && expand,
            label,
            visibility);
        return React.createElement("div", { style: { marginBottom: '1px' } },
            row,
            this.state.showControls && this.updates());
    };
    return StructureNode;
}(base_1.PluginUIComponent));
var StructureRepresentationEntry = /** @class */ (function (_super) {
    tslib_1.__extends(StructureRepresentationEntry, _super);
    function StructureRepresentationEntry() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.toggleVisible = function (e) {
            e.preventDefault();
            e.currentTarget.blur();
            var cell = _this.props.representation.cell;
            commands_1.PluginCommands.State.ToggleVisibility(_this.plugin, { state: cell.parent, ref: cell.transform.parent });
        };
        return _this;
    }
    StructureRepresentationEntry.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.stateUpdated, function (e) {
            if (mol_state_1.State.ObjectEvent.isCell(e, _this.props.representation.cell))
                _this.forceUpdate();
        });
    };
    StructureRepresentationEntry.prototype.render = function () {
        var _a, _b, _c, _d, _e, _f, _g;
        var repr = this.props.representation.cell;
        var label = (_a = repr.obj) === null || _a === void 0 ? void 0 : _a.label;
        if (((_b = repr.obj) === null || _b === void 0 ? void 0 : _b.data.source) && ((_c = repr.obj) === null || _c === void 0 ? void 0 : _c.data.source.label)) {
            var sourceLabel = (((_d = repr.obj) === null || _d === void 0 ? void 0 : _d.data.source.label.indexOf('[Focus]')) >= 0) ? '[Focus]' : (_e = repr.obj) === null || _e === void 0 ? void 0 : _e.data.source.label;
            var isLargeLabel = sourceLabel.length > 10 ? true : false;
            sourceLabel = "" + (isLargeLabel ? sourceLabel.substring(0, 28) + "..." : sourceLabel);
            if (isLargeLabel) {
                label = sourceLabel;
            }
            else {
                label = sourceLabel + " " + ((label && label.length < 21) ? ' - ' + label : '');
            }
        }
        if (((_f = repr.obj) === null || _f === void 0 ? void 0 : _f.data.source) && ((_g = repr.obj) === null || _g === void 0 ? void 0 : _g.data.source.label) === 'Custom Selection')
            label = 'Custom Selection';
        return React.createElement("div", { className: 'msp-representation-entry' },
            repr.parent && React.createElement(common_1.ExpandGroup, { header: "" + (label || 'Representation'), noOffset: true, headerStyle: { overflow: 'hidden' } },
                React.createElement(update_transform_1.UpdateTransformControl, { state: repr.parent, transform: repr.transform, customHeader: 'none', noMargin: true })),
            React.createElement(common_1.IconButton, { svg: this.props.representation.cell.state.isHidden ? icons_1.VisibilityOffOutlinedSvg : icons_1.VisibilityOutlinedSvg, toggleState: false, onClick: this.toggleVisible, title: this.props.representation.cell.state.isHidden ? "Show representation" : "Hide representation", small: true, className: 'msp-default-bg', style: { position: 'absolute', top: 0, right: 0, lineHeight: '24px', height: '24px', textAlign: 'right', width: '32px', paddingRight: '6px', background: 'none' } }));
    };
    return StructureRepresentationEntry;
}(base_1.PurePluginUIComponent));
//# sourceMappingURL=segment-tree.js.map

/***/ }),
/* 443 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomEvents = void 0;
var loci_details_1 = __webpack_require__(413);
var CustomEvents;
(function (CustomEvents) {
    function create(eventTypeArr) {
        var eventObj = {};
        for (var ei = 0, el = eventTypeArr.length; ei < el; ei++) {
            var eventType = eventTypeArr[ei];
            var event_1 = void 0;
            if (typeof MouseEvent == 'function') {
                // current standard
                event_1 = new MouseEvent(eventType, { 'view': window, 'bubbles': true, 'cancelable': true });
            }
            else if (typeof document.createEvent == 'function') {
                // older standard
                event_1 = document.createEvent('MouseEvents');
                event_1.initEvent(eventType, true /* bubbles */, true /* cancelable */);
            }
            eventObj[eventType] = event_1;
        }
        ;
        return eventObj;
    }
    function dispatchCustomEvent(event, eventData, targetElement) {
        if (typeof eventData !== 'undefined') {
            eventData['residueNumber'] = eventData.seq_id;
            event['eventData'] = eventData;
            event.eventData.residueNumber = eventData.seq_id;
            targetElement.dispatchEvent(event);
        }
    }
    function add(plugin, targetElement) {
        var pdbevents = create(['PDB.molstar.click', 'PDB.molstar.mouseover', 'PDB.molstar.mouseout']);
        plugin.behaviors.interaction.click.subscribe(function (e) {
            if (e.button === 1 && e.current && e.current.loci.kind !== 'empty-loci') {
                var evData = loci_details_1.lociDetails(e.current.loci);
                if (evData)
                    dispatchCustomEvent(pdbevents['PDB.molstar.click'], evData, targetElement);
            }
        });
        plugin.behaviors.interaction.hover.subscribe(function (e) {
            if (e.current && e.current.loci && e.current.loci.kind !== 'empty-loci') {
                var evData = loci_details_1.lociDetails(e.current.loci);
                if (evData)
                    dispatchCustomEvent(pdbevents['PDB.molstar.mouseover'], evData, targetElement);
            }
            if (e.current && e.current.loci && e.current.loci.kind === 'empty-loci') {
                dispatchCustomEvent(pdbevents['PDB.molstar.mouseout'], {}, targetElement);
            }
        });
    }
    CustomEvents.add = add;
})(CustomEvents = exports.CustomEvents || (exports.CustomEvents = {}));
//# sourceMappingURL=custom-events.js.map

/***/ }),
/* 444 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SuperpositionFocusRepresentation = exports.SuperpositionFocusRepresentationTags = void 0;
var tslib_1 = __webpack_require__(0);
var structure_1 = __webpack_require__(4);
var structure_representation_params_1 = __webpack_require__(162);
var transforms_1 = __webpack_require__(28);
var behavior_1 = __webpack_require__(170);
var builder_1 = __webpack_require__(10);
var mol_state_1 = __webpack_require__(13);
var param_definition_1 = __webpack_require__(2);
var commands_1 = __webpack_require__(26);
var loci_details_1 = __webpack_require__(413);
var SuperpositionFocusRepresentationParams = function (plugin) {
    var reprParams = transforms_1.StateTransforms.Representation.StructureRepresentation3D.definition.params(void 0, plugin);
    return {
        expandRadius: param_definition_1.ParamDefinition.Numeric(5, { min: 1, max: 10, step: 1 }),
        surroundingsParams: param_definition_1.ParamDefinition.Group(reprParams, {
            label: 'Surroundings',
            customDefault: structure_representation_params_1.createStructureRepresentationParams(plugin, void 0, { type: 'ball-and-stick', size: 'physical', typeParams: { sizeFactor: 0.16 }, sizeParams: { scale: 0.3 } })
        })
    };
};
var SuperpositionFocusRepresentationTags;
(function (SuperpositionFocusRepresentationTags) {
    SuperpositionFocusRepresentationTags["SurrSel"] = "superposition-focus-surr-sel";
    SuperpositionFocusRepresentationTags["SurrRepr"] = "superposition-focus-surr-repr";
})(SuperpositionFocusRepresentationTags = exports.SuperpositionFocusRepresentationTags || (exports.SuperpositionFocusRepresentationTags = {}));
var TagSet = new Set([SuperpositionFocusRepresentationTags.SurrSel, SuperpositionFocusRepresentationTags.SurrRepr]);
var SuperpositionFocusRepresentationBehavior = /** @class */ (function (_super) {
    tslib_1.__extends(SuperpositionFocusRepresentationBehavior, _super);
    function SuperpositionFocusRepresentationBehavior() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Object.defineProperty(SuperpositionFocusRepresentationBehavior.prototype, "surrLabel", {
        get: function () { return "[Focus] Surroundings (" + this.params.expandRadius + " \u00C5)"; },
        enumerable: false,
        configurable: true
    });
    SuperpositionFocusRepresentationBehavior.prototype.ensureShape = function (cell) {
        var state = this.plugin.state.data, tree = state.tree;
        var builder = state.build();
        var refs = mol_state_1.StateSelection.findUniqueTagsInSubtree(tree, cell.transform.ref, TagSet);
        // Selections
        if (!refs[SuperpositionFocusRepresentationTags.SurrSel]) {
            refs[SuperpositionFocusRepresentationTags.SurrSel] = builder
                .to(cell)
                .apply(transforms_1.StateTransforms.Model.StructureSelectionFromExpression, { expression: builder_1.MolScriptBuilder.struct.generator.empty(), label: this.surrLabel }, { tags: SuperpositionFocusRepresentationTags.SurrSel }).ref;
        }
        // Representations
        if (!refs[SuperpositionFocusRepresentationTags.SurrRepr]) {
            refs[SuperpositionFocusRepresentationTags.SurrRepr] = builder
                .to(refs[SuperpositionFocusRepresentationTags.SurrSel])
                .apply(transforms_1.StateTransforms.Representation.StructureRepresentation3D, this.params.surroundingsParams, { tags: SuperpositionFocusRepresentationTags.SurrRepr }).ref;
        }
        return { state: state, builder: builder, refs: refs };
    };
    SuperpositionFocusRepresentationBehavior.prototype.clear = function (root) {
        var state = this.plugin.state.data;
        var surrs = state.select(mol_state_1.StateSelection.Generators.byRef(root).subtree().withTag(SuperpositionFocusRepresentationTags.SurrSel));
        if (surrs.length === 0)
            return;
        var update = state.build();
        var expression = builder_1.MolScriptBuilder.struct.generator.empty();
        for (var _i = 0, surrs_1 = surrs; _i < surrs_1.length; _i++) {
            var s = surrs_1[_i];
            update.to(s).update(transforms_1.StateTransforms.Model.StructureSelectionFromExpression, function (old) { return (tslib_1.__assign(tslib_1.__assign({}, old), { expression: expression })); });
        }
        return commands_1.PluginCommands.State.Update(this.plugin, { state: state, tree: update, options: { doNotLogTiming: true, doNotUpdateCurrent: true } });
    };
    SuperpositionFocusRepresentationBehavior.prototype.focus = function (sourceLoci) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var parent, loci, residueLoci, residueBundle, target, surroundings, lociDeatils, _a, state, builder, refs;
            var _this = this;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        parent = this.plugin.helpers.substructureParent.get(sourceLoci.structure);
                        if (!parent || !parent.obj)
                            return [2 /*return*/];
                        loci = structure_1.StructureElement.Loci.remap(sourceLoci, parent.obj.data);
                        residueLoci = structure_1.StructureElement.Loci.extendToWholeResidues(loci);
                        residueBundle = structure_1.StructureElement.Bundle.fromLoci(residueLoci);
                        target = structure_1.StructureElement.Bundle.toExpression(residueBundle);
                        surroundings = builder_1.MolScriptBuilder.struct.modifier.includeSurroundings({
                            0: target,
                            radius: this.params.expandRadius,
                            'as-whole-residues': true
                        });
                        lociDeatils = loci_details_1.lociDetails(sourceLoci);
                        if (!lociDeatils) {
                            surroundings = builder_1.MolScriptBuilder.struct.modifier.exceptBy({
                                0: surroundings,
                                by: target
                            });
                        }
                        _a = this.ensureShape(parent), state = _a.state, builder = _a.builder, refs = _a.refs;
                        builder.to(refs[SuperpositionFocusRepresentationTags.SurrSel]).update(transforms_1.StateTransforms.Model.StructureSelectionFromExpression, function (old) { return (tslib_1.__assign(tslib_1.__assign({}, old), { expression: surroundings, label: _this.surrLabel })); });
                        return [4 /*yield*/, commands_1.PluginCommands.State.Update(this.plugin, { state: state, tree: builder, options: { doNotLogTiming: true, doNotUpdateCurrent: true } })];
                    case 1:
                        _b.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    SuperpositionFocusRepresentationBehavior.prototype.register = function (ref) {
        var _this = this;
        this.subscribeObservable(this.plugin.managers.structure.focus.behaviors.current, function (entry) {
            // if (entry) this.focus(entry.loci);
            // else this.clear(StateTransform.RootRef);
            _this.clear(mol_state_1.StateTransform.RootRef);
            if (entry)
                _this.focus(entry.loci);
        });
    };
    SuperpositionFocusRepresentationBehavior.prototype.update = function (params) {
        return tslib_1.__awaiter(this, void 0, void 0, function () {
            var old, state, builder, all, _i, _a, repr;
            return tslib_1.__generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        old = this.params;
                        this.params = params;
                        state = this.plugin.state.data;
                        builder = state.build();
                        all = mol_state_1.StateSelection.Generators.root.subtree();
                        for (_i = 0, _a = state.select(all.withTag(SuperpositionFocusRepresentationTags.SurrRepr)); _i < _a.length; _i++) {
                            repr = _a[_i];
                            builder.to(repr).update(this.params.surroundingsParams);
                        }
                        return [4 /*yield*/, commands_1.PluginCommands.State.Update(this.plugin, { state: state, tree: builder, options: { doNotLogTiming: true, doNotUpdateCurrent: true } })];
                    case 1:
                        _b.sent();
                        if (!(params.expandRadius !== old.expandRadius)) return [3 /*break*/, 3];
                        return [4 /*yield*/, this.clear(mol_state_1.StateTransform.RootRef)];
                    case 2:
                        _b.sent();
                        _b.label = 3;
                    case 3: return [2 /*return*/, true];
                }
            });
        });
    };
    return SuperpositionFocusRepresentationBehavior;
}(behavior_1.PluginBehavior.WithSubscribers));
exports.SuperpositionFocusRepresentation = behavior_1.PluginBehavior.create({
    name: 'create-superposition-focus-representation',
    display: { name: 'Superposition Focus Representation' },
    category: 'interaction',
    ctor: SuperpositionFocusRepresentationBehavior,
    params: function (_, plugin) { return SuperpositionFocusRepresentationParams(plugin); }
});
//# sourceMappingURL=superposition-focus-representation.js.map

/***/ }),
/* 445 */
/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.SuperpostionViewport = void 0;
var tslib_1 = __webpack_require__(0);
var React = tslib_1.__importStar(__webpack_require__(3));
var base_1 = __webpack_require__(32);
var controls_1 = __webpack_require__(271);
var task_1 = __webpack_require__(389);
var toast_1 = __webpack_require__(390);
var viewport_1 = __webpack_require__(323);
var SuperpostionViewport = /** @class */ (function (_super) {
    tslib_1.__extends(SuperpostionViewport, _super);
    function SuperpostionViewport() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    SuperpostionViewport.prototype.render = function () {
        var _a, _b;
        var VPControls = ((_b = (_a = this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.viewport) === null || _b === void 0 ? void 0 : _b.controls) || viewport_1.ViewportControls;
        return React.createElement(React.Fragment, null,
            React.createElement(viewport_1.Viewport, null),
            React.createElement("div", { className: 'msp-viewport-top-left-controls' },
                React.createElement(controls_1.StateSnapshotViewportControls, null)),
            React.createElement(controls_1.SelectionViewportControls, null),
            React.createElement(VPControls, null),
            React.createElement(task_1.BackgroundTaskProgress, null),
            React.createElement("div", { className: 'msp-highlight-toast-wrapper' },
                React.createElement(controls_1.LociLabels, null),
                React.createElement(toast_1.Toasts, null)));
    };
    return SuperpostionViewport;
}(base_1.PluginUIComponent));
exports.SuperpostionViewport = SuperpostionViewport;
//# sourceMappingURL=superposition-viewport.js.map

/***/ }),
/* 446 */
/***/ (function(module, exports, __webpack_require__) {

// extracted by mini-css-extract-plugin

/***/ }),
/* 447 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "PluginContext", function() { return /* binding */ context_PluginContext; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/immer/dist/immer.esm.js
var immer_esm = __webpack_require__(151);

// EXTERNAL MODULE: ./node_modules/immutable/dist/immutable.js
var immutable = __webpack_require__(102);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/observable/merge.js
var merge = __webpack_require__(235);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/canvas3d.js
var canvas3d = __webpack_require__(158);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-model-props/common/custom-property.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var custom_property_CustomProperty;
(function (CustomProperty) {
    var Registry = /** @class */ (function () {
        function Registry() {
            this.providers = Object(immutable["OrderedMap"])().asMutable();
            this.defaultAutoAttachValues = new Map();
        }
        /** Get params for all applicable property providers */
        Registry.prototype.getParams = function (data) {
            var propertiesParams = {};
            var autoAttachOptions = [];
            var autoAttachDefault = [];
            if (data) {
                var values = this.providers.values();
                while (true) {
                    var v = values.next();
                    if (v.done)
                        break;
                    var provider = v.value;
                    if (!provider.isApplicable(data))
                        continue;
                    if (!provider.isHidden) {
                        autoAttachOptions.push([provider.descriptor.name, provider.label]);
                        if (this.defaultAutoAttachValues.get(provider.descriptor.name)) {
                            autoAttachDefault.push(provider.descriptor.name);
                        }
                    }
                    propertiesParams[provider.descriptor.name] = param_definition["ParamDefinition"].Group(Object(tslib_es6["__assign"])({}, provider.getParams(data)), { label: provider.label, isHidden: provider.isHidden });
                }
            }
            return {
                autoAttach: param_definition["ParamDefinition"].MultiSelect(autoAttachDefault, autoAttachOptions),
                properties: param_definition["ParamDefinition"].Group(propertiesParams, { isFlat: true })
            };
        };
        Registry.prototype.setDefaultAutoAttach = function (name, value) {
            this.defaultAutoAttachValues.set(name, value);
        };
        Registry.prototype.get = function (name) {
            var prop = this.providers.get(name);
            if (!prop) {
                throw new Error("Custom property '" + name + "' is not registered.");
            }
            return this.providers.get(name);
        };
        Registry.prototype.register = function (provider, defaultAutoAttach) {
            this.providers.set(provider.descriptor.name, provider);
            this.defaultAutoAttachValues.set(provider.descriptor.name, defaultAutoAttach);
        };
        Registry.prototype.unregister = function (name) {
            this.providers.delete(name);
            this.defaultAutoAttachValues.delete(name);
        };
        return Registry;
    }());
    CustomProperty.Registry = Registry;
})(custom_property_CustomProperty || (custom_property_CustomProperty = {}));
//# sourceMappingURL=custom-property.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/data.js + 6 modules
var transforms_data = __webpack_require__(288);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-util/file-info.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
// TODO only support compressed files for which uncompression support is available???
// TODO store globally with decompression plugins?
var compressedExtList = ['gz', 'zip'];
// TODO store globally with parser plugins?
var binaryExtList = ['bcif', 'ccp4', 'dcd'];
function getFileInfo(file) {
    var path;
    var compressed;
    var protocol = '';
    if (file instanceof File) {
        path = file.name;
    }
    else if (file instanceof Blob) {
        path = '';
    }
    else {
        path = file;
    }
    var queryIndex = path.lastIndexOf('?');
    var query = queryIndex !== -1 ? path.substring(queryIndex) : '';
    path = path.substring(0, queryIndex === -1 ? path.length : queryIndex);
    var name = path.replace(/^.*[\\/]/, '');
    var base = name.substring(0, name.lastIndexOf('.'));
    var nameSplit = name.split('.');
    var ext = nameSplit.length > 1 ? (nameSplit.pop() || '').toLowerCase() : '';
    var protocolMatch = path.match(/^(.+):\/\/(.+)$/);
    if (protocolMatch) {
        protocol = protocolMatch[1].toLowerCase();
        path = protocolMatch[2] || '';
    }
    var dir = path.substring(0, path.lastIndexOf('/') + 1);
    if (compressedExtList.includes(ext)) {
        compressed = ext;
        var n = path.length - ext.length - 1;
        ext = (path.substr(0, n).split('.').pop() || '').toLowerCase();
        var m = base.length - ext.length - 1;
        base = base.substr(0, m);
    }
    else {
        compressed = false;
    }
    var binary = binaryExtList.includes(ext);
    return { path: path, name: name, ext: ext, base: base, dir: dir, compressed: compressed, binary: binary, protocol: protocol, query: query, src: file };
}
//# sourceMappingURL=file-info.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/data.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */



var data_DataBuilder = /** @class */ (function () {
    function DataBuilder(plugin) {
        this.plugin = plugin;
    }
    Object.defineProperty(DataBuilder.prototype, "dataState", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    DataBuilder.prototype.rawData = function (params, options) {
        var data = this.dataState.build().toRoot().apply(transforms_data["RawData"], params, options);
        return data.commit({ revertOnError: true });
    };
    DataBuilder.prototype.download = function (params, options) {
        var data = this.dataState.build().toRoot().apply(transforms_data["Download"], params, options);
        return data.commit({ revertOnError: true });
    };
    DataBuilder.prototype.downloadBlob = function (params, options) {
        var data = this.dataState.build().toRoot().apply(transforms_data["DownloadBlob"], params, options);
        return data.commit({ revertOnError: true });
    };
    DataBuilder.prototype.readFile = function (params, options) {
        var _a;
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var data, fileInfo;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.dataState.build().toRoot().apply(transforms_data["ReadFile"], params, options).commit({ revertOnError: true })];
                    case 1:
                        data = _b.sent();
                        fileInfo = getFileInfo(((_a = params.file) === null || _a === void 0 ? void 0 : _a.file) || '');
                        return [2 /*return*/, { data: data, fileInfo: fileInfo }];
                }
            });
        });
    };
    return DataBuilder;
}());

//# sourceMappingURL=data.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/util.js + 5 modules
var util = __webpack_require__(9);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/index.js + 4 modules
var mol_task = __webpack_require__(16);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/debug.js
var debug = __webpack_require__(61);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/object.js
var object = __webpack_require__(85);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-representation-params.js
var structure_representation_params = __webpack_require__(162);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms/representation.js + 13 modules
var transforms_representation = __webpack_require__(198);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure/representation-preset.js
var representation_preset = __webpack_require__(270);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/array.js
var mol_util_array = __webpack_require__(29);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/config.js
var config = __webpack_require__(101);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure/representation.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */












var representation_StructureRepresentationBuilder = /** @class */ (function () {
    function StructureRepresentationBuilder(plugin) {
        var _this = this;
        this.plugin = plugin;
        this._providers = [];
        this.providerMap = new Map();
        this.defaultProvider = representation_preset["a" /* PresetStructureRepresentations */].auto;
        Object(object["c" /* objectForEach */])(representation_preset["a" /* PresetStructureRepresentations */], function (r) { return _this.registerPreset(r); });
    }
    Object.defineProperty(StructureRepresentationBuilder.prototype, "dataState", {
        get: function () { return this.plugin.state.data; },
        enumerable: false,
        configurable: true
    });
    StructureRepresentationBuilder.prototype.resolveProvider = function (ref) {
        var _a;
        return typeof ref === 'string'
            ? (_a = representation_preset["a" /* PresetStructureRepresentations */][ref]) !== null && _a !== void 0 ? _a : Object(util["c" /* arrayFind */])(this._providers, function (p) { return p.id === ref; }) : ref;
    };
    StructureRepresentationBuilder.prototype.hasPreset = function (s) {
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (!p.isApplicable || p.isApplicable(s, this.plugin))
                return true;
        }
        return false;
    };
    Object.defineProperty(StructureRepresentationBuilder.prototype, "providers", {
        get: function () { return this._providers; },
        enumerable: false,
        configurable: true
    });
    StructureRepresentationBuilder.prototype.getPresets = function (s) {
        if (!s)
            return this.providers;
        var ret = [];
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (p.isApplicable && !p.isApplicable(s, this.plugin))
                continue;
            ret.push(p);
        }
        return ret;
    };
    StructureRepresentationBuilder.prototype.getPresetSelect = function (s) {
        var options = [];
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (s && p.isApplicable && !p.isApplicable(s, this.plugin))
                continue;
            options.push([p.id, p.display.name, p.display.group]);
        }
        return param_definition["ParamDefinition"].Select('auto', options);
    };
    StructureRepresentationBuilder.prototype.getPresetsWithOptions = function (s) {
        var options = [];
        var map = Object.create(null);
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (p.isApplicable && !p.isApplicable(s, this.plugin))
                continue;
            options.push([p.id, p.display.name]);
            map[p.id] = p.params ? param_definition["ParamDefinition"].Group(p.params(s, this.plugin)) : param_definition["ParamDefinition"].EmptyGroup();
        }
        if (options.length === 0)
            return param_definition["ParamDefinition"].MappedStatic('', { '': param_definition["ParamDefinition"].EmptyGroup() });
        return param_definition["ParamDefinition"].MappedStatic(options[0][0], map, { options: options });
    };
    StructureRepresentationBuilder.prototype.registerPreset = function (provider) {
        if (this.providerMap.has(provider.id)) {
            throw new Error("Representation provider with id '" + provider.id + "' already registered.");
        }
        this._providers.push(provider);
        this.providerMap.set(provider.id, provider);
    };
    StructureRepresentationBuilder.prototype.unregisterPreset = function (provider) {
        this.providerMap.delete(provider.id);
        Object(mol_util_array["arrayRemoveInPlace"])(this._providers, provider);
    };
    StructureRepresentationBuilder.prototype.applyPreset = function (parent, providerRef, params) {
        var _this = this;
        var _a;
        var provider = this.resolveProvider(providerRef);
        if (!provider)
            return;
        var state = this.plugin.state.data;
        var cell = mol_state["StateObjectRef"].resolveAndCheck(state, parent);
        if (!cell) {
            if (!debug["b" /* isProductionMode */])
                console.warn("Applying structure repr. provider to bad cell.");
            return;
        }
        var pd = ((_a = provider.params) === null || _a === void 0 ? void 0 : _a.call(provider, cell.obj, this.plugin)) || {};
        var prms = params || (provider.params
            ? param_definition["ParamDefinition"].getDefaultValues(pd)
            : {});
        var defaults = this.plugin.config.get(config["PluginConfig"].Structure.DefaultRepresentationPresetParams);
        prms = param_definition["ParamDefinition"].merge(pd, defaults, prms);
        var task = mol_task["b" /* Task */].create("" + provider.display.name, function () { return provider.apply(cell, prms, _this.plugin); });
        return this.plugin.runTask(task);
    };
    StructureRepresentationBuilder.prototype.addRepresentation = function (structure, props, options) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var repr, selector;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        repr = this.dataState.build();
                        selector = this.buildRepresentation(repr, structure, props, options);
                        if (!selector)
                            return [2 /*return*/];
                        return [4 /*yield*/, repr.commit()];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, selector];
                }
            });
        });
    };
    StructureRepresentationBuilder.prototype.buildRepresentation = function (builder, structure, props, options) {
        var _a, _b;
        if (!structure)
            return;
        var data = (_b = (_a = mol_state["StateObjectRef"].resolveAndCheck(this.dataState, structure)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!data)
            return;
        var params = Object(structure_representation_params["createStructureRepresentationParams"])(this.plugin, data, props);
        return (options === null || options === void 0 ? void 0 : options.tag) ? builder.to(structure).applyOrUpdateTagged(options.tag, transforms_representation["StructureRepresentation3D"], params, { state: options === null || options === void 0 ? void 0 : options.initialState }).selector
            : builder.to(structure).apply(transforms_representation["StructureRepresentation3D"], params, { state: options === null || options === void 0 ? void 0 : options.initialState }).selector;
    };
    return StructureRepresentationBuilder;
}());

//# sourceMappingURL=representation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js + 1 modules
var symmetry = __webpack_require__(113);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry.js + 6 modules
var geometry = __webpack_require__(11);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/root-structure.js
var root_structure = __webpack_require__(269);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra.js + 1 modules
var linear_algebra = __webpack_require__(1);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/util.js
var mol_repr_util = __webpack_require__(164);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure/hierarchy-preset.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








function hierarchy_preset_TrajectoryHierarchyPresetProvider(preset) { return preset; }
(function (TrajectoryHierarchyPresetProvider) {
    TrajectoryHierarchyPresetProvider.CommonParams = function (a, plugin) { return ({
        modelProperties: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Group(mol_state["StateTransformer"].getParamDefinition(transforms["StateTransforms"].Model.CustomModelProperties, void 0, plugin))),
        structureProperties: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Group(mol_state["StateTransformer"].getParamDefinition(transforms["StateTransforms"].Model.CustomStructureProperties, void 0, plugin))),
        representationPreset: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Text('auto')),
    }); };
})(hierarchy_preset_TrajectoryHierarchyPresetProvider || (hierarchy_preset_TrajectoryHierarchyPresetProvider = {}));
var CommonParams = hierarchy_preset_TrajectoryHierarchyPresetProvider.CommonParams;
var DefaultParams = function (a, plugin) { return (Object(tslib_es6["__assign"])({ model: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Group(mol_state["StateTransformer"].getParamDefinition(transforms["StateTransforms"].Model.ModelFromTrajectory, a, plugin))), showUnitcell: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Boolean(false)), structure: param_definition["ParamDefinition"].Optional(root_structure["a" /* RootStructureDefinition */].getParams(void 0, 'assembly').type) }, CommonParams(a, plugin))); };
var defaultPreset = hierarchy_preset_TrajectoryHierarchyPresetProvider({
    id: 'preset-trajectory-default',
    display: {
        name: 'Default (Assembly)', group: 'Preset',
        description: 'Shows the first assembly or, if that is unavailable, the first model.'
    },
    isApplicable: function (o) {
        return true;
    },
    params: DefaultParams,
    apply: function (trajectory, params, plugin) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var builder, model, modelProperties, structure, structureProperties, unitcell, _a, representation;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        builder = plugin.builders.structure;
                        return [4 /*yield*/, builder.createModel(trajectory, params.model)];
                    case 1:
                        model = _b.sent();
                        return [4 /*yield*/, builder.insertModelProperties(model, params.modelProperties)];
                    case 2:
                        modelProperties = _b.sent();
                        return [4 /*yield*/, builder.createStructure(modelProperties || model, params.structure)];
                    case 3:
                        structure = _b.sent();
                        return [4 /*yield*/, builder.insertStructureProperties(structure, params.structureProperties)];
                    case 4:
                        structureProperties = _b.sent();
                        if (!(params.showUnitcell === void 0 || !!params.showUnitcell)) return [3 /*break*/, 6];
                        return [4 /*yield*/, builder.tryCreateUnitcell(modelProperties, undefined, { isHidden: true })];
                    case 5:
                        _a = _b.sent();
                        return [3 /*break*/, 7];
                    case 6:
                        _a = void 0;
                        _b.label = 7;
                    case 7:
                        unitcell = _a;
                        return [4 /*yield*/, plugin.builders.structure.representation.applyPreset(structureProperties, params.representationPreset || 'auto')];
                    case 8:
                        representation = _b.sent();
                        return [2 /*return*/, {
                                model: model,
                                modelProperties: modelProperties,
                                unitcell: unitcell,
                                structure: structure,
                                structureProperties: structureProperties,
                                representation: representation
                            }];
                }
            });
        });
    }
});
var allModels = hierarchy_preset_TrajectoryHierarchyPresetProvider({
    id: 'preset-trajectory-all-models',
    display: {
        name: 'All Models', group: 'Preset',
        description: 'Shows all models; colored by model-index.'
    },
    isApplicable: function (o) {
        return o.data.length > 1;
    },
    params: CommonParams,
    apply: function (trajectory, params, plugin) {
        var _a, _b;
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var tr, builder, models, structures, i, model, modelProperties, structure, structureProperties, quality;
            return Object(tslib_es6["__generator"])(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        tr = (_b = (_a = mol_state["StateObjectRef"].resolveAndCheck(plugin.state.data, trajectory)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
                        if (!tr)
                            return [2 /*return*/, {}];
                        builder = plugin.builders.structure;
                        models = [], structures = [];
                        i = 0;
                        _c.label = 1;
                    case 1:
                        if (!(i < tr.length)) return [3 /*break*/, 8];
                        return [4 /*yield*/, builder.createModel(trajectory, { modelIndex: i })];
                    case 2:
                        model = _c.sent();
                        return [4 /*yield*/, builder.insertModelProperties(model, params.modelProperties, { isCollapsed: true })];
                    case 3:
                        modelProperties = _c.sent();
                        return [4 /*yield*/, builder.createStructure(modelProperties || model, { name: 'model', params: {} })];
                    case 4:
                        structure = _c.sent();
                        return [4 /*yield*/, builder.insertStructureProperties(structure, params.structureProperties)];
                    case 5:
                        structureProperties = _c.sent();
                        models.push(model);
                        structures.push(structure);
                        quality = structure.obj ? Object(mol_repr_util["c" /* getStructureQuality */])(structure.obj.data, { elementCountFactor: tr.length }) : 'medium';
                        return [4 /*yield*/, builder.representation.applyPreset(structureProperties, params.representationPreset || 'auto', { globalThemeName: 'model-index', quality: quality })];
                    case 6:
                        _c.sent();
                        _c.label = 7;
                    case 7:
                        i++;
                        return [3 /*break*/, 1];
                    case 8: return [2 /*return*/, { models: models, structures: structures }];
                }
            });
        });
    }
});
var CrystalSymmetryParams = function (a, plugin) { return (Object(tslib_es6["__assign"])({ model: param_definition["ParamDefinition"].Optional(param_definition["ParamDefinition"].Group(mol_state["StateTransformer"].getParamDefinition(transforms["StateTransforms"].Model.ModelFromTrajectory, a, plugin))) }, CommonParams(a, plugin))); };
function applyCrystalSymmetry(props, trajectory, params, plugin) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var builder, model, modelProperties, structure, structureProperties, unitcell, representation;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    builder = plugin.builders.structure;
                    return [4 /*yield*/, builder.createModel(trajectory, params.model)];
                case 1:
                    model = _a.sent();
                    return [4 /*yield*/, builder.insertModelProperties(model, params.modelProperties)];
                case 2:
                    modelProperties = _a.sent();
                    return [4 /*yield*/, builder.createStructure(modelProperties || model, {
                            name: 'symmetry',
                            params: props
                        })];
                case 3:
                    structure = _a.sent();
                    return [4 /*yield*/, builder.insertStructureProperties(structure, params.structureProperties)];
                case 4:
                    structureProperties = _a.sent();
                    return [4 /*yield*/, builder.tryCreateUnitcell(modelProperties, undefined, { isHidden: false })];
                case 5:
                    unitcell = _a.sent();
                    return [4 /*yield*/, plugin.builders.structure.representation.applyPreset(structureProperties, params.representationPreset || 'auto', { globalThemeName: props.theme })];
                case 6:
                    representation = _a.sent();
                    return [2 /*return*/, {
                            model: model,
                            modelProperties: modelProperties,
                            unitcell: unitcell,
                            structure: structure,
                            structureProperties: structureProperties,
                            representation: representation
                        }];
            }
        });
    });
}
var hierarchy_preset_unitcell = hierarchy_preset_TrajectoryHierarchyPresetProvider({
    id: 'preset-trajectory-unitcell',
    display: {
        name: 'Unit Cell', group: 'Preset',
        description: 'Shows the fully populated unit cell.'
    },
    isApplicable: function (o) {
        return mol_model_structure["Model"].hasCrystalSymmetry(o.data[0]);
    },
    params: CrystalSymmetryParams,
    apply: function (trajectory, params, plugin) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, applyCrystalSymmetry({ ijkMin: linear_algebra["Vec3"].create(0, 0, 0), ijkMax: linear_algebra["Vec3"].create(0, 0, 0) }, trajectory, params, plugin)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    }
});
var supercell = hierarchy_preset_TrajectoryHierarchyPresetProvider({
    id: 'preset-trajectory-supercell',
    display: {
        name: 'Super Cell', group: 'Preset',
        description: 'Shows the super cell, i.e. the central unit cell and all adjacent unit cells.'
    },
    isApplicable: function (o) {
        return mol_model_structure["Model"].hasCrystalSymmetry(o.data[0]);
    },
    params: CrystalSymmetryParams,
    apply: function (trajectory, params, plugin) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, applyCrystalSymmetry({ ijkMin: linear_algebra["Vec3"].create(-1, -1, -1), ijkMax: linear_algebra["Vec3"].create(1, 1, 1), theme: 'operator-hkl' }, trajectory, params, plugin)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    }
});
var PresetTrajectoryHierarchy = {
    'default': defaultPreset,
    'all-models': allModels,
    unitcell: hierarchy_preset_unitcell,
    supercell: supercell,
};
//# sourceMappingURL=hierarchy-preset.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure/hierarchy.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var hierarchy_TrajectoryHierarchyBuilder = /** @class */ (function () {
    function TrajectoryHierarchyBuilder(plugin) {
        var _this = this;
        this.plugin = plugin;
        this._providers = [];
        this.providerMap = new Map();
        this.defaultProvider = PresetTrajectoryHierarchy.default;
        Object(object["c" /* objectForEach */])(PresetTrajectoryHierarchy, function (r) { return _this.registerPreset(r); });
    }
    TrajectoryHierarchyBuilder.prototype.resolveProvider = function (ref) {
        var _a;
        return typeof ref === 'string'
            ? (_a = PresetTrajectoryHierarchy[ref]) !== null && _a !== void 0 ? _a : Object(util["c" /* arrayFind */])(this._providers, function (p) { return p.id === ref; }) : ref;
    };
    TrajectoryHierarchyBuilder.prototype.hasPreset = function (t) {
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (!p.isApplicable || p.isApplicable(t, this.plugin))
                return true;
        }
        return false;
    };
    Object.defineProperty(TrajectoryHierarchyBuilder.prototype, "providers", {
        get: function () { return this._providers; },
        enumerable: false,
        configurable: true
    });
    TrajectoryHierarchyBuilder.prototype.getPresets = function (t) {
        if (!t)
            return this.providers;
        var ret = [];
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (p.isApplicable && !p.isApplicable(t, this.plugin))
                continue;
            ret.push(p);
        }
        return ret;
    };
    TrajectoryHierarchyBuilder.prototype.getPresetSelect = function (t) {
        var options = [];
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (t && p.isApplicable && !p.isApplicable(t, this.plugin))
                continue;
            options.push([p.id, p.display.name]);
        }
        return param_definition["ParamDefinition"].Select('auto', options);
    };
    TrajectoryHierarchyBuilder.prototype.getPresetsWithOptions = function (t) {
        var options = [];
        var map = Object.create(null);
        for (var _i = 0, _a = this._providers; _i < _a.length; _i++) {
            var p = _a[_i];
            if (p.isApplicable && !p.isApplicable(t, this.plugin))
                continue;
            options.push([p.id, p.display.name]);
            map[p.id] = p.params ? param_definition["ParamDefinition"].Group(p.params(t, this.plugin)) : param_definition["ParamDefinition"].EmptyGroup();
        }
        if (options.length === 0)
            return param_definition["ParamDefinition"].MappedStatic('', { '': param_definition["ParamDefinition"].EmptyGroup() });
        return param_definition["ParamDefinition"].MappedStatic(options[0][0], map, { options: options });
    };
    TrajectoryHierarchyBuilder.prototype.registerPreset = function (provider) {
        if (this.providerMap.has(provider.id)) {
            throw new Error("Hierarchy provider with id '" + provider.id + "' already registered.");
        }
        this._providers.push(provider);
        this.providerMap.set(provider.id, provider);
    };
    TrajectoryHierarchyBuilder.prototype.unregisterPreset = function (provider) {
        this.providerMap.delete(provider.id);
        Object(mol_util_array["arrayRemoveInPlace"])(this._providers, provider);
    };
    TrajectoryHierarchyBuilder.prototype.applyPreset = function (parent, providerRef, params) {
        var _this = this;
        var provider = this.resolveProvider(providerRef);
        if (!provider)
            return;
        var state = this.plugin.state.data;
        var cell = mol_state["StateObjectRef"].resolveAndCheck(state, parent);
        if (!cell) {
            if (!debug["b" /* isProductionMode */])
                console.warn("Applying hierarchy preset provider to bad cell.");
            return;
        }
        var prms = params || (provider.params
            ? param_definition["ParamDefinition"].getDefaultValues(provider.params(cell.obj, this.plugin))
            : {});
        var task = mol_task["b" /* Task */].create("" + provider.display.name, function () { return provider.apply(cell, prms, _this.plugin); });
        return this.plugin.runTask(task);
    };
    return TrajectoryHierarchyBuilder;
}());

//# sourceMappingURL=hierarchy.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/builder/structure.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */










var structure_StructureBuilder = /** @class */ (function () {
    function StructureBuilder(plugin) {
        this.plugin = plugin;
        this.hierarchy = new hierarchy_TrajectoryHierarchyBuilder(this.plugin);
        this.representation = new representation_StructureRepresentationBuilder(this.plugin);
    }
    Object.defineProperty(StructureBuilder.prototype, "dataState", {
        get: function () {
            return this.plugin.state.data;
        },
        enumerable: false,
        configurable: true
    });
    StructureBuilder.prototype.parseTrajectoryData = function (data, format) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var provider, trajectory;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        provider = typeof format === 'string' ? this.plugin.dataFormats.get(format) : format;
                        if (!provider)
                            throw new Error("'" + format + "' is not a supported data format.");
                        return [4 /*yield*/, provider.parse(this.plugin, data)];
                    case 1:
                        trajectory = (_a.sent()).trajectory;
                        return [2 /*return*/, trajectory];
                }
            });
        });
    };
    StructureBuilder.prototype.parseTrajectoryBlob = function (data, params) {
        var state = this.dataState;
        var trajectory = state.build().to(data)
            .apply(transforms["StateTransforms"].Data.ParseBlob, params, { state: { isGhost: true } })
            .apply(transforms["StateTransforms"].Model.TrajectoryFromBlob, void 0);
        return trajectory.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.parseTrajectory = function (data, params) {
        var cell = mol_state["StateObjectRef"].resolveAndCheck(this.dataState, data);
        if (!cell)
            throw new Error('Invalid data cell.');
        if (objects["a" /* PluginStateObject */].Data.Blob.is(cell.obj)) {
            return this.parseTrajectoryBlob(data, params);
        }
        else {
            return this.parseTrajectoryData(data, params);
        }
    };
    StructureBuilder.prototype.createModel = function (trajectory, params, initialState) {
        var state = this.dataState;
        var model = state.build().to(trajectory)
            .apply(transforms["StateTransforms"].Model.ModelFromTrajectory, params || { modelIndex: 0 }, { state: initialState });
        return model.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.insertModelProperties = function (model, params, initialState) {
        var state = this.dataState;
        var props = state.build().to(model)
            .apply(transforms["StateTransforms"].Model.CustomModelProperties, params, { state: initialState });
        return props.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.tryCreateUnitcell = function (model, params, initialState) {
        var _a, _b, _c;
        var state = this.dataState;
        var m = (_b = (_a = mol_state["StateObjectRef"].resolveAndCheck(state, model)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!m)
            return;
        var cell = (_c = symmetry["a" /* ModelSymmetry */].Provider.get(m)) === null || _c === void 0 ? void 0 : _c.spacegroup.cell;
        if (geometry["f" /* SpacegroupCell */].isZero(cell))
            return;
        var unitcell = state.build().to(model)
            .apply(transforms["StateTransforms"].Representation.ModelUnitcell3D, params, { state: initialState });
        return unitcell.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.createStructure = function (modelRef, params, initialState) {
        var _a;
        var state = this.dataState;
        if (!params) {
            var model = mol_state["StateObjectRef"].resolveAndCheck(state, modelRef);
            if (model) {
                var symm = symmetry["a" /* ModelSymmetry */].Provider.get((_a = model.obj) === null || _a === void 0 ? void 0 : _a.data);
                if (!symm || (symm === null || symm === void 0 ? void 0 : symm.assemblies.length) === 0)
                    params = { name: 'model', params: {} };
            }
        }
        var structure = state.build().to(modelRef)
            .apply(transforms["StateTransforms"].Model.StructureFromModel, { type: params || { name: 'assembly', params: {} } }, { state: initialState });
        return structure.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.insertStructureProperties = function (structure, params) {
        var state = this.dataState;
        var props = state.build().to(structure)
            .apply(transforms["StateTransforms"].Model.CustomStructureProperties, params);
        return props.commit({ revertOnError: true });
    };
    StructureBuilder.prototype.isComponentTransform = function (cell) {
        return cell.transform.transformer === transforms["StateTransforms"].Model.StructureComponent;
    };
    /** returns undefined if the component is empty/null */
    StructureBuilder.prototype.tryCreateComponent = function (structure, params, key, tags) {
        var _a, _b;
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var state, root, keyTag, component, selector;
            return Object(tslib_es6["__generator"])(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        state = this.dataState;
                        root = state.build().to(structure);
                        keyTag = "structure-component-" + key;
                        component = root.applyOrUpdateTagged(keyTag, transforms["StateTransforms"].Model.StructureComponent, params, {
                            tags: tags ? Object(tslib_es6["__spreadArrays"])(tags, [keyTag]) : [keyTag]
                        });
                        return [4 /*yield*/, component.commit()];
                    case 1:
                        _c.sent();
                        selector = component.selector;
                        if (!(!selector.isOk || ((_b = (_a = selector.cell) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data.elementCount) === 0)) return [3 /*break*/, 3];
                        return [4 /*yield*/, state.build().delete(selector.ref).commit()];
                    case 2:
                        _c.sent();
                        return [2 /*return*/];
                    case 3: return [2 /*return*/, selector];
                }
            });
        });
    };
    StructureBuilder.prototype.tryCreateComponentFromExpression = function (structure, expression, key, params) {
        return this.tryCreateComponent(structure, {
            type: { name: 'expression', params: expression },
            nullIfEmpty: true,
            label: ((params === null || params === void 0 ? void 0 : params.label) || '').trim()
        }, key, params === null || params === void 0 ? void 0 : params.tags);
    };
    StructureBuilder.prototype.tryCreateComponentStatic = function (structure, type, params) {
        return this.tryCreateComponent(structure, {
            type: { name: 'static', params: type },
            nullIfEmpty: true,
            label: ((params === null || params === void 0 ? void 0 : params.label) || '').trim()
        }, "static-" + type, params === null || params === void 0 ? void 0 : params.tags);
    };
    StructureBuilder.prototype.tryCreateComponentFromSelection = function (structure, selection, key, params) {
        var _this = this;
        return this.plugin.runTask(mol_task["b" /* Task */].create('Query Component', function (taskCtx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _a, label, tags, structureData, transformParams, _b, _c, _d, _e, _f;
            var _g, _h;
            return Object(tslib_es6["__generator"])(this, function (_j) {
                switch (_j.label) {
                    case 0:
                        _a = params || {}, label = _a.label, tags = _a.tags;
                        label = (label || '').trim();
                        structureData = (_h = (_g = mol_state["StateObjectRef"].resolveAndCheck(this.dataState, structure)) === null || _g === void 0 ? void 0 : _g.obj) === null || _h === void 0 ? void 0 : _h.data;
                        if (!structureData)
                            return [2 /*return*/];
                        if (!selection.referencesCurrent) return [3 /*break*/, 2];
                        _c = {};
                        _d = {
                            name: 'bundle'
                        };
                        _f = (_e = mol_model_structure["StructureElement"].Bundle).fromSelection;
                        return [4 /*yield*/, selection.getSelection(this.plugin, taskCtx, structureData)];
                    case 1:
                        _b = (_c.type = (_d.params = _f.apply(_e, [_j.sent()]),
                            _d),
                            _c.nullIfEmpty = true,
                            _c.label = label || selection.label,
                            _c);
                        return [3 /*break*/, 3];
                    case 2:
                        _b = {
                            type: { name: 'expression', params: selection.expression },
                            nullIfEmpty: true,
                            label: label || selection.label
                        };
                        _j.label = 3;
                    case 3:
                        transformParams = _b;
                        if (!selection.ensureCustomProperties) return [3 /*break*/, 5];
                        return [4 /*yield*/, selection.ensureCustomProperties({ runtime: taskCtx, assetManager: this.plugin.managers.asset }, structureData)];
                    case 4:
                        _j.sent();
                        _j.label = 5;
                    case 5: return [2 /*return*/, this.tryCreateComponent(structure, transformParams, key, tags)];
                }
            });
        }); }));
    };
    return StructureBuilder;
}());

//# sourceMappingURL=structure.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/trajectory.js
var formats_trajectory = __webpack_require__(367);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/provider.js
var formats_provider = __webpack_require__(179);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/names.js
var names = __webpack_require__(47);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/volume.js
var mol_model_volume = __webpack_require__(36);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/volume-representation-params.js
var volume_representation_params = __webpack_require__(315);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/volume.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var Category = 'Volume';
function defaultVisuals(plugin, data) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var visual;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    visual = plugin.build().to(data.volume).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D);
                    return [4 /*yield*/, visual.commit()];
                case 1: return [2 /*return*/, [_a.sent()]];
            }
        });
    });
}
var Ccp4Provider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'CCP4/MRC/BRIX',
    description: 'CCP4/MRC/BRIX',
    category: Category,
    binaryExtensions: ['ccp4', 'mrc', 'map'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, volume;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParseCcp4, {}, { state: { isGhost: true } });
                    volume = format.apply(transforms["StateTransforms"].Volume.VolumeFromCcp4);
                    return [4 /*yield*/, format.commit({ revertOnError: true })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { format: format.selector, volume: volume.selector }];
            }
        });
    }); },
    visuals: defaultVisuals
});
var Dsn6Provider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'DSN6/BRIX',
    description: 'DSN6/BRIX',
    category: Category,
    binaryExtensions: ['dsn6', 'brix'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, volume;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParseDsn6, {}, { state: { isGhost: true } });
                    volume = format.apply(transforms["StateTransforms"].Volume.VolumeFromDsn6);
                    return [4 /*yield*/, format.commit({ revertOnError: true })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { format: format.selector, volume: volume.selector }];
            }
        });
    }); },
    visuals: defaultVisuals
});
var DxProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'DX',
    description: 'DX',
    category: Category,
    stringExtensions: ['dx'],
    binaryExtensions: ['dxbin'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, volume;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParseDx, {}, { state: { isGhost: true } });
                    volume = format.apply(transforms["StateTransforms"].Volume.VolumeFromDx);
                    return [4 /*yield*/, volume.commit({ revertOnError: true })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { volume: volume.selector }];
            }
        });
    }); },
    visuals: defaultVisuals
});
var CubeProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'Cube',
    description: 'Cube',
    category: Category,
    stringExtensions: ['cub', 'cube'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, volume, structure;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParseCube, {}, { state: { isGhost: true } });
                    volume = format.apply(transforms["StateTransforms"].Volume.VolumeFromCube);
                    structure = format
                        .apply(transforms["StateTransforms"].Model.TrajectoryFromCube, void 0, { state: { isGhost: true } })
                        .apply(transforms["StateTransforms"].Model.ModelFromTrajectory)
                        .apply(transforms["StateTransforms"].Model.StructureFromModel);
                    return [4 /*yield*/, format.commit({ revertOnError: true })];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { format: format.selector, volume: volume.selector, structure: structure.selector }];
            }
        });
    }); },
    visuals: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var surfaces, volumeReprs, volumeData, volumePos, volumeNeg, volume, structure, structureReprs;
        var _a, _b;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    surfaces = plugin.build();
                    volumeReprs = [];
                    volumeData = (_b = (_a = data.volume.cell) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
                    if (volumeData && mol_model_volume["b" /* Volume */].isOrbitals(volumeData)) {
                        volumePos = surfaces.to(data.volume).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, Object(volume_representation_params["a" /* createVolumeRepresentationParams */])(plugin, volumeData, {
                            type: 'isosurface',
                            typeParams: { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(1), alpha: 0.4 },
                            color: 'uniform',
                            colorParams: { value: names["a" /* ColorNames */].blue }
                        }));
                        volumeNeg = surfaces.to(data.volume).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, Object(volume_representation_params["a" /* createVolumeRepresentationParams */])(plugin, volumeData, {
                            type: 'isosurface',
                            typeParams: { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(-1), alpha: 0.4 },
                            color: 'uniform',
                            colorParams: { value: names["a" /* ColorNames */].red }
                        }));
                        volumeReprs.push(volumePos.selector, volumeNeg.selector);
                    }
                    else {
                        volume = surfaces.to(data.volume).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, Object(volume_representation_params["a" /* createVolumeRepresentationParams */])(plugin, volumeData, {
                            type: 'isosurface',
                            typeParams: { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(2), alpha: 0.4 },
                            color: 'uniform',
                            colorParams: { value: names["a" /* ColorNames */].grey }
                        }));
                        volumeReprs.push(volume.selector);
                    }
                    return [4 /*yield*/, plugin.builders.structure.representation.applyPreset(data.structure, 'auto')];
                case 1:
                    structure = _c.sent();
                    return [4 /*yield*/, surfaces.commit()];
                case 2:
                    _c.sent();
                    structureReprs = [];
                    Object(object["c" /* objectForEach */])(structure === null || structure === void 0 ? void 0 : structure.representations, function (r) {
                        if (r)
                            structureReprs.push(r);
                    });
                    return [2 /*return*/, Object(tslib_es6["__spreadArrays"])(volumeReprs, structureReprs)];
            }
        });
    }); }
});
var DscifProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'DensityServer CIF',
    description: 'DensityServer CIF',
    category: Category,
    stringExtensions: ['cif'],
    binaryExtensions: ['bcif'],
    isApplicable: function (info, data) {
        return Object(formats_provider["b" /* guessCifVariant */])(info, data) === 'dscif' ? true : false;
    },
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var cifCell, b, blocks, volumes, _i, blocks_1, block;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, plugin.build().to(data).apply(transforms["StateTransforms"].Data.ParseCif).commit()];
                case 1:
                    cifCell = _a.sent();
                    b = plugin.build().to(cifCell);
                    blocks = cifCell.obj.data.blocks.slice(1);
                    if (blocks.length !== 1 && blocks.length !== 2)
                        throw new Error('unknown number of blocks');
                    volumes = [];
                    for (_i = 0, blocks_1 = blocks; _i < blocks_1.length; _i++) {
                        block = blocks_1[_i];
                        volumes.push(b.apply(transforms["StateTransforms"].Volume.VolumeFromDensityServerCif, { blockHeader: block.header }).selector);
                    }
                    return [4 /*yield*/, b.commit()];
                case 2:
                    _a.sent();
                    return [2 /*return*/, { volumes: volumes }];
            }
        });
    }); },
    visuals: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var volumes, tree, visuals, posParams, negParams;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    volumes = data.volumes;
                    tree = plugin.build();
                    visuals = [];
                    if (volumes.length > 0) {
                        visuals[0] = tree
                            .to(volumes[0])
                            .apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, transforms_representation["VolumeRepresentation3DHelpers"].getDefaultParamsStatic(plugin, 'isosurface', { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(1.5), alpha: 1 }, 'uniform', { value: names["a" /* ColorNames */].teal }))
                            .selector;
                    }
                    if (volumes.length > 1) {
                        posParams = transforms_representation["VolumeRepresentation3DHelpers"].getDefaultParamsStatic(plugin, 'isosurface', { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(3), alpha: 0.3 }, 'uniform', { value: names["a" /* ColorNames */].green });
                        negParams = transforms_representation["VolumeRepresentation3DHelpers"].getDefaultParamsStatic(plugin, 'isosurface', { isoValue: mol_model_volume["b" /* Volume */].IsoValue.relative(-3), alpha: 0.3 }, 'uniform', { value: names["a" /* ColorNames */].red });
                        visuals[visuals.length] = tree.to(volumes[1]).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, posParams).selector;
                        visuals[visuals.length] = tree.to(volumes[1]).apply(transforms["StateTransforms"].Representation.VolumeRepresentation3D, negParams).selector;
                    }
                    return [4 /*yield*/, tree.commit()];
                case 1:
                    _a.sent();
                    return [2 /*return*/, visuals];
            }
        });
    }); }
});
var BuiltInVolumeFormats = [
    ['ccp4', Ccp4Provider],
    ['dsn6', Dsn6Provider],
    ['cube', CubeProvider],
    ['dx', DxProvider],
    ['dscif', DscifProvider],
];
//# sourceMappingURL=volume.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/shape.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var shape_Category = 'Shape';
var PlyProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'PLY',
    description: 'PLY',
    category: shape_Category,
    stringExtensions: ['ply'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, shape;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.state.data.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParsePly, {}, { state: { isGhost: true } });
                    shape = format.apply(transforms["StateTransforms"].Model.ShapeFromPly);
                    return [4 /*yield*/, format.commit()];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { format: format.selector, shape: shape.selector }];
            }
        });
    }); },
    visuals: function (plugin, data) {
        var repr = plugin.state.data.build()
            .to(data.shape)
            .apply(transforms["StateTransforms"].Representation.ShapeRepresentation3D);
        return repr.commit();
    }
});
var BuiltInShapeFormats = [
    ['ply', PlyProvider],
];
//# sourceMappingURL=shape.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/structure.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var structure_Category = 'Structure';
var PsfProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'PSF',
    description: 'PSF',
    category: structure_Category,
    stringExtensions: ['psf'],
    parse: function (plugin, data) { return Object(tslib_es6["__awaiter"])(void 0, void 0, void 0, function () {
        var format, topology;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    format = plugin.state.data.build()
                        .to(data)
                        .apply(transforms["StateTransforms"].Data.ParsePsf, {}, { state: { isGhost: true } });
                    topology = format.apply(transforms["StateTransforms"].Model.TopologyFromPsf);
                    return [4 /*yield*/, format.commit()];
                case 1:
                    _a.sent();
                    return [2 /*return*/, { format: format.selector, topology: topology.selector }];
            }
        });
    }); }
});
var DcdProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'DCD',
    description: 'DCD',
    category: structure_Category,
    binaryExtensions: ['dcd'],
    parse: function (plugin, data) {
        var coordinates = plugin.state.data.build()
            .to(data)
            .apply(transforms["StateTransforms"].Model.CoordinatesFromDcd);
        return coordinates.commit();
    }
});
var XtcProvider = Object(formats_provider["a" /* DataFormatProvider */])({
    label: 'XTC',
    description: 'XTC',
    category: structure_Category,
    binaryExtensions: ['xtc'],
    parse: function (plugin, data) {
        var coordinates = plugin.state.data.build()
            .to(data)
            .apply(transforms["StateTransforms"].Model.CoordinatesFromXtc);
        return coordinates.commit();
    }
});
var BuiltInStructureFormats = [
    ['psf', PsfProvider],
    ['dcd', DcdProvider],
    ['xtc', XtcProvider],
];
//# sourceMappingURL=structure.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/formats/registry.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var registry_DataFormatRegistry = /** @class */ (function () {
    function DataFormatRegistry() {
        this._list = [];
        this._map = new Map();
        this._extensions = undefined;
        this._binaryExtensions = undefined;
        this._options = undefined;
        for (var _i = 0, BuiltInVolumeFormats_1 = BuiltInVolumeFormats; _i < BuiltInVolumeFormats_1.length; _i++) {
            var _a = BuiltInVolumeFormats_1[_i], id = _a[0], p = _a[1];
            this.add(id, p);
        }
        for (var _b = 0, BuiltInStructureFormats_1 = BuiltInStructureFormats; _b < BuiltInStructureFormats_1.length; _b++) {
            var _c = BuiltInStructureFormats_1[_b], id = _c[0], p = _c[1];
            this.add(id, p);
        }
        for (var _d = 0, BuiltInShapeFormats_1 = BuiltInShapeFormats; _d < BuiltInShapeFormats_1.length; _d++) {
            var _e = BuiltInShapeFormats_1[_d], id = _e[0], p = _e[1];
            this.add(id, p);
        }
        for (var _f = 0, BuiltInTrajectoryFormats_1 = formats_trajectory["a" /* BuiltInTrajectoryFormats */]; _f < BuiltInTrajectoryFormats_1.length; _f++) {
            var _g = BuiltInTrajectoryFormats_1[_f], id = _g[0], p = _g[1];
            this.add(id, p);
        }
    }
    Object.defineProperty(DataFormatRegistry.prototype, "types", {
        get: function () {
            return this._list.map(function (e) { return [e.name, e.provider.label]; });
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DataFormatRegistry.prototype, "extensions", {
        get: function () {
            if (this._extensions)
                return this._extensions;
            var extensions = new Set();
            this._list.forEach(function (_a) {
                var _b, _c;
                var provider = _a.provider;
                (_b = provider.stringExtensions) === null || _b === void 0 ? void 0 : _b.forEach(function (ext) { return extensions.add(ext); });
                (_c = provider.binaryExtensions) === null || _c === void 0 ? void 0 : _c.forEach(function (ext) { return extensions.add(ext); });
            });
            this._extensions = extensions;
            return extensions;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DataFormatRegistry.prototype, "binaryExtensions", {
        get: function () {
            if (this._binaryExtensions)
                return this._binaryExtensions;
            var binaryExtensions = new Set();
            this._list.forEach(function (_a) {
                var _b;
                var provider = _a.provider;
                return (_b = provider.binaryExtensions) === null || _b === void 0 ? void 0 : _b.forEach(function (ext) { return binaryExtensions.add(ext); });
            });
            this._binaryExtensions = binaryExtensions;
            return binaryExtensions;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(DataFormatRegistry.prototype, "options", {
        get: function () {
            if (this._options)
                return this._options;
            var options = [];
            this._list.forEach(function (_a) {
                var name = _a.name, provider = _a.provider;
                return options.push([name, provider.label, provider.category || '']);
            });
            this._options = options;
            return options;
        },
        enumerable: false,
        configurable: true
    });
    ;
    DataFormatRegistry.prototype._clear = function () {
        this._extensions = undefined;
        this._binaryExtensions = undefined;
        this._options = undefined;
    };
    DataFormatRegistry.prototype.add = function (name, provider) {
        this._clear();
        this._list.push({ name: name, provider: provider });
        this._map.set(name, provider);
    };
    DataFormatRegistry.prototype.remove = function (name) {
        this._clear();
        this._list.splice(this._list.findIndex(function (e) { return e.name === name; }), 1);
        this._map.delete(name);
    };
    DataFormatRegistry.prototype.auto = function (info, dataStateObject) {
        for (var i = 0, il = this.list.length; i < il; ++i) {
            var provider = this._list[i].provider;
            var hasExt = false;
            if (provider.binaryExtensions && provider.binaryExtensions.indexOf(info.ext) >= 0)
                hasExt = true;
            else if (provider.stringExtensions && provider.stringExtensions.indexOf(info.ext) >= 0)
                hasExt = true;
            if (hasExt && (!provider.isApplicable || provider.isApplicable(info, dataStateObject.data)))
                return provider;
        }
        return;
    };
    DataFormatRegistry.prototype.get = function (name) {
        if (this._map.has(name)) {
            return this._map.get(name);
        }
        else {
            throw new Error("unknown data format name '" + name + "'");
        }
    };
    Object.defineProperty(DataFormatRegistry.prototype, "list", {
        get: function () {
            return this._list;
        },
        enumerable: false,
        configurable: true
    });
    return DataFormatRegistry;
}());

//# sourceMappingURL=registry.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/helpers/structure-selection-query.js
var structure_selection_query = __webpack_require__(80);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/boundary-helper.js
var boundary_helper = __webpack_require__(126);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/camera.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




// TODO: make this customizable somewhere?
var DefaultCameraFocusOptions = {
    minRadius: 5,
    extraRadius: 6,
    durationMs: 250
};
var camera_CameraManager = /** @class */ (function () {
    function CameraManager(plugin) {
        this.plugin = plugin;
        this.boundaryHelper = new boundary_helper["a" /* BoundaryHelper */]('98');
    }
    CameraManager.prototype.transformedLoci = function (loci) {
        var _a, _b;
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            // use decorated (including 3d transforms) parent structure
            var parent_1 = (_b = (_a = this.plugin.helpers.substructureParent.get(loci.structure)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
            if (parent_1)
                loci = mol_model_structure["StructureElement"].Loci.remap(loci, parent_1);
        }
        return loci;
    };
    CameraManager.prototype.focusRenderObjects = function (objects, options) {
        if (!objects)
            return;
        var spheres = [];
        for (var _i = 0, objects_1 = objects; _i < objects_1.length; _i++) {
            var o = objects_1[_i];
            var s = o.values.boundingSphere.ref.value;
            if (s.radius === 0)
                continue;
            spheres.push(s);
        }
        this.focusSpheres(spheres, function (s) { return s; }, options);
    };
    CameraManager.prototype.focusLoci = function (loci, options) {
        // TODO: allow computation of principal axes here?
        // perhaps have an optimized function, that does exact axes small Loci and approximate/sampled from big ones?
        var sphere;
        if (Array.isArray(loci) && loci.length > 1) {
            var spheres = [];
            for (var _i = 0, loci_1 = loci; _i < loci_1.length; _i++) {
                var l = loci_1[_i];
                var s = mol_model_loci["Loci"].getBoundingSphere(this.transformedLoci(l));
                if (s)
                    spheres.push(s);
            }
            if (spheres.length === 0)
                return;
            this.boundaryHelper.reset();
            for (var _a = 0, spheres_1 = spheres; _a < spheres_1.length; _a++) {
                var s = spheres_1[_a];
                this.boundaryHelper.includeSphere(s);
            }
            this.boundaryHelper.finishedIncludeStep();
            for (var _b = 0, spheres_2 = spheres; _b < spheres_2.length; _b++) {
                var s = spheres_2[_b];
                this.boundaryHelper.radiusSphere(s);
            }
            sphere = this.boundaryHelper.getSphere();
        }
        else if (Array.isArray(loci)) {
            if (loci.length === 0)
                return;
            sphere = mol_model_loci["Loci"].getBoundingSphere(this.transformedLoci(loci[0]));
        }
        else {
            sphere = mol_model_loci["Loci"].getBoundingSphere(this.transformedLoci(loci));
        }
        if (sphere) {
            this.focusSphere(sphere, options);
        }
    };
    CameraManager.prototype.focusSpheres = function (xs, sphere, options) {
        var spheres = [];
        for (var _i = 0, xs_1 = xs; _i < xs_1.length; _i++) {
            var x = xs_1[_i];
            var s = sphere(x);
            if (s)
                spheres.push(s);
        }
        if (spheres.length === 0)
            return;
        if (spheres.length === 1)
            return this.focusSphere(spheres[0], options);
        this.boundaryHelper.reset();
        for (var _a = 0, spheres_3 = spheres; _a < spheres_3.length; _a++) {
            var s = spheres_3[_a];
            this.boundaryHelper.includeSphere(s);
        }
        this.boundaryHelper.finishedIncludeStep();
        for (var _b = 0, spheres_4 = spheres; _b < spheres_4.length; _b++) {
            var s = spheres_4[_b];
            this.boundaryHelper.radiusSphere(s);
        }
        this.focusSphere(this.boundaryHelper.getSphere(), options);
    };
    CameraManager.prototype.focusSphere = function (sphere, options) {
        var _a, _b, _c, _d;
        var _e = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultCameraFocusOptions), options), extraRadius = _e.extraRadius, minRadius = _e.minRadius, durationMs = _e.durationMs;
        var radius = Math.max(sphere.radius + extraRadius, minRadius);
        if (options === null || options === void 0 ? void 0 : options.principalAxes) {
            var _f = options === null || options === void 0 ? void 0 : options.principalAxes.boxAxes, origin_1 = _f.origin, dirA = _f.dirA, dirC = _f.dirC;
            var snapshot = (_a = this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.camera.getFocus(origin_1, radius, dirA, dirC);
            (_b = this.plugin.canvas3d) === null || _b === void 0 ? void 0 : _b.requestCameraReset({ durationMs: durationMs, snapshot: snapshot });
            // this.plugin.canvas3d?.camera.focus(origin, radius, durationMs, dirA, dirC);
        }
        else {
            var snapshot = (_c = this.plugin.canvas3d) === null || _c === void 0 ? void 0 : _c.camera.getFocus(sphere.center, radius);
            (_d = this.plugin.canvas3d) === null || _d === void 0 ? void 0 : _d.requestCameraReset({ durationMs: durationMs, snapshot: snapshot });
            // this.plugin.canvas3d?.camera.focus(sphere.center, radius, durationMs);
        }
    };
    CameraManager.prototype.setSnapshot = function (snapshot, durationMs) {
        var _a;
        // TODO: setState and requestCameraReset are very similar now: unify them?
        (_a = this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.requestCameraReset({ snapshot: snapshot, durationMs: durationMs });
    };
    CameraManager.prototype.reset = function (snapshot, durationMs) {
        var _a;
        (_a = this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.requestCameraReset({ snapshot: snapshot, durationMs: durationMs });
    };
    return CameraManager;
}());

//# sourceMappingURL=camera.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/interactivity.js
var interactivity = __webpack_require__(370);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var mol_repr_representation = __webpack_require__(40);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/marker-action.js
var marker_action = __webpack_require__(45);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/loci-label.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var loci_label_LociLabelManager = /** @class */ (function () {
    function LociLabelManager(ctx) {
        var _this = this;
        this.ctx = ctx;
        this.providers = [];
        this.locis = [];
        this.isDirty = false;
        this.labels = [];
        this.groupedLabels = new Map();
        ctx.managers.interactivity.lociHighlights.addProvider(function (loci, action) {
            _this.mark(loci, action);
            _this.showLabels();
        });
    }
    LociLabelManager.prototype.addProvider = function (provider) {
        this.providers.push(provider);
        this.providers.sort(function (a, b) { return (b.priority || 0) - (a.priority || 0); });
        this.isDirty = true;
        this.showLabels();
    };
    LociLabelManager.prototype.removeProvider = function (provider) {
        this.providers = this.providers.filter(function (p) { return p !== provider; });
        this.isDirty = true;
        this.showLabels();
    };
    LociLabelManager.prototype.mark = function (loci, action) {
        var idx = this.locis.findIndex(function (l) { return mol_repr_representation["a" /* Representation */].Loci.areEqual(loci, l); });
        if (idx === -1 && action === marker_action["a" /* MarkerAction */].Highlight) {
            this.locis.push(loci);
            this.isDirty = true;
        }
        else if (idx !== -1 && action === marker_action["a" /* MarkerAction */].RemoveHighlight) {
            Object(mol_util_array["arrayRemoveAtInPlace"])(this.locis, idx);
            this.isDirty = true;
        }
    };
    LociLabelManager.prototype.showLabels = function () {
        this.ctx.behaviors.labels.highlight.next({ labels: this.getLabels() });
    };
    LociLabelManager.prototype.getLabels = function () {
        var _this = this;
        if (this.isDirty) {
            this.groupedLabels.clear();
            this.labels.length = 0;
            for (var _i = 0, _a = this.providers; _i < _a.length; _i++) {
                var provider = _a[_i];
                for (var _b = 0, _c = this.locis; _b < _c.length; _b++) {
                    var loci = _c[_b];
                    if (mol_model_loci["Loci"].isEmpty(loci.loci))
                        continue;
                    var label = provider.label(loci.loci, loci.repr);
                    if (label) {
                        var hash = provider.group ? provider.group(label) : label.toString();
                        var group = this.groupedLabels.get(hash);
                        if (group)
                            group.push(label);
                        else
                            this.groupedLabels.set(hash, [label]);
                    }
                }
            }
            this.labels.length = 0;
            this.groupedLabels.forEach(function (group, hash) {
                var count = group.length;
                var entry = count > 1 && group[0] !== group[1]
                    ? hash : group[0];
                _this.labels.push(count === 1 ? entry : entry + " <small>|| \u00D7 " + count + "</small>");
            });
            this.isDirty = false;
        }
        return this.labels;
    };
    return LociLabelManager;
}());

//# sourceMappingURL=loci-label.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/component.js + 2 modules
var structure_component = __webpack_require__(246);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/component.js
var mol_plugin_state_component = __webpack_require__(118);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/focus.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */








var HISTORY_CAPACITY = 8;
var focus_StructureFocusManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureFocusManager, _super);
    // this.subscribeObservable(this.plugin.state.events.object.updated, o => {
    //     if (!PluginStateObject.Molecule.Structure.is(o.oldObj) || !StructureElement.Loci.is(lastLoci)) return;
    //     if (lastLoci.structure === o.oldObj.data) {
    //         lastLoci = EmptyLoci;
    //     }
    // });
    function StructureFocusManager(plugin) {
        var _this = _super.call(this, { history: [] }) || this;
        _this.plugin = plugin;
        _this.events = {
            historyUpdated: _this.ev()
        };
        _this.behaviors = {
            current: _this.ev.behavior(void 0)
        };
        plugin.state.data.events.object.removed.subscribe(function (o) {
            var _a;
            var _b;
            if (!objects["a" /* PluginStateObject */].Molecule.Structure.is(o.obj))
                return;
            if (((_b = _this.current) === null || _b === void 0 ? void 0 : _b.loci.structure) === o.obj.data) {
                _this.clear();
            }
            var keep = [];
            for (var _i = 0, _c = _this.history; _i < _c.length; _i++) {
                var e = _c[_i];
                if (e.loci.structure === o.obj.data)
                    keep.push(e);
            }
            if (keep.length !== _this.history.length) {
                _this.history.length = 0;
                (_a = _this.history).push.apply(_a, keep);
                _this.events.historyUpdated.next();
            }
        });
        return _this;
        // plugin.state.data.events.object.updated.subscribe(e => this.onUpdate(e.ref, e.oldObj, e.obj));
    }
    Object.defineProperty(StructureFocusManager.prototype, "current", {
        get: function () { return this.state.current; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureFocusManager.prototype, "history", {
        get: function () { return this.state.history; },
        enumerable: false,
        configurable: true
    });
    StructureFocusManager.prototype.tryAddHistory = function (entry) {
        if (mol_model_structure["StructureElement"].Loci.isEmpty(entry.loci))
            return;
        var idx = 0, existingEntry = void 0;
        for (var _i = 0, _a = this.state.history; _i < _a.length; _i++) {
            var e = _a[_i];
            if (mol_model_structure["StructureElement"].Loci.areEqual(e.loci, entry.loci)) {
                existingEntry = e;
                break;
            }
            idx++;
        }
        if (existingEntry) {
            // move to top, use new
            Object(mol_util_array["arrayRemoveAtInPlace"])(this.state.history, idx);
            this.state.history.unshift(entry);
            this.events.historyUpdated.next();
            return;
        }
        this.state.history.unshift(entry);
        if (this.state.history.length > HISTORY_CAPACITY)
            this.state.history.pop();
        this.events.historyUpdated.next();
    };
    StructureFocusManager.prototype.set = function (entry) {
        this.tryAddHistory(entry);
        if (!this.state.current || !mol_model_structure["StructureElement"].Loci.areEqual(this.state.current.loci, entry.loci)) {
            this.state.current = entry;
            this.behaviors.current.next(entry);
        }
    };
    StructureFocusManager.prototype.setFromLoci = function (anyLoci) {
        var loci = mol_model_loci["Loci"].normalize(anyLoci);
        if (!mol_model_structure["StructureElement"].Loci.is(loci) || mol_model_structure["StructureElement"].Loci.isEmpty(loci)) {
            this.clear();
            return;
        }
        this.set({ loci: loci, label: Object(mol_theme_label["lociLabel"])(loci, { reverse: true, hidePrefix: true, htmlStyling: false }) });
    };
    StructureFocusManager.prototype.addFromLoci = function (anyLoci) {
        var union = this.state.current && mol_model_structure["StructureElement"].Loci.is(anyLoci) && anyLoci.structure === this.state.current.loci.structure
            ? mol_model_structure["StructureElement"].Loci.union(anyLoci, this.state.current.loci)
            : anyLoci;
        this.setFromLoci(union);
    };
    StructureFocusManager.prototype.clear = function () {
        if (this.state.current) {
            this.state.current = undefined;
            this.behaviors.current.next(void 0);
        }
    };
    StructureFocusManager.prototype.getSnapshot = function () {
        if (!this.current)
            return {};
        var node = this.plugin.helpers.substructureParent.get(this.current.loci.structure);
        var ref = node === null || node === void 0 ? void 0 : node.transform.ref;
        if (!ref)
            return {};
        return {
            current: {
                label: this.current.label,
                ref: ref,
                bundle: mol_model_structure["StructureElement"].Bundle.fromLoci(this.current.loci),
                category: this.current.category
            }
        };
    };
    StructureFocusManager.prototype.setSnapshot = function (snapshot) {
        var _a, _b;
        if (!snapshot.current) {
            this.clear();
            return;
        }
        var _c = snapshot.current, label = _c.label, ref = _c.ref, bundle = _c.bundle, category = _c.category;
        var structure = (_b = (_a = this.plugin.state.data.select(mol_state["StateSelection"].Generators.byRef(ref))[0]) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!structure)
            return;
        var loci = mol_model_structure["StructureElement"].Bundle.toLoci(bundle, structure);
        this.set({ label: label, loci: loci, category: category });
    };
    return StructureFocusManager;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));

//# sourceMappingURL=focus.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/hierarchy.js + 1 modules
var hierarchy = __webpack_require__(255);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/measurement.js
var measurement = __webpack_require__(369);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/matrix/principal-axes.js + 1 modules
var principal_axes = __webpack_require__(227);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/structure/selection.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














var boundaryHelper = new boundary_helper["a" /* BoundaryHelper */]('98');
var selection_HISTORY_CAPACITY = 24;
var selection_StructureSelectionManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureSelectionManager, _super);
    function StructureSelectionManager(plugin) {
        var _this = _super.call(this, { entries: new Map(), additionsHistory: [], stats: SelectionStats() }) || this;
        _this.plugin = plugin;
        _this.events = {
            changed: _this.ev(),
            additionsHistoryUpdated: _this.ev(),
            loci: {
                add: _this.ev(),
                remove: _this.ev(),
                clear: _this.ev()
            }
        };
        // listen to events from substructureParent helper to ensure it is updated
        plugin.helpers.substructureParent.events.removed.subscribe(function (e) { return _this.onRemove(e.ref, e.obj); });
        plugin.helpers.substructureParent.events.updated.subscribe(function (e) { return _this.onUpdate(e.ref, e.oldObj, e.obj); });
        return _this;
    }
    Object.defineProperty(StructureSelectionManager.prototype, "entries", {
        get: function () { return this.state.entries; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSelectionManager.prototype, "additionsHistory", {
        get: function () { return this.state.additionsHistory; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(StructureSelectionManager.prototype, "stats", {
        get: function () {
            if (this.state.stats)
                return this.state.stats;
            this.state.stats = this.calcStats();
            return this.state.stats;
        },
        enumerable: false,
        configurable: true
    });
    StructureSelectionManager.prototype.getEntry = function (s) {
        // ignore decorators to get stable ref
        var cell = this.plugin.helpers.substructureParent.get(s, true);
        if (!cell)
            return;
        var ref = cell.transform.ref;
        if (!this.entries.has(ref)) {
            var entry = new selection_SelectionEntry(mol_model_structure["StructureElement"].Loci(s, []));
            this.entries.set(ref, entry);
            return entry;
        }
        return this.entries.get(ref);
    };
    StructureSelectionManager.prototype.calcStats = function () {
        var structureCount = 0;
        var elementCount = 0;
        var stats = mol_model_structure["StructureElement"].Stats.create();
        this.entries.forEach(function (v) {
            var elements = v.selection.elements;
            if (elements.length) {
                structureCount += 1;
                for (var i = 0, il = elements.length; i < il; ++i) {
                    elementCount += mol_data_int["OrderedSet"].size(elements[i].indices);
                }
                mol_model_structure["StructureElement"].Stats.add(stats, stats, mol_model_structure["StructureElement"].Stats.ofLoci(v.selection));
            }
        });
        var label = Object(mol_theme_label["structureElementStatsLabel"])(stats, { countsOnly: true });
        return { structureCount: structureCount, elementCount: elementCount, label: label };
    };
    StructureSelectionManager.prototype.add = function (loci) {
        if (!mol_model_structure["StructureElement"].Loci.is(loci))
            return false;
        var entry = this.getEntry(loci.structure);
        if (!entry)
            return false;
        var sel = entry.selection;
        entry.selection = mol_model_structure["StructureElement"].Loci.union(entry.selection, loci);
        this.tryAddHistory(loci);
        this.referenceLoci = loci;
        this.events.loci.add.next(loci);
        return !mol_model_structure["StructureElement"].Loci.areEqual(sel, entry.selection);
    };
    StructureSelectionManager.prototype.remove = function (loci) {
        if (!mol_model_structure["StructureElement"].Loci.is(loci))
            return false;
        var entry = this.getEntry(loci.structure);
        if (!entry)
            return false;
        var sel = entry.selection;
        entry.selection = mol_model_structure["StructureElement"].Loci.subtract(entry.selection, loci);
        // this.addHistory(loci);
        this.referenceLoci = loci;
        this.events.loci.remove.next(loci);
        return !mol_model_structure["StructureElement"].Loci.areEqual(sel, entry.selection);
    };
    StructureSelectionManager.prototype.intersect = function (loci) {
        if (!mol_model_structure["StructureElement"].Loci.is(loci))
            return false;
        var entry = this.getEntry(loci.structure);
        if (!entry)
            return false;
        var sel = entry.selection;
        entry.selection = mol_model_structure["StructureElement"].Loci.intersect(entry.selection, loci);
        // this.addHistory(loci);
        this.referenceLoci = loci;
        return !mol_model_structure["StructureElement"].Loci.areEqual(sel, entry.selection);
    };
    StructureSelectionManager.prototype.set = function (loci) {
        if (!mol_model_structure["StructureElement"].Loci.is(loci))
            return false;
        var entry = this.getEntry(loci.structure);
        if (!entry)
            return false;
        var sel = entry.selection;
        entry.selection = loci;
        this.tryAddHistory(loci);
        this.referenceLoci = undefined;
        return !mol_model_structure["StructureElement"].Loci.areEqual(sel, entry.selection);
    };
    StructureSelectionManager.prototype.modifyHistory = function (entry, action, modulus, groupByStructure) {
        if (groupByStructure === void 0) { groupByStructure = false; }
        var history = this.additionsHistory;
        var idx = history.indexOf(entry);
        if (idx < 0)
            return;
        var swapWith = void 0;
        switch (action) {
            case 'remove':
                Object(mol_util_array["arrayRemoveAtInPlace"])(history, idx);
                break;
            case 'up':
                swapWith = idx - 1;
                break;
            case 'down':
                swapWith = idx + 1;
                break;
        }
        if (swapWith !== void 0) {
            var mod = modulus ? Math.min(history.length, modulus) : history.length;
            while (true) {
                swapWith = swapWith % mod;
                if (swapWith < 0)
                    swapWith += mod;
                if (!groupByStructure || history[idx].loci.structure === history[swapWith].loci.structure) {
                    var t = history[idx];
                    history[idx] = history[swapWith];
                    history[swapWith] = t;
                    break;
                }
                else {
                    swapWith += action === 'up' ? -1 : +1;
                }
            }
        }
        this.events.additionsHistoryUpdated.next();
    };
    StructureSelectionManager.prototype.tryAddHistory = function (loci) {
        if (mol_model_loci["Loci"].isEmpty(loci))
            return;
        var idx = 0, entry = void 0;
        for (var _i = 0, _a = this.additionsHistory; _i < _a.length; _i++) {
            var l = _a[_i];
            if (mol_model_loci["Loci"].areEqual(l.loci, loci)) {
                entry = l;
                break;
            }
            idx++;
        }
        if (entry) {
            // move to top
            Object(mol_util_array["arrayRemoveAtInPlace"])(this.additionsHistory, idx);
            this.additionsHistory.unshift(entry);
            this.events.additionsHistoryUpdated.next();
            return;
        }
        var stats = mol_model_structure["StructureElement"].Stats.ofLoci(loci);
        var label = Object(mol_theme_label["structureElementStatsLabel"])(stats, { reverse: true });
        this.additionsHistory.unshift({ id: mol_util["c" /* UUID */].create22(), loci: loci, label: label });
        if (this.additionsHistory.length > selection_HISTORY_CAPACITY)
            this.additionsHistory.pop();
        this.events.additionsHistoryUpdated.next();
    };
    StructureSelectionManager.prototype.clearHistory = function () {
        if (this.state.additionsHistory.length !== 0) {
            this.state.additionsHistory = [];
            this.events.additionsHistoryUpdated.next();
        }
    };
    StructureSelectionManager.prototype.clearHistoryForStructure = function (structure) {
        var historyEntryToRemove = [];
        for (var _i = 0, _a = this.state.additionsHistory; _i < _a.length; _i++) {
            var e = _a[_i];
            if (e.loci.structure.root === structure.root) {
                historyEntryToRemove.push(e);
            }
        }
        for (var _b = 0, historyEntryToRemove_1 = historyEntryToRemove; _b < historyEntryToRemove_1.length; _b++) {
            var e = historyEntryToRemove_1[_b];
            this.modifyHistory(e, 'remove');
        }
        if (historyEntryToRemove.length !== 0) {
            this.events.additionsHistoryUpdated.next();
        }
    };
    StructureSelectionManager.prototype.onRemove = function (ref, obj) {
        var _a;
        if (this.entries.has(ref)) {
            this.entries.delete(ref);
            if (obj === null || obj === void 0 ? void 0 : obj.data) {
                this.clearHistoryForStructure(obj.data);
            }
            if (((_a = this.referenceLoci) === null || _a === void 0 ? void 0 : _a.structure) === (obj === null || obj === void 0 ? void 0 : obj.data)) {
                this.referenceLoci = undefined;
            }
            this.state.stats = void 0;
            this.events.changed.next();
        }
    };
    StructureSelectionManager.prototype.onUpdate = function (ref, oldObj, obj) {
        var _a, _b, _c, _d;
        // no change to structure
        if (oldObj === obj || (oldObj === null || oldObj === void 0 ? void 0 : oldObj.data) === obj.data)
            return;
        // ignore decorators to get stable ref
        var cell = this.plugin.helpers.substructureParent.get(obj.data, true);
        if (!cell)
            return;
        ref = cell.transform.ref;
        if (!this.entries.has(ref))
            return;
        // use structure from last decorator as reference
        var structure = (_b = (_a = this.plugin.helpers.substructureParent.get(obj.data)) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!structure)
            return;
        // oldObj is not defined for inserts (e.g. TransformStructureConformation)
        if (!(oldObj === null || oldObj === void 0 ? void 0 : oldObj.data) || mol_model_structure["Structure"].areUnitAndIndicesEqual(oldObj.data, obj.data)) {
            this.entries.set(ref, remapSelectionEntry(this.entries.get(ref), structure));
            // remap referenceLoci & prevHighlight if needed and possible
            if (((_c = this.referenceLoci) === null || _c === void 0 ? void 0 : _c.structure.root) === structure.root) {
                this.referenceLoci = mol_model_structure["StructureElement"].Loci.remap(this.referenceLoci, structure);
            }
            // remap history locis if needed and possible
            var changedHistory = false;
            for (var _i = 0, _f = this.state.additionsHistory; _i < _f.length; _i++) {
                var e = _f[_i];
                if (e.loci.structure.root === structure.root) {
                    e.loci = mol_model_structure["StructureElement"].Loci.remap(e.loci, structure);
                    changedHistory = true;
                }
            }
            if (changedHistory)
                this.events.additionsHistoryUpdated.next();
        }
        else {
            // clear the selection for ref
            this.entries.set(ref, new selection_SelectionEntry(mol_model_structure["StructureElement"].Loci(structure, [])));
            if (((_d = this.referenceLoci) === null || _d === void 0 ? void 0 : _d.structure.root) === structure.root) {
                this.referenceLoci = undefined;
            }
            this.clearHistoryForStructure(structure);
            this.state.stats = void 0;
            this.events.changed.next();
        }
    };
    /** Removes all selections and returns them */
    StructureSelectionManager.prototype.clear = function () {
        var keys = this.entries.keys();
        var selections = [];
        while (true) {
            var k = keys.next();
            if (k.done)
                break;
            var s = this.entries.get(k.value);
            if (!mol_model_structure["StructureElement"].Loci.isEmpty(s.selection))
                selections.push(s.selection);
            s.selection = mol_model_structure["StructureElement"].Loci(s.selection.structure, []);
        }
        this.referenceLoci = undefined;
        this.state.stats = void 0;
        this.events.changed.next();
        this.events.loci.clear.next();
        this.clearHistory();
        return selections;
    };
    StructureSelectionManager.prototype.getLoci = function (structure) {
        var entry = this.getEntry(structure);
        if (!entry)
            return mol_model_loci["EmptyLoci"];
        return entry.selection;
    };
    StructureSelectionManager.prototype.getStructure = function (structure) {
        var entry = this.getEntry(structure);
        if (!entry)
            return;
        return entry.structure;
    };
    StructureSelectionManager.prototype.structureHasSelection = function (structure) {
        var _a, _b;
        var s = (_b = (_a = structure.cell) === null || _a === void 0 ? void 0 : _a.obj) === null || _b === void 0 ? void 0 : _b.data;
        if (!s)
            return false;
        var entry = this.getEntry(s);
        return !!entry && !mol_model_structure["StructureElement"].Loci.isEmpty(entry.selection);
    };
    StructureSelectionManager.prototype.has = function (loci) {
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            var entry = this.getEntry(loci.structure);
            if (entry) {
                return mol_model_structure["StructureElement"].Loci.isSubset(entry.selection, loci);
            }
        }
        return false;
    };
    StructureSelectionManager.prototype.tryGetRange = function (loci) {
        if (!mol_model_structure["StructureElement"].Loci.is(loci))
            return;
        if (loci.elements.length !== 1)
            return;
        var entry = this.getEntry(loci.structure);
        if (!entry)
            return;
        var xs = loci.elements[0];
        if (!xs)
            return;
        var ref = this.referenceLoci;
        if (!ref || !mol_model_structure["StructureElement"].Loci.is(ref) || ref.structure !== loci.structure)
            return;
        var e;
        for (var _i = 0, _a = ref.elements; _i < _a.length; _i++) {
            var _e = _a[_i];
            if (xs.unit === _e.unit) {
                e = _e;
                break;
            }
        }
        if (!e)
            return;
        if (xs.unit !== e.unit)
            return;
        return getElementRange(loci.structure, e, xs);
    };
    /** Count of all selected elements */
    StructureSelectionManager.prototype.elementCount = function () {
        var count = 0;
        this.entries.forEach(function (v) {
            count += mol_model_structure["StructureElement"].Loci.size(v.selection);
        });
        return count;
    };
    StructureSelectionManager.prototype.getBoundary = function () {
        var min = linear_algebra["Vec3"].create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
        var max = linear_algebra["Vec3"].create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
        boundaryHelper.reset();
        var boundaries = [];
        this.entries.forEach(function (v) {
            var loci = v.selection;
            if (!mol_model_structure["StructureElement"].Loci.isEmpty(loci)) {
                boundaries.push(mol_model_structure["StructureElement"].Loci.getBoundary(loci));
            }
        });
        for (var i = 0, il = boundaries.length; i < il; ++i) {
            var _a = boundaries[i], box = _a.box, sphere = _a.sphere;
            linear_algebra["Vec3"].min(min, min, box.min);
            linear_algebra["Vec3"].max(max, max, box.max);
            boundaryHelper.includePositionRadius(sphere.center, sphere.radius);
        }
        boundaryHelper.finishedIncludeStep();
        for (var i = 0, il = boundaries.length; i < il; ++i) {
            var sphere = boundaries[i].sphere;
            boundaryHelper.radiusPositionRadius(sphere.center, sphere.radius);
        }
        return { box: { min: min, max: max }, sphere: boundaryHelper.getSphere() };
    };
    StructureSelectionManager.prototype.getPrincipalAxes = function () {
        var elementCount = this.elementCount();
        var positions = new Float32Array(3 * elementCount);
        var offset = 0;
        this.entries.forEach(function (v) {
            mol_model_structure["StructureElement"].Loci.toPositionsArray(v.selection, positions, offset);
            offset += mol_model_structure["StructureElement"].Loci.size(v.selection) * 3;
        });
        return principal_axes["a" /* PrincipalAxes */].ofPositions(positions);
    };
    StructureSelectionManager.prototype.modify = function (modifier, loci) {
        var changed = false;
        switch (modifier) {
            case 'add':
                changed = this.add(loci);
                break;
            case 'remove':
                changed = this.remove(loci);
                break;
            case 'intersect':
                changed = this.intersect(loci);
                break;
            case 'set':
                changed = this.set(loci);
                break;
        }
        if (changed) {
            this.state.stats = void 0;
            this.events.changed.next();
        }
    };
    Object.defineProperty(StructureSelectionManager.prototype, "applicableStructures", {
        get: function () {
            return this.plugin.managers.structure.hierarchy.selection.structures
                .filter(function (s) { return !!s.cell.obj; })
                .map(function (s) { return s.cell.obj.data; });
        },
        enumerable: false,
        configurable: true
    });
    StructureSelectionManager.prototype.triggerInteraction = function (modifier, loci, applyGranularity) {
        if (applyGranularity === void 0) { applyGranularity = true; }
        switch (modifier) {
            case 'add':
                this.plugin.managers.interactivity.lociSelects.select({ loci: loci }, applyGranularity);
                break;
            case 'remove':
                this.plugin.managers.interactivity.lociSelects.deselect({ loci: loci }, applyGranularity);
                break;
            case 'intersect':
                this.plugin.managers.interactivity.lociSelects.selectJoin({ loci: loci }, applyGranularity);
                break;
            case 'set':
                this.plugin.managers.interactivity.lociSelects.selectOnly({ loci: loci }, applyGranularity);
                break;
        }
    };
    StructureSelectionManager.prototype.fromLoci = function (modifier, loci, applyGranularity) {
        if (applyGranularity === void 0) { applyGranularity = true; }
        this.triggerInteraction(modifier, loci, applyGranularity);
    };
    StructureSelectionManager.prototype.fromSelectionQuery = function (modifier, query, applyGranularity) {
        var _this = this;
        if (applyGranularity === void 0) { applyGranularity = true; }
        this.plugin.runTask(mol_task["b" /* Task */].create('Structure Selection', function (runtime) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var _i, _a, s, loci;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _i = 0, _a = this.applicableStructures;
                        _b.label = 1;
                    case 1:
                        if (!(_i < _a.length)) return [3 /*break*/, 4];
                        s = _a[_i];
                        return [4 /*yield*/, query.getSelection(this.plugin, runtime, s)];
                    case 2:
                        loci = _b.sent();
                        this.triggerInteraction(modifier, mol_model_structure["StructureSelection"].toLociWithSourceUnits(loci), applyGranularity);
                        _b.label = 3;
                    case 3:
                        _i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        }); }));
    };
    StructureSelectionManager.prototype.fromSelections = function (ref) {
        var _a;
        var cell = mol_state["StateObjectRef"].resolveAndCheck(this.plugin.state.data, ref);
        if (!cell || !cell.obj)
            return;
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.Selections.is(cell.obj)) {
            console.warn('fromSelections applied to wrong object type.', cell.obj);
            return;
        }
        this.clear();
        for (var _i = 0, _b = (_a = cell.obj) === null || _a === void 0 ? void 0 : _a.data; _i < _b.length; _i++) {
            var s = _b[_i];
            this.fromLoci('set', s.loci);
        }
    };
    return StructureSelectionManager;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));

function SelectionStats() { return { structureCount: 0, elementCount: 0, label: 'Nothing Selected' }; }
;
var selection_SelectionEntry = /** @class */ (function () {
    function SelectionEntry(selection) {
        this._structure = void 0;
        this._selection = selection;
    }
    Object.defineProperty(SelectionEntry.prototype, "selection", {
        get: function () { return this._selection; },
        set: function (value) {
            this._selection = value;
            this._structure = void 0;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SelectionEntry.prototype, "structure", {
        get: function () {
            if (this._structure)
                return this._structure;
            if (mol_model_loci["Loci"].isEmpty(this._selection)) {
                this._structure = void 0;
            }
            else {
                this._structure = mol_model_structure["StructureElement"].Loci.toStructure(this._selection);
            }
            return this._structure;
        },
        enumerable: false,
        configurable: true
    });
    return SelectionEntry;
}());
/** remap `selection-entry` to be related to `structure` if possible */
function remapSelectionEntry(e, s) {
    return new selection_SelectionEntry(mol_model_structure["StructureElement"].Loci.remap(e.selection, s));
}
/**
 * Assumes `ref` and `ext` belong to the same unit in the same structure
 */
function getElementRange(structure, ref, ext) {
    var min = Math.min(mol_data_int["OrderedSet"].min(ref.indices), mol_data_int["OrderedSet"].min(ext.indices));
    var max = Math.max(mol_data_int["OrderedSet"].max(ref.indices), mol_data_int["OrderedSet"].max(ext.indices));
    return mol_model_structure["StructureElement"].Loci(structure, [{
            unit: ref.unit,
            indices: mol_data_int["OrderedSet"].ofRange(min, max)
        }]);
}
//# sourceMappingURL=selection.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/units-visual.js
var units_visual = __webpack_require__(48);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/sphere.js + 2 modules
var primitive_sphere = __webpack_require__(264);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh-builder.js
var mesh_builder = __webpack_require__(34);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/sphere.js
var builder_sphere = __webpack_require__(75);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/location-iterator.js
var location_iterator = __webpack_require__(86);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/spheres/spheres.js
var spheres_spheres = __webpack_require__(258);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/spheres/spheres-builder.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var quadMapping = new Float32Array([
    -1.0, 1.0,
    -1.0, -1.0,
    1.0, 1.0,
    1.0, -1.0
]);
var quadIndices = new Uint16Array([
    0, 1, 2,
    1, 3, 2
]);
var spheres_builder_SpheresBuilder;
(function (SpheresBuilder) {
    function create(initialCount, chunkSize, spheres) {
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        initialCount *= 4;
        chunkSize *= 4;
        var centers = util["a" /* ChunkedArray */].create(Float32Array, 3, chunkSize, spheres ? spheres.centerBuffer.ref.value : initialCount);
        var mappings = util["a" /* ChunkedArray */].create(Float32Array, 2, chunkSize, spheres ? spheres.mappingBuffer.ref.value : initialCount);
        var indices = util["a" /* ChunkedArray */].create(Uint32Array, 3, chunkSize / 2, spheres ? spheres.indexBuffer.ref.value : initialCount / 2);
        var groups = util["a" /* ChunkedArray */].create(Float32Array, 1, chunkSize, spheres ? spheres.groupBuffer.ref.value : initialCount);
        return {
            add: function (x, y, z, group) {
                var offset = centers.elementCount;
                for (var i = 0; i < 4; ++i) {
                    util["a" /* ChunkedArray */].add3(centers, x, y, z);
                    util["a" /* ChunkedArray */].add2(mappings, quadMapping[i * 2], quadMapping[i * 2 + 1]);
                    util["a" /* ChunkedArray */].add(groups, group);
                }
                util["a" /* ChunkedArray */].add3(indices, offset + quadIndices[0], offset + quadIndices[1], offset + quadIndices[2]);
                util["a" /* ChunkedArray */].add3(indices, offset + quadIndices[3], offset + quadIndices[4], offset + quadIndices[5]);
            },
            getSpheres: function () {
                var cb = util["a" /* ChunkedArray */].compact(centers, true);
                var mb = util["a" /* ChunkedArray */].compact(mappings, true);
                var ib = util["a" /* ChunkedArray */].compact(indices, true);
                var gb = util["a" /* ChunkedArray */].compact(groups, true);
                return spheres_spheres["a" /* Spheres */].create(cb, mb, ib, gb, centers.elementCount / 4, spheres);
            }
        };
    }
    SpheresBuilder.create = create;
})(spheres_builder_SpheresBuilder || (spheres_builder_SpheresBuilder = {}));
//# sourceMappingURL=spheres-builder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/common.js
var common = __webpack_require__(51);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/element.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */











function createElementSphereMesh(ctx, unit, structure, theme, props, mesh) {
    var detail = props.detail, sizeFactor = props.sizeFactor, ignoreHydrogens = props.ignoreHydrogens, traceOnly = props.traceOnly;
    var elements = unit.elements;
    var elementCount = elements.length;
    var vertexCount = elementCount * Object(primitive_sphere["b" /* sphereVertexCount */])(detail);
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 2, mesh);
    var v = linear_algebra["Vec3"].zero();
    var pos = unit.conformation.invariantPosition;
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    l.unit = unit;
    for (var i = 0; i < elementCount; i++) {
        if (ignoreHydrogens && Object(common["k" /* isHydrogen */])(unit, elements[i]))
            continue;
        if (traceOnly && !Object(common["l" /* isTrace */])(unit, elements[i]))
            continue;
        l.element = elements[i];
        pos(elements[i], v);
        builderState.currentGroup = i;
        Object(builder_sphere["a" /* addSphere */])(builderState, v, theme.size.size(l) * sizeFactor, detail);
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
function createElementSphereImpostor(ctx, unit, structure, theme, props, spheres) {
    var ignoreHydrogens = props.ignoreHydrogens, traceOnly = props.traceOnly;
    var elements = unit.elements;
    var elementCount = elements.length;
    var builder = spheres_builder_SpheresBuilder.create(elementCount, elementCount / 2, spheres);
    var v = linear_algebra["Vec3"].zero();
    var pos = unit.conformation.invariantPosition;
    for (var i = 0; i < elementCount; i++) {
        if (ignoreHydrogens && Object(common["k" /* isHydrogen */])(unit, elements[i]))
            continue;
        if (traceOnly && !Object(common["l" /* isTrace */])(unit, elements[i]))
            continue;
        pos(elements[i], v);
        builder.add(v[0], v[1], v[2], i);
    }
    var s = builder.getSpheres();
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1);
    s.setBoundingSphere(sphere);
    return s;
}
function eachElement(loci, structureGroup, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    var structure = structureGroup.structure, group = structureGroup.group;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var elementCount = group.elements.length;
    for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
        var e = _b[_a];
        var unitIdx = group.unitIndexMap.get(e.unit.id);
        if (unitIdx !== undefined) {
            var offset = unitIdx * elementCount; // to target unit instance
            if (mol_data_int["Interval"].is(e.indices)) {
                var start = offset + mol_data_int["Interval"].start(e.indices);
                var end = offset + mol_data_int["Interval"].end(e.indices);
                if (apply(mol_data_int["Interval"].ofBounds(start, end)))
                    changed = true;
            }
            else {
                for (var i = 0, _i = e.indices.length; i < _i; i++) {
                    var start = e.indices[i];
                    var endI = i + 1;
                    while (endI < _i && e.indices[endI] === start)
                        endI++;
                    i = endI - 1;
                    var end = e.indices[i];
                    changed = apply(mol_data_int["Interval"].ofRange(offset + start, offset + end)) || changed;
                }
            }
        }
    }
    return changed;
}
function getElementLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        var indices = mol_data_int["OrderedSet"].ofSingleton(groupId);
        return mol_model_structure["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
    }
    return mol_model_loci["EmptyLoci"];
}
//
function eachSerialElement(loci, structure, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var cumulativeUnitElementCount = structure.serialMapping.cumulativeUnitElementCount;
    for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
        var e = _b[_a];
        var unitIdx = structure.unitIndexMap.get(e.unit.id);
        if (unitIdx !== undefined) {
            if (mol_data_int["Interval"].is(e.indices)) {
                var start = cumulativeUnitElementCount[unitIdx] + mol_data_int["Interval"].start(e.indices);
                var end = cumulativeUnitElementCount[unitIdx] + mol_data_int["Interval"].end(e.indices);
                if (apply(mol_data_int["Interval"].ofBounds(start, end)))
                    changed = true;
            }
            else {
                for (var i = 0, _i = e.indices.length; i < _i; i++) {
                    var idx = cumulativeUnitElementCount[unitIdx] + e.indices[i];
                    if (apply(mol_data_int["Interval"].ofSingleton(idx)))
                        changed = true;
                }
            }
        }
    }
    return changed;
}
function getSerialElementLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var _a = structure.serialMapping, unitIndices = _a.unitIndices, cumulativeUnitElementCount = _a.cumulativeUnitElementCount;
        var unitIdx = unitIndices[groupId];
        var unit = structure.units[unitIdx];
        var idx = groupId - cumulativeUnitElementCount[unitIdx];
        var indices = mol_data_int["OrderedSet"].ofSingleton(idx);
        return mol_model_structure["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
    }
    return mol_model_loci["EmptyLoci"];
}
//
var element_ElementIterator;
(function (ElementIterator) {
    function fromGroup(structureGroup) {
        var group = structureGroup.group, structure = structureGroup.structure;
        var groupCount = group.elements.length;
        var instanceCount = group.units.length;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex, instanceIndex) {
            var unit = group.units[instanceIndex];
            location.unit = unit;
            location.element = unit.elements[groupIndex];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
    }
    ElementIterator.fromGroup = fromGroup;
    function fromStructure(structure) {
        var units = structure.units, elementCount = structure.elementCount;
        var groupCount = elementCount;
        var instanceCount = 1;
        var _a = structure.serialMapping, unitIndices = _a.unitIndices, elementIndices = _a.elementIndices;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex) {
            location.unit = units[unitIndices[groupIndex]];
            location.element = elementIndices[groupIndex];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
    }
    ElementIterator.fromStructure = fromStructure;
})(element_ElementIterator || (element_ElementIterator = {}));
//# sourceMappingURL=element.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/base.js
var base = __webpack_require__(33);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/element-sphere.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */





var ElementSphereParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), units_visual["g" /* UnitsSpheresParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false), traceOnly: param_definition["ParamDefinition"].Boolean(false) });
function getElementSphereVisual(webgl) {
    return webgl && webgl.extensions.fragDepth ? ElementSphereImpostorVisual : ElementSphereMeshVisual;
}
function ElementSphereImpostorVisual(materialId) {
    return Object(units_visual["h" /* UnitsSpheresVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(ElementSphereParams),
        createGeometry: createElementSphereImpostor,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                newProps.traceOnly !== currentProps.traceOnly);
        }
    }, materialId);
}
function ElementSphereMeshVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(ElementSphereParams),
        createGeometry: createElementSphereMesh,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                newProps.traceOnly !== currentProps.traceOnly);
        }
    }, materialId);
}
//# sourceMappingURL=element-sphere.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/mesh.js
var mesh_mesh = __webpack_require__(39);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/link.js
var util_link = __webpack_require__(63);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/model/types.js + 1 modules
var types = __webpack_require__(22);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/type-helpers.js
var type_helpers = __webpack_require__(283);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/bond.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var BondParams = {
    includeTypes: param_definition["ParamDefinition"].MultiSelect(Object(type_helpers["a" /* ObjectKeys */])(types["BondType"].Names), param_definition["ParamDefinition"].objectToOptions(types["BondType"].Names)),
    excludeTypes: param_definition["ParamDefinition"].MultiSelect([], param_definition["ParamDefinition"].objectToOptions(types["BondType"].Names)),
};
var DefaultBondProps = param_definition["ParamDefinition"].getDefaultValues(BondParams);
var BondCylinderParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util_link["a" /* LinkCylinderParams */]), BondParams);
var DefaultBondCylinderProps = param_definition["ParamDefinition"].getDefaultValues(BondCylinderParams);
var BondLineParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, util_link["b" /* LinkLineParams */]), BondParams);
var DefaultBondLineProps = param_definition["ParamDefinition"].getDefaultValues(BondLineParams);
function ignoreBondType(include, exclude, f) {
    return !types["BondType"].is(include, f) || types["BondType"].is(exclude, f);
}
var bond_BondIterator;
(function (BondIterator) {
    function fromGroup(structureGroup) {
        var group = structureGroup.group, structure = structureGroup.structure;
        var unit = group.units[0];
        var groupCount = mol_model_structure["Unit"].isAtomic(unit) ? unit.bonds.edgeCount * 2 : 0;
        var instanceCount = group.units.length;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex, instanceIndex) {
            var unit = group.units[instanceIndex];
            location.unit = unit;
            location.element = unit.elements[unit.bonds.a[groupIndex]];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
    }
    BondIterator.fromGroup = fromGroup;
    function fromStructure(structure) {
        var groupCount = structure.interUnitBonds.edgeCount;
        var instanceCount = 1;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex) {
            var bond = structure.interUnitBonds.edges[groupIndex];
            location.unit = bond.unitA;
            location.element = bond.unitA.elements[bond.indexA];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
    }
    BondIterator.fromStructure = fromStructure;
})(bond_BondIterator || (bond_BondIterator = {}));
//
function getIntraBondLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        if (mol_model_structure["Unit"].isAtomic(unit)) {
            return mol_model_structure["Bond"].Loci(structure, [
                mol_model_structure["Bond"].Location(structure, unit, unit.bonds.a[groupId], structure, unit, unit.bonds.b[groupId]),
                mol_model_structure["Bond"].Location(structure, unit, unit.bonds.b[groupId], structure, unit, unit.bonds.a[groupId])
            ]);
        }
    }
    return mol_model_loci["EmptyLoci"];
}
function eachIntraBond(loci, structureGroup, apply, isMarking) {
    var changed = false;
    if (mol_model_structure["Bond"].isLoci(loci)) {
        var structure = structureGroup.structure, group = structureGroup.group;
        if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
            return false;
        var unit = group.units[0];
        if (!mol_model_structure["Unit"].isAtomic(unit))
            return false;
        var groupCount = unit.bonds.edgeCount * 2;
        for (var _i = 0, _a = loci.bonds; _i < _a.length; _i++) {
            var b = _a[_i];
            var unitIdx = group.unitIndexMap.get(b.aUnit.id);
            if (unitIdx !== undefined) {
                var idx = unit.bonds.getDirectedEdgeIndex(b.aIndex, b.bIndex);
                if (idx !== -1) {
                    if (apply(mol_data_int["Interval"].ofSingleton(unitIdx * groupCount + idx)))
                        changed = true;
                }
            }
        }
    }
    else if (mol_model_structure["StructureElement"].Loci.is(loci)) {
        var structure = structureGroup.structure, group = structureGroup.group;
        if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
            return false;
        var unit = group.units[0];
        if (!mol_model_structure["Unit"].isAtomic(unit))
            return false;
        var groupCount_1 = unit.bonds.edgeCount * 2;
        var _loop_1 = function (e) {
            var unitIdx = group.unitIndexMap.get(e.unit.id);
            if (unitIdx !== undefined) {
                var _a = unit.bonds, offset_1 = _a.offset, b_1 = _a.b;
                mol_data_int["OrderedSet"].forEach(e.indices, function (v) {
                    for (var t = offset_1[v], _t = offset_1[v + 1]; t < _t; t++) {
                        if (!isMarking || mol_data_int["OrderedSet"].has(e.indices, b_1[t])) {
                            if (apply(mol_data_int["Interval"].ofSingleton(unitIdx * groupCount_1 + t)))
                                changed = true;
                        }
                    }
                });
            }
        };
        for (var _b = 0, _c = loci.elements; _b < _c.length; _b++) {
            var e = _c[_b];
            _loop_1(e);
        }
    }
    return changed;
}
//
function getInterBondLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var bond = structure.interUnitBonds.edges[groupId];
        return mol_model_structure["Bond"].Loci(structure, [
            mol_model_structure["Bond"].Location(structure, bond.unitA, bond.indexA, structure, bond.unitB, bond.indexB),
            mol_model_structure["Bond"].Location(structure, bond.unitB, bond.indexB, structure, bond.unitA, bond.indexA)
        ]);
    }
    return mol_model_loci["EmptyLoci"];
}
function eachInterBond(loci, structure, apply, isMarking) {
    var changed = false;
    if (mol_model_structure["Bond"].isLoci(loci)) {
        if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
            return false;
        for (var _i = 0, _a = loci.bonds; _i < _a.length; _i++) {
            var b = _a[_i];
            var idx = structure.interUnitBonds.getBondIndexFromLocation(b);
            if (idx !== -1) {
                if (apply(mol_data_int["Interval"].ofSingleton(idx)))
                    changed = true;
            }
        }
    }
    else if (mol_model_structure["StructureElement"].Loci.is(loci)) {
        if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
            return false;
        if (loci.elements.length === 1)
            return false; // only a single unit
        var map_1 = new Map();
        for (var _b = 0, _c = loci.elements; _b < _c.length; _b++) {
            var e = _c[_b];
            map_1.set(e.unit.id, e.indices);
        }
        var _loop_2 = function (e) {
            var unit = e.unit;
            if (!mol_model_structure["Unit"].isAtomic(unit))
                return "continue";
            structure.interUnitBonds.getConnectedUnits(unit).forEach(function (b) {
                var otherLociIndices = map_1.get(b.unitB.id);
                if (otherLociIndices) {
                    mol_data_int["OrderedSet"].forEach(e.indices, function (v) {
                        if (!b.connectedIndices.includes(v))
                            return;
                        b.getEdges(v).forEach(function (bi) {
                            if (!isMarking || mol_data_int["OrderedSet"].has(otherLociIndices, bi.indexB)) {
                                var idx = structure.interUnitBonds.getEdgeIndex(v, unit, bi.indexB, b.unitB);
                                if (apply(mol_data_int["Interval"].ofSingleton(idx)))
                                    changed = true;
                            }
                        });
                    });
                }
            });
        };
        for (var _d = 0, _e = loci.elements; _d < _e.length; _d++) {
            var e = _e[_d];
            _loop_2(e);
        }
    }
    return changed;
}
//# sourceMappingURL=bond.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/bond-intra-unit-cylinder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */












function createIntraUnitBondCylinderMesh(ctx, unit, structure, theme, props, mesh) {
    if (!mol_model_structure["Unit"].isAtomic(unit))
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var location = mol_model_structure["StructureElement"].Location.create(structure, unit);
    var elements = unit.elements;
    var bonds = unit.bonds;
    var edgeCount = bonds.edgeCount, a = bonds.a, b = bonds.b, edgeProps = bonds.edgeProps, offset = bonds.offset;
    var _order = edgeProps.order, _flags = edgeProps.flags;
    var sizeFactor = props.sizeFactor, sizeAspectRatio = props.sizeAspectRatio, ignoreHydrogens = props.ignoreHydrogens, includeTypes = props.includeTypes, excludeTypes = props.excludeTypes;
    var include = types["BondType"].fromNames(includeTypes);
    var exclude = types["BondType"].fromNames(excludeTypes);
    var ignoreHydrogen = ignoreHydrogens ? function (edgeIndex) {
        return Object(common["k" /* isHydrogen */])(unit, elements[a[edgeIndex]]) || Object(common["k" /* isHydrogen */])(unit, elements[b[edgeIndex]]);
    } : function () { return false; };
    if (!edgeCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var vRef = linear_algebra["Vec3"].zero();
    var pos = unit.conformation.invariantPosition;
    var builderProps = {
        linkCount: edgeCount * 2,
        referencePosition: function (edgeIndex) {
            var _a, _b;
            var aI = a[edgeIndex], bI = b[edgeIndex];
            if (aI > bI)
                _a = [bI, aI], aI = _a[0], bI = _a[1];
            if (offset[aI + 1] - offset[aI] === 1)
                _b = [bI, aI], aI = _b[0], bI = _b[1];
            // TODO prefer reference atoms in rings
            for (var i = offset[aI], il = offset[aI + 1]; i < il; ++i) {
                var _bI = b[i];
                if (_bI !== bI && _bI !== aI)
                    return pos(elements[_bI], vRef);
            }
            for (var i = offset[bI], il = offset[bI + 1]; i < il; ++i) {
                var _aI = a[i];
                if (_aI !== aI && _aI !== bI)
                    return pos(elements[_aI], vRef);
            }
            return null;
        },
        position: function (posA, posB, edgeIndex) {
            pos(elements[a[edgeIndex]], posA);
            pos(elements[b[edgeIndex]], posB);
        },
        style: function (edgeIndex) {
            var o = _order[edgeIndex];
            var f = mol_util["a" /* BitFlags */].create(_flags[edgeIndex]);
            if (types["BondType"].is(f, 2 /* MetallicCoordination */) || types["BondType"].is(f, 4 /* HydrogenBond */)) {
                // show metall coordinations and hydrogen bonds with dashed cylinders
                return util_link["c" /* LinkStyle */].Dashed;
            }
            else if (o === 2) {
                return util_link["c" /* LinkStyle */].Double;
            }
            else if (o === 3) {
                return util_link["c" /* LinkStyle */].Triple;
            }
            else {
                return util_link["c" /* LinkStyle */].Solid;
            }
        },
        radius: function (edgeIndex) {
            location.element = elements[a[edgeIndex]];
            var sizeA = theme.size.size(location);
            location.element = elements[b[edgeIndex]];
            var sizeB = theme.size.size(location);
            return Math.min(sizeA, sizeB) * sizeFactor * sizeAspectRatio;
        },
        ignore: function (edgeIndex) { return ignoreHydrogen(edgeIndex) || ignoreBondType(include, exclude, _flags[edgeIndex]); }
    };
    var m = Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var IntraUnitBondCylinderParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), BondCylinderParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.3, { min: 0, max: 10, step: 0.01 }), sizeAspectRatio: param_definition["ParamDefinition"].Numeric(2 / 3, { min: 0, max: 3, step: 0.01 }), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function IntraUnitBondCylinderVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(IntraUnitBondCylinderParams),
        createGeometry: createIntraUnitBondCylinderMesh,
        createLocationIterator: bond_BondIterator.fromGroup,
        getLoci: getIntraBondLoci,
        eachLocation: eachIntraBond,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.sizeAspectRatio !== currentProps.sizeAspectRatio ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.linkScale !== currentProps.linkScale ||
                newProps.linkSpacing !== currentProps.linkSpacing ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                newProps.linkCap !== currentProps.linkCap ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.includeTypes, currentProps.includeTypes) ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.excludeTypes, currentProps.excludeTypes));
        }
    }, materialId);
}
//# sourceMappingURL=bond-intra-unit-cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/complex-visual.js
var complex_visual = __webpack_require__(110);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/bond-inter-unit-cylinder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var tmpRefPosBondIt = new mol_model_structure["Bond"].ElementBondIterator();
function setRefPosition(pos, structure, unit, index) {
    tmpRefPosBondIt.setElement(structure, unit, index);
    while (tmpRefPosBondIt.hasNext) {
        var bA = tmpRefPosBondIt.move();
        bA.otherUnit.conformation.position(bA.otherUnit.elements[bA.otherIndex], pos);
        return pos;
    }
    return null;
}
var tmpRef = Object(linear_algebra["Vec3"])();
var tmpLoc = mol_model_structure["StructureElement"].Location.create(void 0);
function createInterUnitBondCylinderMesh(ctx, structure, theme, props, mesh) {
    var bonds = structure.interUnitBonds;
    var edgeCount = bonds.edgeCount, edges = bonds.edges;
    var sizeFactor = props.sizeFactor, sizeAspectRatio = props.sizeAspectRatio, ignoreHydrogens = props.ignoreHydrogens, includeTypes = props.includeTypes, excludeTypes = props.excludeTypes;
    var include = types["BondType"].fromNames(includeTypes);
    var exclude = types["BondType"].fromNames(excludeTypes);
    var ignoreHydrogen = ignoreHydrogens ? function (edgeIndex) {
        var b = edges[edgeIndex];
        var uA = b.unitA, uB = b.unitB;
        return Object(common["k" /* isHydrogen */])(uA, uA.elements[b.indexA]) || Object(common["k" /* isHydrogen */])(uB, uB.elements[b.indexB]);
    } : function () { return false; };
    if (!edgeCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var builderProps = {
        linkCount: edgeCount,
        referencePosition: function (edgeIndex) {
            var b = edges[edgeIndex];
            var unitA, unitB;
            var indexA, indexB;
            if (b.unitA.id < b.unitB.id) {
                unitA = b.unitA, unitB = b.unitB;
                indexA = b.indexA, indexB = b.indexB;
            }
            else if (b.unitA.id > b.unitB.id) {
                unitA = b.unitB, unitB = b.unitA;
                indexA = b.indexB, indexB = b.indexA;
            }
            else {
                throw new Error('same units in createInterUnitBondCylinderMesh');
            }
            return setRefPosition(tmpRef, structure, unitA, indexA) || setRefPosition(tmpRef, structure, unitB, indexB);
        },
        position: function (posA, posB, edgeIndex) {
            var b = edges[edgeIndex];
            var uA = b.unitA, uB = b.unitB;
            uA.conformation.position(uA.elements[b.indexA], posA);
            uB.conformation.position(uB.elements[b.indexB], posB);
        },
        style: function (edgeIndex) {
            var o = edges[edgeIndex].props.order;
            var f = mol_util["a" /* BitFlags */].create(edges[edgeIndex].props.flag);
            if (types["BondType"].is(f, 2 /* MetallicCoordination */) || types["BondType"].is(f, 4 /* HydrogenBond */)) {
                // show metall coordinations and hydrogen bonds with dashed cylinders
                return util_link["c" /* LinkStyle */].Dashed;
            }
            else if (o === 2) {
                return util_link["c" /* LinkStyle */].Double;
            }
            else if (o === 3) {
                return util_link["c" /* LinkStyle */].Triple;
            }
            else {
                return util_link["c" /* LinkStyle */].Solid;
            }
        },
        radius: function (edgeIndex) {
            var b = edges[edgeIndex];
            tmpLoc.structure = structure;
            tmpLoc.unit = b.unitA;
            tmpLoc.element = b.unitA.elements[b.indexA];
            var sizeA = theme.size.size(tmpLoc);
            tmpLoc.unit = b.unitB;
            tmpLoc.element = b.unitB.elements[b.indexB];
            var sizeB = theme.size.size(tmpLoc);
            return Math.min(sizeA, sizeB) * sizeFactor * sizeAspectRatio;
        },
        ignore: function (edgeIndex) { return ignoreHydrogen(edgeIndex) || ignoreBondType(include, exclude, edges[edgeIndex].props.flag); }
    };
    return Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
}
var InterUnitBondCylinderParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["c" /* ComplexMeshParams */]), BondCylinderParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.3, { min: 0, max: 10, step: 0.01 }), sizeAspectRatio: param_definition["ParamDefinition"].Numeric(2 / 3, { min: 0, max: 3, step: 0.01 }), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function InterUnitBondCylinderVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(InterUnitBondCylinderParams),
        createGeometry: createInterUnitBondCylinderMesh,
        createLocationIterator: bond_BondIterator.fromStructure,
        getLoci: getInterBondLoci,
        eachLocation: eachInterBond,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.sizeAspectRatio !== currentProps.sizeAspectRatio ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.linkScale !== currentProps.linkScale ||
                newProps.linkSpacing !== currentProps.linkSpacing ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                newProps.linkCap !== currentProps.linkCap ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.includeTypes, currentProps.includeTypes) ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.excludeTypes, currentProps.excludeTypes));
        }
    }, materialId);
}
//# sourceMappingURL=bond-inter-unit-cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/units-representation.js
var units_representation = __webpack_require__(104);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/complex-representation.js
var complex_representation = __webpack_require__(222);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation.js
var structure_representation = __webpack_require__(54);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/structure/params.js
var structure_params = __webpack_require__(94);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/ball-and-stick.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var BallAndStickVisuals = {
    'element-sphere': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Element sphere mesh', ctx, getParams, getElementSphereVisual(ctx.webgl)); },
    'intra-bond': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Intra-unit bond cylinder', ctx, getParams, IntraUnitBondCylinderVisual); },
    'inter-bond': function (ctx, getParams) { return Object(complex_representation["a" /* ComplexRepresentation */])('Inter-unit bond cylinder', ctx, getParams, InterUnitBondCylinderVisual); },
};
var BallAndStickParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, ElementSphereParams), IntraUnitBondCylinderParams), InterUnitBondCylinderParams), { unitKinds: Object(structure_params["i" /* getUnitKindsParam */])(['atomic']), sizeFactor: param_definition["ParamDefinition"].Numeric(0.15, { min: 0.01, max: 10, step: 0.01 }), sizeAspectRatio: param_definition["ParamDefinition"].Numeric(2 / 3, { min: 0.01, max: 3, step: 0.01 }), visuals: param_definition["ParamDefinition"].MultiSelect(['element-sphere', 'intra-bond', 'inter-bond'], param_definition["ParamDefinition"].objectToOptions(BallAndStickVisuals)) });
function getBallAndStickParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(BallAndStickParams);
}
function BallAndStickRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Ball & Stick', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], BallAndStickVisuals);
}
var BallAndStickRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'ball-and-stick',
    label: 'Ball & Stick',
    description: 'Displays atoms as spheres and bonds as cylinders.',
    factory: BallAndStickRepresentation,
    getParams: getBallAndStickParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(BallAndStickParams),
    defaultColorTheme: { name: 'element-symbol' },
    defaultSizeTheme: { name: 'physical' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=ball-and-stick.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/carbohydrate-link-cylinder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











function createCarbohydrateLinkCylinderMesh(ctx, structure, theme, props, mesh) {
    var _a = structure.carbohydrates, links = _a.links, elements = _a.elements;
    var linkSizeFactor = props.linkSizeFactor;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var builderProps = {
        linkCount: links.length,
        position: function (posA, posB, edgeIndex) {
            var l = links[edgeIndex];
            linear_algebra["Vec3"].copy(posA, elements[l.carbohydrateIndexA].geometry.center);
            linear_algebra["Vec3"].copy(posB, elements[l.carbohydrateIndexB].geometry.center);
        },
        radius: function (edgeIndex) {
            var l = links[edgeIndex];
            var carbA = elements[l.carbohydrateIndexA];
            var ringA = carbA.unit.rings.all[carbA.ringIndex];
            location.unit = carbA.unit;
            location.element = carbA.unit.elements[ringA[0]];
            return theme.size.size(location) * linkSizeFactor;
        },
    };
    return Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
}
var CarbohydrateLinkParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), util_link["a" /* LinkCylinderParams */]), { linkSizeFactor: param_definition["ParamDefinition"].Numeric(0.3, { min: 0, max: 3, step: 0.01 }) });
function CarbohydrateLinkVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(CarbohydrateLinkParams),
        createGeometry: createCarbohydrateLinkCylinderMesh,
        createLocationIterator: CarbohydrateLinkIterator,
        getLoci: getLinkLoci,
        eachLocation: eachCarbohydrateLink,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.linkSizeFactor !== currentProps.linkSizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.linkCap !== currentProps.linkCap);
        }
    }, materialId);
}
function CarbohydrateLinkIterator(structure) {
    var _a = structure.carbohydrates, elements = _a.elements, links = _a.links;
    var groupCount = links.length;
    var instanceCount = 1;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var getLocation = function (groupIndex) {
        var link = links[groupIndex];
        var carbA = elements[link.carbohydrateIndexA];
        var ringA = carbA.unit.rings.all[carbA.ringIndex];
        location.unit = carbA.unit;
        location.element = carbA.unit.elements[ringA[0]];
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
}
function getLinkLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var _a = structure.carbohydrates, links = _a.links, elements = _a.elements;
        var l = links[groupId];
        var carbA = elements[l.carbohydrateIndexA];
        var carbB = elements[l.carbohydrateIndexB];
        return mol_model_structure["StructureElement"].Loci.union(Object(common["f" /* getAltResidueLociFromId */])(structure, carbA.unit, carbA.residueIndex, carbA.altId), Object(common["f" /* getAltResidueLociFromId */])(structure, carbB.unit, carbB.residueIndex, carbB.altId));
    }
    return mol_model_loci["EmptyLoci"];
}
function eachCarbohydrateLink(loci, structure, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var getLinkIndices = structure.carbohydrates.getLinkIndices;
    var _loop_1 = function (unit, indices) {
        if (!mol_model_structure["Unit"].isAtomic(unit))
            return "continue";
        mol_data_int["OrderedSet"].forEach(indices, function (v) {
            // TODO avoid duplicate calls to apply
            var linkIndices = getLinkIndices(unit, unit.elements[v]);
            for (var i = 0, il = linkIndices.length; i < il; ++i) {
                if (apply(mol_data_int["Interval"].ofSingleton(linkIndices[i])))
                    changed = true;
            }
        });
    };
    for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
        var _b = _a[_i], unit = _b.unit, indices = _b.indices;
        _loop_1(unit, indices);
    }
    return changed;
}
//# sourceMappingURL=carbohydrate-link-cylinder.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/box.js
var primitive_box = __webpack_require__(242);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/primitive.js
var primitive = __webpack_require__(127);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/polygon.js
var polygon = __webpack_require__(149);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/pyramid.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var on = linear_algebra["Vec3"].create(0, 0, -0.5), op = linear_algebra["Vec3"].create(0, 0, 0.5);
var pyramid_a = linear_algebra["Vec3"].zero(), pyramid_b = linear_algebra["Vec3"].zero(), pyramid_c = linear_algebra["Vec3"].zero(), pyramid_d = linear_algebra["Vec3"].zero();
/**
 * Create a pyramid with a polygonal base
 */
function Pyramid(points) {
    var sideCount = points.length / 3;
    var baseCount = sideCount === 3 ? 1 : sideCount === 4 ? 2 : sideCount;
    var count = 2 * baseCount + 2 * sideCount;
    var builder = Object(primitive["a" /* PrimitiveBuilder */])(count);
    // create sides
    for (var i = 0; i < sideCount; ++i) {
        var ni = (i + 1) % sideCount;
        linear_algebra["Vec3"].set(pyramid_a, points[i * 3], points[i * 3 + 1], -0.5);
        linear_algebra["Vec3"].set(pyramid_b, points[ni * 3], points[ni * 3 + 1], -0.5);
        builder.add(pyramid_a, pyramid_b, op);
    }
    // create base
    if (sideCount === 3) {
        linear_algebra["Vec3"].set(pyramid_a, points[0], points[1], -0.5);
        linear_algebra["Vec3"].set(pyramid_b, points[3], points[4], -0.5);
        linear_algebra["Vec3"].set(pyramid_c, points[6], points[7], -0.5);
        builder.add(pyramid_c, pyramid_b, pyramid_a);
    }
    else if (sideCount === 4) {
        linear_algebra["Vec3"].set(pyramid_a, points[0], points[1], -0.5);
        linear_algebra["Vec3"].set(pyramid_b, points[3], points[4], -0.5);
        linear_algebra["Vec3"].set(pyramid_c, points[6], points[7], -0.5);
        linear_algebra["Vec3"].set(pyramid_d, points[9], points[10], -0.5);
        builder.add(pyramid_c, pyramid_b, pyramid_a);
        builder.add(pyramid_a, pyramid_d, pyramid_c);
    }
    else {
        for (var i = 0; i < sideCount; ++i) {
            var ni = (i + 1) % sideCount;
            linear_algebra["Vec3"].set(pyramid_a, points[i * 3], points[i * 3 + 1], -0.5);
            linear_algebra["Vec3"].set(pyramid_b, points[ni * 3], points[ni * 3 + 1], -0.5);
            builder.add(on, pyramid_b, pyramid_a);
        }
    }
    return builder.getPrimitive();
}
var triangularPyramid;
function TriangularPyramid() {
    if (!triangularPyramid)
        triangularPyramid = Pyramid(Object(polygon["a" /* polygon */])(3, true));
    return triangularPyramid;
}
var octagonalPyramid;
function OctagonalPyramid() {
    if (!octagonalPyramid)
        octagonalPyramid = Pyramid(Object(polygon["a" /* polygon */])(8, true));
    return octagonalPyramid;
}
var perforatedOctagonalPyramid;
function PerforatedOctagonalPyramid() {
    if (!perforatedOctagonalPyramid) {
        var points = Object(polygon["a" /* polygon */])(8, true);
        var vertices = new Float32Array(8 * 3 + 6);
        for (var i = 0; i < 8; ++i) {
            vertices[i * 3] = points[i * 3];
            vertices[i * 3 + 1] = points[i * 3 + 1];
            vertices[i * 3 + 2] = -0.5;
        }
        vertices[8 * 3] = 0;
        vertices[8 * 3 + 1] = 0;
        vertices[8 * 3 + 2] = -0.5;
        vertices[8 * 3 + 3] = 0;
        vertices[8 * 3 + 4] = 0;
        vertices[8 * 3 + 5] = 0.5;
        var indices = [
            0, 1, 8, 1, 2, 8, 4, 5, 8, 5, 6, 8,
            2, 3, 9, 3, 4, 9, 6, 7, 9, 7, 0, 9
        ];
        perforatedOctagonalPyramid = Object(primitive["b" /* createPrimitive */])(vertices, indices);
    }
    return perforatedOctagonalPyramid;
}
//
/**
 * Create a prism cage
 */
function PyramidCage(points) {
    var sideCount = points.length / 3;
    // const count = 4 * sideCount
    var vertices = [];
    var edges = [];
    var offset = 1;
    vertices.push(op[0], op[1], op[2]);
    // vertices and side edges
    for (var i = 0; i < sideCount; ++i) {
        vertices.push(points[i * 3], points[i * 3 + 1], -0.5);
        edges.push(0, offset);
        offset += 1;
    }
    // bases edges
    for (var i = 0; i < sideCount; ++i) {
        var ni = (i + 1) % sideCount;
        edges.push(i + 1, ni + 1);
    }
    return { vertices: vertices, edges: edges };
}
var octagonalPyramidCage;
function OctagonalPyramidCage() {
    if (!octagonalPyramidCage)
        octagonalPyramidCage = PyramidCage(Object(polygon["a" /* polygon */])(8, true));
    return octagonalPyramidCage;
}
//# sourceMappingURL=pyramid.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/star.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



var DefaultStarProps = {
    pointCount: 5,
    outerRadius: 1,
    innerRadius: 0.5,
    thickness: 0.3
};
var star_op = linear_algebra["Vec3"].zero(), star_on = linear_algebra["Vec3"].zero();
var star_a = linear_algebra["Vec3"].zero(), star_b = linear_algebra["Vec3"].zero(), star_c = linear_algebra["Vec3"].zero();
function Star(props) {
    var _a = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultStarProps), props), outerRadius = _a.outerRadius, innerRadius = _a.innerRadius, thickness = _a.thickness, pointCount = _a.pointCount;
    var triangleCount = pointCount * 2 * 2;
    var builder = Object(primitive["a" /* PrimitiveBuilder */])(triangleCount);
    var innerPoints = new Float32Array(pointCount * 2);
    var outerPoints = new Float32Array(pointCount * 2);
    for (var i = 0; i < pointCount; ++i) {
        var io = i * 2, ii = i * 2 + 1;
        var co = (io + 1) / pointCount * Math.PI, ci = (ii + 1) / pointCount * Math.PI;
        outerPoints[io] = Math.cos(co) * outerRadius;
        outerPoints[ii] = Math.sin(co) * outerRadius;
        innerPoints[io] = Math.cos(ci) * innerRadius;
        innerPoints[ii] = Math.sin(ci) * innerRadius;
    }
    linear_algebra["Vec3"].set(star_op, 0, 0, thickness / 2);
    linear_algebra["Vec3"].set(star_on, 0, 0, -thickness / 2);
    for (var i = 0; i < pointCount; ++i) {
        var ni = (i + 1) % pointCount;
        linear_algebra["Vec3"].set(star_a, outerPoints[i * 2], outerPoints[i * 2 + 1], 0);
        linear_algebra["Vec3"].set(star_b, innerPoints[i * 2], innerPoints[i * 2 + 1], 0);
        linear_algebra["Vec3"].set(star_c, outerPoints[ni * 2], outerPoints[ni * 2 + 1], 0);
        builder.add(star_op, star_a, star_b);
        builder.add(star_b, star_a, star_on);
        builder.add(star_op, star_b, star_c);
        builder.add(star_c, star_b, star_on);
    }
    return builder.getPrimitive();
}
//# sourceMappingURL=star.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/cage.js
var cage = __webpack_require__(184);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/octahedron.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var octahedronVertices = [
    0.5, 0, 0, -0.5, 0, 0, 0, 0.5, 0,
    0, -0.5, 0, 0, 0, 0.5, 0, 0, -0.5
];
var octahedronIndices = [
    0, 2, 4, 0, 4, 3, 0, 3, 5,
    0, 5, 2, 1, 2, 5, 1, 5, 3,
    1, 3, 4, 1, 4, 2
];
var perforatedOctahedronIndices = [
    0, 2, 4, 0, 4, 3,
    // 0, 3, 5,   0, 5, 2,
    1, 2, 5, 1, 5, 3,
];
var octahedronEdges = [
    0, 2, 1, 3, 2, 1, 3, 0,
    0, 4, 1, 4, 2, 4, 3, 4,
    0, 5, 1, 5, 2, 5, 3, 5,
];
var octahedron;
function Octahedron() {
    if (!octahedron)
        octahedron = Object(primitive["b" /* createPrimitive */])(octahedronVertices, octahedronIndices);
    return octahedron;
}
var perforatedOctahedron;
function PerforatedOctahedron() {
    if (!perforatedOctahedron)
        perforatedOctahedron = Object(primitive["b" /* createPrimitive */])(octahedronVertices, perforatedOctahedronIndices);
    return perforatedOctahedron;
}
var octahedronCage = Object(cage["b" /* createCage */])(octahedronVertices, octahedronEdges);
function OctahedronCage() {
    return octahedronCage;
}
//# sourceMappingURL=octahedron.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/primitive/prism.js
var prism = __webpack_require__(234);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/carbohydrates/constants.js
var constants = __webpack_require__(178);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/carbohydrate-symbol-mesh.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


















var carbohydrate_symbol_mesh_t = linear_algebra["Mat4"].identity();
var sVec = linear_algebra["Vec3"].zero();
var carbohydrate_symbol_mesh_pd = linear_algebra["Vec3"].zero();
var SideFactor = 2 * 0.806; // 0.806 == Math.cos(Math.PI / 4)
var carbohydrate_symbol_mesh_box = Object(primitive_box["a" /* Box */])();
var perforatedBox = Object(primitive_box["c" /* PerforatedBox */])();
var carbohydrate_symbol_mesh_octagonalPyramid = OctagonalPyramid();
var carbohydrate_symbol_mesh_perforatedOctagonalPyramid = PerforatedOctagonalPyramid();
var star = Star({ outerRadius: 1, innerRadius: 0.5, thickness: 0.5, pointCount: 5 });
var carbohydrate_symbol_mesh_octahedron = Octahedron();
var carbohydrate_symbol_mesh_perforatedOctahedron = PerforatedOctahedron();
var diamondPrism = Object(prism["a" /* DiamondPrism */])();
var pentagonalPrism = Object(prism["d" /* PentagonalPrism */])();
var hexagonalPrism = Object(prism["c" /* HexagonalPrism */])();
var shiftedHexagonalPrism = Object(prism["g" /* ShiftedHexagonalPrism */])();
var heptagonalPrism = Object(prism["b" /* HeptagonalPrism */])();
function createCarbohydrateSymbolMesh(ctx, structure, theme, props, mesh) {
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(256, 128, mesh);
    var detail = props.detail, sizeFactor = props.sizeFactor;
    var carbohydrates = structure.carbohydrates;
    var n = carbohydrates.elements.length;
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    for (var i = 0; i < n; ++i) {
        var c = carbohydrates.elements[i];
        var ring = c.unit.rings.all[c.ringIndex];
        var shapeType = Object(constants["f" /* getSaccharideShape */])(c.component.type, ring.length);
        l.unit = c.unit;
        l.element = c.unit.elements[ring[0]];
        var size = theme.size.size(l);
        var radius = size * sizeFactor;
        var side = size * sizeFactor * SideFactor;
        var _a = c.geometry, center = _a.center, normal = _a.normal, direction = _a.direction;
        linear_algebra["Vec3"].add(carbohydrate_symbol_mesh_pd, center, direction);
        linear_algebra["Mat4"].targetTo(carbohydrate_symbol_mesh_t, center, carbohydrate_symbol_mesh_pd, normal);
        linear_algebra["Mat4"].setTranslation(carbohydrate_symbol_mesh_t, center);
        builderState.currentGroup = i * 2;
        switch (shapeType) {
            case 0 /* FilledSphere */:
                Object(builder_sphere["a" /* addSphere */])(builderState, center, radius, detail);
                break;
            case 1 /* FilledCube */:
                linear_algebra["Mat4"].scaleUniformly(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, side);
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_box);
                break;
            case 2 /* CrossedCube */:
                linear_algebra["Mat4"].scaleUniformly(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, side);
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, perforatedBox);
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZ90X180);
                builderState.currentGroup += 1;
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, perforatedBox);
                break;
            case 4 /* FilledCone */:
                linear_algebra["Mat4"].scaleUniformly(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, side * 1.2);
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_octagonalPyramid);
                break;
            case 5 /* DevidedCone */:
                linear_algebra["Mat4"].scaleUniformly(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, side * 1.2);
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_perforatedOctagonalPyramid);
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZ90);
                builderState.currentGroup += 1;
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_perforatedOctagonalPyramid);
                break;
            case 6 /* FlatBox */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_box);
                break;
            case 7 /* FilledStar */:
                linear_algebra["Mat4"].scaleUniformly(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, side);
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, star);
                break;
            case 8 /* FilledDiamond */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side * 1.4, side * 1.4, side * 1.4));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_octahedron);
                break;
            case 3 /* DividedDiamond */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side * 1.4, side * 1.4, side * 1.4));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_perforatedOctahedron);
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotY90);
                builderState.currentGroup += 1;
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_perforatedOctahedron);
                break;
            case 9 /* FlatDiamond */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side / 2, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, diamondPrism);
                break;
            case 12 /* DiamondPrism */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, diamondPrism);
                break;
            case 13 /* PentagonalPrism */:
            case 11 /* Pentagon */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, pentagonalPrism);
                break;
            case 14 /* HexagonalPrism */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, hexagonalPrism);
                break;
            case 15 /* HeptagonalPrism */:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZY90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, heptagonalPrism);
                break;
            case 10 /* FlatHexagon */:
            default:
                linear_algebra["Mat4"].mul(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Mat4"].rotZYZ90);
                linear_algebra["Mat4"].scale(carbohydrate_symbol_mesh_t, carbohydrate_symbol_mesh_t, linear_algebra["Vec3"].set(sVec, side / 1.5, side, side / 2));
                mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, carbohydrate_symbol_mesh_t, shiftedHexagonalPrism);
                break;
        }
    }
    return mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
}
var CarbohydrateSymbolParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["c" /* ComplexMeshParams */]), { detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo), sizeFactor: param_definition["ParamDefinition"].Numeric(1.75, { min: 0, max: 10, step: 0.01 }) });
function CarbohydrateSymbolVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(CarbohydrateSymbolParams),
        createGeometry: createCarbohydrateSymbolMesh,
        createLocationIterator: CarbohydrateElementIterator,
        getLoci: getCarbohydrateLoci,
        eachLocation: eachCarbohydrate,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail);
        }
    }, materialId);
}
function CarbohydrateElementIterator(structure) {
    var carbElements = structure.carbohydrates.elements;
    var groupCount = carbElements.length * 2;
    var instanceCount = 1;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    function getLocation(groupIndex, instanceIndex) {
        var carb = carbElements[Math.floor(groupIndex / 2)];
        var ring = carb.unit.rings.all[carb.ringIndex];
        location.unit = carb.unit;
        location.element = carb.unit.elements[ring[0]];
        return location;
    }
    function isSecondary(elementIndex, instanceIndex) {
        return (elementIndex % 2) === 1;
    }
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true, isSecondary);
}
/** Return a Loci for the elements of the whole residue of a carbohydrate. */
function getCarbohydrateLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var carb = structure.carbohydrates.elements[Math.floor(groupId / 2)];
        return Object(common["f" /* getAltResidueLociFromId */])(structure, carb.unit, carb.residueIndex, carb.altId);
    }
    return mol_model_loci["EmptyLoci"];
}
/** For each carbohydrate (usually a monosaccharide) when all its residue's elements are in a loci. */
function eachCarbohydrate(loci, structure, apply) {
    var getElementIndices = structure.carbohydrates.getElementIndices;
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var _loop_1 = function (unit, indices) {
        if (!mol_model_structure["Unit"].isAtomic(unit))
            return "continue";
        mol_data_int["OrderedSet"].forEach(indices, function (v) {
            // TODO avoid duplicate calls to apply
            var elementIndices = getElementIndices(unit, unit.elements[v]);
            for (var i = 0, il = elementIndices.length; i < il; ++i) {
                if (apply(mol_data_int["Interval"].ofSingleton(elementIndices[i] * 2)))
                    changed = true;
            }
        });
    };
    for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
        var _b = _a[_i], unit = _b.unit, indices = _b.indices;
        _loop_1(unit, indices);
    }
    return changed;
}
//# sourceMappingURL=carbohydrate-symbol-mesh.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure/structure/unit/bonds/common.js
var bonds_common = __webpack_require__(109);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/carbohydrate-terminal-link-cylinder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function createCarbohydrateTerminalLinkCylinderMesh(ctx, structure, theme, props, mesh) {
    var _a = structure.carbohydrates, terminalLinks = _a.terminalLinks, elements = _a.elements;
    var terminalLinkSizeFactor = props.terminalLinkSizeFactor;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var builderProps = {
        linkCount: terminalLinks.length,
        position: function (posA, posB, edgeIndex) {
            var l = terminalLinks[edgeIndex];
            if (l.fromCarbohydrate) {
                linear_algebra["Vec3"].copy(posA, elements[l.carbohydrateIndex].geometry.center);
                l.elementUnit.conformation.position(l.elementUnit.elements[l.elementIndex], posB);
            }
            else {
                l.elementUnit.conformation.position(l.elementUnit.elements[l.elementIndex], posA);
                linear_algebra["Vec3"].copy(posB, elements[l.carbohydrateIndex].geometry.center);
            }
        },
        radius: function (edgeIndex) {
            var l = terminalLinks[edgeIndex];
            if (l.fromCarbohydrate) {
                var carb = elements[l.carbohydrateIndex];
                var ring = carb.unit.rings.all[carb.ringIndex];
                location.unit = carb.unit;
                location.element = carb.unit.elements[ring[0]];
            }
            else {
                location.unit = l.elementUnit;
                location.element = l.elementUnit.elements[l.elementIndex];
            }
            return theme.size.size(location) * terminalLinkSizeFactor;
        },
        style: function (edgeIndex) {
            var l = terminalLinks[edgeIndex];
            var eI = l.elementUnit.elements[l.elementIndex];
            var beI = Object(bonds_common["c" /* getElementIdx */])(l.elementUnit.model.atomicHierarchy.atoms.type_symbol.value(eI));
            return bonds_common["b" /* MetalsSet */].has(beI) ? util_link["c" /* LinkStyle */].Dashed : util_link["c" /* LinkStyle */].Solid;
        }
    };
    return Object(util_link["d" /* createLinkCylinderMesh */])(ctx, builderProps, props, mesh);
}
var CarbohydrateTerminalLinkParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), util_link["a" /* LinkCylinderParams */]), { terminalLinkSizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 3, step: 0.01 }) });
function CarbohydrateTerminalLinkVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(CarbohydrateTerminalLinkParams),
        createGeometry: createCarbohydrateTerminalLinkCylinderMesh,
        createLocationIterator: CarbohydrateTerminalLinkIterator,
        getLoci: getTerminalLinkLoci,
        eachLocation: eachTerminalLink,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.terminalLinkSizeFactor !== currentProps.terminalLinkSizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.linkCap !== currentProps.linkCap);
        }
    }, materialId);
}
function CarbohydrateTerminalLinkIterator(structure) {
    var _a = structure.carbohydrates, elements = _a.elements, terminalLinks = _a.terminalLinks;
    var groupCount = terminalLinks.length;
    var instanceCount = 1;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var getLocation = function (groupIndex) {
        var terminalLink = terminalLinks[groupIndex];
        if (terminalLink.fromCarbohydrate) {
            var carb = elements[terminalLink.carbohydrateIndex];
            var ring = carb.unit.rings.all[carb.ringIndex];
            location.unit = carb.unit;
            location.element = carb.unit.elements[ring[0]];
        }
        else {
            location.unit = terminalLink.elementUnit;
            location.element = terminalLink.elementUnit.elements[terminalLink.elementIndex];
        }
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation, true);
}
function getTerminalLinkLoci(pickingId, structure, id) {
    var objectId = pickingId.objectId, groupId = pickingId.groupId;
    if (id === objectId) {
        var _a = structure.carbohydrates, terminalLinks = _a.terminalLinks, elements = _a.elements;
        var l = terminalLinks[groupId];
        var carb = elements[l.carbohydrateIndex];
        return mol_model_structure["StructureElement"].Loci.union(Object(common["f" /* getAltResidueLociFromId */])(structure, carb.unit, carb.residueIndex, carb.altId), Object(common["e" /* getAltResidueLoci */])(structure, l.elementUnit, l.elementUnit.elements[l.elementIndex]));
    }
    return mol_model_loci["EmptyLoci"];
}
function eachTerminalLink(loci, structure, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var getTerminalLinkIndices = structure.carbohydrates.getTerminalLinkIndices;
    var _loop_1 = function (unit, indices) {
        if (!mol_model_structure["Unit"].isAtomic(unit))
            return "continue";
        mol_data_int["OrderedSet"].forEach(indices, function (v) {
            // TODO avoid duplicate calls to apply
            var linkIndices = getTerminalLinkIndices(unit, unit.elements[v]);
            for (var i = 0, il = linkIndices.length; i < il; ++i) {
                if (apply(mol_data_int["Interval"].ofSingleton(linkIndices[i])))
                    changed = true;
            }
        });
    };
    for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
        var _b = _a[_i], unit = _b.unit, indices = _b.indices;
        _loop_1(unit, indices);
    }
    return changed;
}
//# sourceMappingURL=carbohydrate-terminal-link-cylinder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/carbohydrate.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var CarbohydrateVisuals = {
    'carbohydrate-symbol': function (ctx, getParams) { return Object(complex_representation["a" /* ComplexRepresentation */])('Carbohydrate symbol mesh', ctx, getParams, CarbohydrateSymbolVisual); },
    'carbohydrate-link': function (ctx, getParams) { return Object(complex_representation["a" /* ComplexRepresentation */])('Carbohydrate link cylinder', ctx, getParams, CarbohydrateLinkVisual); },
    'carbohydrate-terminal-link': function (ctx, getParams) { return Object(complex_representation["a" /* ComplexRepresentation */])('Carbohydrate terminal link cylinder', ctx, getParams, CarbohydrateTerminalLinkVisual); },
};
var CarbohydrateParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, CarbohydrateSymbolParams), CarbohydrateLinkParams), CarbohydrateTerminalLinkParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['carbohydrate-symbol', 'carbohydrate-link', 'carbohydrate-terminal-link'], param_definition["ParamDefinition"].objectToOptions(CarbohydrateVisuals)) });
function getCarbohydrateParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(CarbohydrateParams);
}
function CarbohydrateRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Carbohydrate', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], CarbohydrateVisuals);
}
var CarbohydrateRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'carbohydrate',
    label: 'Carbohydrate',
    description: 'Displays carbohydrate symbols (3D SNFG).',
    factory: CarbohydrateRepresentation,
    getParams: getCarbohydrateParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(CarbohydrateParams),
    defaultColorTheme: { name: 'carbohydrate-symbol' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) {
        return structure.models.some(function (m) { return mol_model_structure["Model"].hasCarbohydrate(m); });
    }
});
//# sourceMappingURL=carbohydrate.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/cylinder.js + 1 modules
var cylinder = __webpack_require__(81);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int/sorted-ranges.js
var sorted_ranges = __webpack_require__(79);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/polymer/backbone-iterator.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




/** Iterates over consecutive pairs of residues/coarse elements in polymers */
function PolymerBackboneIterator(structure, unit) {
    switch (unit.kind) {
        case 0 /* Atomic */: return new backbone_iterator_AtomicPolymerBackboneIterator(structure, unit);
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            return new backbone_iterator_CoarsePolymerBackboneIterator(structure, unit);
    }
}
function createPolymerBackbonePair(structure, unit) {
    return {
        centerA: mol_model_structure["StructureElement"].Location.create(structure, unit),
        centerB: mol_model_structure["StructureElement"].Location.create(structure, unit),
    };
}
var backbone_iterator_AtomicPolymerBackboneIterator = /** @class */ (function () {
    function AtomicPolymerBackboneIterator(structure, unit) {
        this.unit = unit;
        this.state = 0 /* nextPolymer */;
        this.hasNext = false;
        this.traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex; // can assume it won't be -1 for polymer residues
        this.polymerIt = sorted_ranges["a" /* default */].transientSegments(getPolymerRanges(unit), unit.elements);
        this.residueIt = mol_data_int["Segmentation"].transientSegments(unit.model.atomicHierarchy.residueAtomSegments, unit.elements);
        this.value = createPolymerBackbonePair(structure, unit);
        this.hasNext = this.residueIt.hasNext && this.polymerIt.hasNext;
    }
    AtomicPolymerBackboneIterator.prototype.move = function () {
        if (this.state === 0 /* nextPolymer */) {
            while (this.polymerIt.hasNext) {
                this.residueIt.setSegment(this.polymerIt.move());
                if (this.residueIt.hasNext) {
                    this.residueSegment = this.residueIt.move();
                    this.value.centerB.element = this.traceElementIndex[this.residueSegment.index];
                    this.state = 2 /* nextResidue */;
                    break;
                }
            }
        }
        if (this.state === 2 /* nextResidue */) {
            this.residueSegment = this.residueIt.move();
            this.value.centerA.element = this.value.centerB.element;
            this.value.centerB.element = this.traceElementIndex[this.residueSegment.index];
            if (!this.residueIt.hasNext) {
                if (this.unit.model.atomicRanges.cyclicPolymerMap.has(this.residueSegment.index)) {
                    this.state = 3 /* cycle */;
                }
                else {
                    // TODO need to advance to a polymer that has two or more residues (can't assume it has)
                    this.state = 0 /* nextPolymer */;
                }
            }
        }
        else if (this.state === 3 /* cycle */) {
            var cyclicPolymerMap = this.unit.model.atomicRanges.cyclicPolymerMap;
            this.value.centerA.element = this.value.centerB.element;
            this.value.centerB.element = this.traceElementIndex[cyclicPolymerMap.get(this.residueSegment.index)];
            // TODO need to advance to a polymer that has two or more residues (can't assume it has)
            this.state = 0 /* nextPolymer */;
        }
        this.hasNext = this.residueIt.hasNext || this.polymerIt.hasNext || this.state === 3 /* cycle */;
        return this.value;
    };
    return AtomicPolymerBackboneIterator;
}());

var backbone_iterator_CoarsePolymerBackboneIterator = /** @class */ (function () {
    function CoarsePolymerBackboneIterator(structure, unit) {
        this.unit = unit;
        this.state = 0 /* nextPolymer */;
        this.hasNext = false;
        this.polymerIt = sorted_ranges["a" /* default */].transientSegments(getPolymerRanges(unit), unit.elements);
        this.value = createPolymerBackbonePair(structure, unit);
        this.hasNext = this.polymerIt.hasNext;
    }
    CoarsePolymerBackboneIterator.prototype.move = function () {
        if (this.state === 0 /* nextPolymer */) {
            if (this.polymerIt.hasNext) {
                this.polymerSegment = this.polymerIt.move();
                this.elementIndex = this.polymerSegment.start;
                if (this.elementIndex + 1 < this.polymerSegment.end) {
                    this.value.centerB.element = this.unit.elements[this.elementIndex];
                    this.state = 1 /* nextElement */;
                }
                else {
                    this.state = 0 /* nextPolymer */;
                }
            }
        }
        if (this.state === 1 /* nextElement */) {
            this.elementIndex += 1;
            this.value.centerA.element = this.value.centerB.element;
            this.value.centerB.element = this.unit.elements[this.elementIndex];
            if (this.elementIndex + 1 >= this.polymerSegment.end) {
                this.state = 0 /* nextPolymer */;
            }
        }
        this.hasNext = this.elementIndex + 1 < this.polymerSegment.end || this.polymerIt.hasNext;
        return this.value;
    };
    return CoarsePolymerBackboneIterator;
}());

//# sourceMappingURL=backbone-iterator.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/polymer/gap-iterator.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



/** Iterates over gaps, i.e. the stem residues/coarse elements adjacent to gaps */
function PolymerGapIterator(structure, unit) {
    switch (unit.kind) {
        case 0 /* Atomic */: return new gap_iterator_AtomicPolymerGapIterator(structure, unit);
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            return new gap_iterator_CoarsePolymerGapIterator(structure, unit);
    }
}
function createPolymerGapPair(structure, unit) {
    return {
        centerA: mol_model_structure["StructureElement"].Location.create(structure, unit),
        centerB: mol_model_structure["StructureElement"].Location.create(structure, unit),
    };
}
var gap_iterator_AtomicPolymerGapIterator = /** @class */ (function () {
    function AtomicPolymerGapIterator(structure, unit) {
        this.unit = unit;
        this.hasNext = false;
        this.traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex; // can assume it won't be -1 for polymer residues
        this.gapIt = sorted_ranges["a" /* default */].transientSegments(getGapRanges(unit), unit.elements);
        this.value = createPolymerGapPair(structure, unit);
        this.hasNext = this.gapIt.hasNext;
    }
    AtomicPolymerGapIterator.prototype.move = function () {
        var _a = this.unit, elements = _a.elements, residueIndex = _a.residueIndex;
        var gapSegment = this.gapIt.move();
        this.value.centerA.element = this.traceElementIndex[residueIndex[elements[gapSegment.start]]];
        this.value.centerB.element = this.traceElementIndex[residueIndex[elements[gapSegment.end - 1]]];
        this.hasNext = this.gapIt.hasNext;
        return this.value;
    };
    return AtomicPolymerGapIterator;
}());

var gap_iterator_CoarsePolymerGapIterator = /** @class */ (function () {
    function CoarsePolymerGapIterator(structure, unit) {
        this.unit = unit;
        this.hasNext = false;
        this.gapIt = sorted_ranges["a" /* default */].transientSegments(getGapRanges(unit), unit.elements);
        this.value = createPolymerGapPair(structure, unit);
        this.hasNext = this.gapIt.hasNext;
    }
    CoarsePolymerGapIterator.prototype.move = function () {
        var gapSegment = this.gapIt.move();
        this.value.centerA.element = this.unit.elements[gapSegment.start];
        this.value.centerB.element = this.unit.elements[gapSegment.end - 1];
        this.hasNext = this.gapIt.hasNext;
        return this.value;
    };
    return CoarsePolymerGapIterator;
}());

//# sourceMappingURL=gap-iterator.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/computed/secondary-structure.js + 12 modules
var secondary_structure = __webpack_require__(152);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/polymer/trace-iterator.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







/**
 * Iterates over individual residues/coarse elements in polymers of a unit while
 * providing information about the neighbourhood in the underlying model for drawing splines
 */
function PolymerTraceIterator(unit, structure) {
    switch (unit.kind) {
        case 0 /* Atomic */: return new trace_iterator_AtomicPolymerTraceIterator(unit, structure);
        case 1 /* Spheres */:
        case 2 /* Gaussians */:
            return new trace_iterator_CoarsePolymerTraceIterator(unit, structure);
    }
}
var SecStrucTypeNA = types["SecondaryStructureType"].create(536870912 /* NA */);
function createPolymerTraceElement(structure, unit) {
    return {
        center: mol_model_structure["StructureElement"].Location.create(structure, unit),
        centerPrev: mol_model_structure["StructureElement"].Location.create(structure, unit),
        centerNext: mol_model_structure["StructureElement"].Location.create(structure, unit),
        first: false, last: false,
        initial: false, final: false,
        secStrucFirst: false, secStrucLast: false,
        secStrucType: SecStrucTypeNA,
        moleculeType: 0 /* Unknown */,
        coarseBackboneFirst: false, coarseBackboneLast: false,
        isCoarseBackbone: false,
        p0: Object(linear_algebra["Vec3"])(), p1: Object(linear_algebra["Vec3"])(), p2: Object(linear_algebra["Vec3"])(), p3: Object(linear_algebra["Vec3"])(), p4: Object(linear_algebra["Vec3"])(),
        d12: Object(linear_algebra["Vec3"])(), d23: Object(linear_algebra["Vec3"])()
    };
}
var tmpDir = Object(linear_algebra["Vec3"])();
var tmpVecA = Object(linear_algebra["Vec3"])();
var tmpVecB = Object(linear_algebra["Vec3"])();
var trace_iterator_AtomicPolymerTraceIterator = /** @class */ (function () {
    function AtomicPolymerTraceIterator(unit, structure) {
        var _a;
        this.unit = unit;
        this.state = 0 /* nextPolymer */;
        this.p0 = Object(linear_algebra["Vec3"])();
        this.p1 = Object(linear_algebra["Vec3"])();
        this.p2 = Object(linear_algebra["Vec3"])();
        this.p3 = Object(linear_algebra["Vec3"])();
        this.p4 = Object(linear_algebra["Vec3"])();
        this.p5 = Object(linear_algebra["Vec3"])();
        this.p6 = Object(linear_algebra["Vec3"])();
        this.d01 = Object(linear_algebra["Vec3"])();
        this.d12 = Object(linear_algebra["Vec3"])();
        this.d23 = Object(linear_algebra["Vec3"])();
        this.d34 = Object(linear_algebra["Vec3"])();
        this.hasNext = false;
        this.atomicConformation = unit.model.atomicConformation;
        this.residueAtomSegments = unit.model.atomicHierarchy.residueAtomSegments;
        this.polymerRanges = unit.model.atomicRanges.polymerRanges;
        this.traceElementIndex = unit.model.atomicHierarchy.derived.residue.traceElementIndex; // can assume it won't be -1 for polymer residues
        this.directionFromElementIndex = unit.model.atomicHierarchy.derived.residue.directionFromElementIndex;
        this.directionToElementIndex = unit.model.atomicHierarchy.derived.residue.directionToElementIndex;
        this.moleculeType = unit.model.atomicHierarchy.derived.residue.moleculeType;
        this.cyclicPolymerMap = unit.model.atomicRanges.cyclicPolymerMap;
        this.polymerIt = sorted_ranges["a" /* default */].transientSegments(this.polymerRanges, unit.elements);
        this.residueIt = mol_data_int["Segmentation"].transientSegments(this.residueAtomSegments, unit.elements);
        this.value = createPolymerTraceElement(structure, unit);
        this.hasNext = this.residueIt.hasNext && this.polymerIt.hasNext;
        var secondaryStructure = (_a = secondary_structure["a" /* SecondaryStructureProvider */].get(structure).value) === null || _a === void 0 ? void 0 : _a.get(unit.invariantId);
        if (!secondaryStructure)
            throw new Error('missing secondary structure');
        this.secondaryStructureType = secondaryStructure.type;
        this.secondaryStructureGetIndex = secondaryStructure.getIndex;
    }
    AtomicPolymerTraceIterator.prototype.pos = function (target, index) {
        if (index !== -1) {
            target[0] = this.atomicConformation.x[index];
            target[1] = this.atomicConformation.y[index];
            target[2] = this.atomicConformation.z[index];
        }
    };
    AtomicPolymerTraceIterator.prototype.updateResidueSegmentRange = function (polymerSegment) {
        var index = this.residueAtomSegments.index;
        this.residueSegmentMin = index[this.polymerRanges[polymerSegment.index * 2]];
        this.residueSegmentMax = index[this.polymerRanges[polymerSegment.index * 2 + 1]];
    };
    AtomicPolymerTraceIterator.prototype.getResidueIndex = function (residueIndex) {
        if (residueIndex < this.residueSegmentMin) {
            var cyclicIndex = this.cyclicPolymerMap.get(this.residueSegmentMin);
            if (cyclicIndex !== undefined) {
                residueIndex = cyclicIndex - (this.residueSegmentMin - residueIndex - 1);
            }
            else {
                residueIndex = this.residueSegmentMin;
            }
        }
        else if (residueIndex > this.residueSegmentMax) {
            var cyclicIndex = this.cyclicPolymerMap.get(this.residueSegmentMax);
            if (cyclicIndex !== undefined) {
                residueIndex = cyclicIndex + (residueIndex - this.residueSegmentMax - 1);
            }
            else {
                residueIndex = this.residueSegmentMax;
            }
        }
        return residueIndex;
    };
    AtomicPolymerTraceIterator.prototype.getSecStruc = function (residueIndex) {
        return this.secondaryStructureType[this.secondaryStructureGetIndex(residueIndex)];
    };
    AtomicPolymerTraceIterator.prototype.setControlPoint = function (out, p1, p2, p3, residueIndex) {
        var ss = this.getSecStruc(residueIndex);
        if (types["SecondaryStructureType"].is(ss, 4 /* Beta */)) {
            linear_algebra["Vec3"].scale(out, linear_algebra["Vec3"].add(out, p1, linear_algebra["Vec3"].add(out, p3, linear_algebra["Vec3"].add(out, p2, p2))), 1 / 4);
        }
        else {
            linear_algebra["Vec3"].copy(out, p2);
        }
    };
    AtomicPolymerTraceIterator.prototype.setFromToVector = function (out, residueIndex) {
        if (this.value.isCoarseBackbone) {
            linear_algebra["Vec3"].set(out, 1, 0, 0);
        }
        else {
            this.pos(tmpVecA, this.directionFromElementIndex[residueIndex]);
            this.pos(tmpVecB, this.directionToElementIndex[residueIndex]);
            linear_algebra["Vec3"].sub(out, tmpVecB, tmpVecA);
        }
    };
    AtomicPolymerTraceIterator.prototype.setDirection = function (out, v1, v2, v3) {
        linear_algebra["Vec3"].matchDirection(tmpVecA, v1, v2);
        linear_algebra["Vec3"].matchDirection(tmpVecB, v3, v2);
        linear_algebra["Vec3"].scale(out, linear_algebra["Vec3"].add(out, tmpVecA, linear_algebra["Vec3"].add(out, tmpVecB, linear_algebra["Vec3"].add(out, v2, v2))), 1 / 4);
    };
    AtomicPolymerTraceIterator.prototype.move = function () {
        var _a = this, residueIt = _a.residueIt, polymerIt = _a.polymerIt, value = _a.value;
        if (this.state === 0 /* nextPolymer */) {
            while (polymerIt.hasNext) {
                this.polymerSegment = polymerIt.move();
                residueIt.setSegment(this.polymerSegment);
                this.updateResidueSegmentRange(this.polymerSegment);
                if (residueIt.hasNext) {
                    this.state = 1 /* nextResidue */;
                    var residueIndexBeg = this.residueAtomSegments.index[this.unit.elements[this.polymerSegment.start]];
                    var residueIndexBegPrev = this.getResidueIndex(residueIndexBeg - 1);
                    this.currSecStrucType = residueIndexBeg === residueIndexBegPrev ? SecStrucTypeNA : this.getSecStruc(residueIndexBegPrev);
                    this.nextSecStrucType = this.getSecStruc(residueIndexBeg);
                    this.currCoarseBackbone = this.directionFromElementIndex[residueIndexBegPrev] === -1 || this.directionToElementIndex[residueIndexBegPrev] === -1;
                    this.nextCoarseBackbone = this.directionFromElementIndex[residueIndexBeg] === -1 || this.directionToElementIndex[residueIndexBeg] === -1;
                    break;
                }
            }
        }
        if (this.state === 1 /* nextResidue */) {
            var residueIndex = residueIt.move().index;
            var residueIndexPrev3 = this.getResidueIndex(residueIndex - 3);
            var residueIndexPrev2 = this.getResidueIndex(residueIndex - 2);
            var residueIndexPrev1 = this.getResidueIndex(residueIndex - 1);
            var residueIndexNext1 = this.getResidueIndex(residueIndex + 1);
            var residueIndexNext2 = this.getResidueIndex(residueIndex + 2);
            var residueIndexNext3 = this.getResidueIndex(residueIndex + 3);
            this.prevSecStrucType = this.currSecStrucType;
            this.currSecStrucType = this.nextSecStrucType;
            this.nextSecStrucType = residueIndex === residueIndexNext1 ? SecStrucTypeNA : this.getSecStruc(residueIndexNext1);
            this.prevCoarseBackbone = this.currCoarseBackbone;
            this.currCoarseBackbone = this.nextCoarseBackbone;
            this.nextCoarseBackbone = residueIndex === residueIndexNext1 ? false : (this.directionFromElementIndex[residueIndexNext1] === -1 || this.directionToElementIndex[residueIndexNext1] === -1);
            value.secStrucType = this.currSecStrucType;
            value.secStrucFirst = this.prevSecStrucType !== this.currSecStrucType;
            value.secStrucLast = this.currSecStrucType !== this.nextSecStrucType;
            value.isCoarseBackbone = this.currCoarseBackbone;
            value.coarseBackboneFirst = this.prevCoarseBackbone !== this.currCoarseBackbone;
            value.coarseBackboneLast = this.currCoarseBackbone !== this.nextCoarseBackbone;
            value.first = residueIndex === this.residueSegmentMin;
            value.last = residueIndex === this.residueSegmentMax;
            value.moleculeType = this.moleculeType[residueIndex];
            value.isCoarseBackbone = this.directionFromElementIndex[residueIndex] === -1 || this.directionToElementIndex[residueIndex] === -1;
            value.initial = residueIndex === residueIndexPrev1;
            value.final = residueIndex === residueIndexNext1;
            value.centerPrev.element = this.traceElementIndex[residueIndexPrev1];
            value.center.element = this.traceElementIndex[residueIndex];
            value.centerNext.element = this.traceElementIndex[residueIndexNext1];
            this.pos(this.p0, this.traceElementIndex[residueIndexPrev3]);
            this.pos(this.p1, this.traceElementIndex[residueIndexPrev2]);
            this.pos(this.p2, this.traceElementIndex[residueIndexPrev1]);
            this.pos(this.p3, this.traceElementIndex[residueIndex]);
            this.pos(this.p4, this.traceElementIndex[residueIndexNext1]);
            this.pos(this.p5, this.traceElementIndex[residueIndexNext2]);
            this.pos(this.p6, this.traceElementIndex[residueIndexNext3]);
            this.setFromToVector(this.d01, residueIndexPrev1);
            this.setFromToVector(this.d12, residueIndex);
            this.setFromToVector(this.d23, residueIndexNext1);
            this.setFromToVector(this.d34, residueIndexNext2);
            // extend termini
            var f = 0.5;
            if (residueIndex === residueIndexPrev1) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p3, this.p4), f);
                linear_algebra["Vec3"].add(this.p2, this.p3, tmpDir);
                linear_algebra["Vec3"].add(this.p1, this.p2, tmpDir);
                linear_algebra["Vec3"].add(this.p0, this.p1, tmpDir);
            }
            else if (residueIndexPrev1 === residueIndexPrev2) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p2, this.p3), f);
                linear_algebra["Vec3"].add(this.p1, this.p2, tmpDir);
                linear_algebra["Vec3"].add(this.p0, this.p1, tmpDir);
            }
            else if (residueIndexPrev2 === residueIndexPrev3) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p1, this.p2), f);
                linear_algebra["Vec3"].add(this.p0, this.p1, tmpDir);
            }
            if (residueIndex === residueIndexNext1) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p3, this.p2), f);
                linear_algebra["Vec3"].add(this.p4, this.p3, tmpDir);
                linear_algebra["Vec3"].add(this.p5, this.p4, tmpDir);
                linear_algebra["Vec3"].add(this.p6, this.p5, tmpDir);
            }
            else if (residueIndexNext1 === residueIndexNext2) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p4, this.p3), f);
                linear_algebra["Vec3"].add(this.p5, this.p4, tmpDir);
                linear_algebra["Vec3"].add(this.p6, this.p5, tmpDir);
            }
            else if (residueIndexNext2 === residueIndexNext3) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.p5, this.p4), f);
                linear_algebra["Vec3"].add(this.p6, this.p5, tmpDir);
            }
            this.setControlPoint(value.p0, this.p0, this.p1, this.p2, residueIndexPrev2);
            this.setControlPoint(value.p1, this.p1, this.p2, this.p3, residueIndexPrev1);
            this.setControlPoint(value.p2, this.p2, this.p3, this.p4, residueIndex);
            this.setControlPoint(value.p3, this.p3, this.p4, this.p5, residueIndexNext1);
            this.setControlPoint(value.p4, this.p4, this.p5, this.p6, residueIndexNext2);
            this.setDirection(value.d12, this.d01, this.d12, this.d23);
            this.setDirection(value.d23, this.d12, this.d23, this.d34);
            if (!residueIt.hasNext) {
                this.state = 0 /* nextPolymer */;
            }
        }
        this.hasNext = residueIt.hasNext || polymerIt.hasNext;
        return this.value;
    };
    return AtomicPolymerTraceIterator;
}());

var trace_iterator_CoarsePolymerTraceIterator = /** @class */ (function () {
    function CoarsePolymerTraceIterator(unit, structure) {
        this.unit = unit;
        this.state = 0 /* nextPolymer */;
        this.hasNext = false;
        this.polymerIt = sorted_ranges["a" /* default */].transientSegments(getPolymerRanges(unit), unit.elements);
        this.value = createPolymerTraceElement(structure, unit);
        linear_algebra["Vec3"].set(this.value.d12, 1, 0, 0);
        linear_algebra["Vec3"].set(this.value.d23, 1, 0, 0);
        switch (unit.kind) {
            case 1 /* Spheres */:
                this.conformation = unit.model.coarseConformation.spheres;
                break;
            case 2 /* Gaussians */:
                this.conformation = unit.model.coarseConformation.gaussians;
                break;
        }
        this.hasNext = this.polymerIt.hasNext;
    }
    CoarsePolymerTraceIterator.prototype.getElementIndex = function (elementIndex) {
        return Math.min(Math.max(this.polymerSegment.start, elementIndex), this.polymerSegment.end - 1);
    };
    CoarsePolymerTraceIterator.prototype.pos = function (target, elementIndex) {
        var index = this.unit.elements[elementIndex];
        target[0] = this.conformation.x[index];
        target[1] = this.conformation.y[index];
        target[2] = this.conformation.z[index];
    };
    CoarsePolymerTraceIterator.prototype.move = function () {
        if (this.state === 0 /* nextPolymer */) {
            while (this.polymerIt.hasNext) {
                this.polymerSegment = this.polymerIt.move();
                this.elementIndex = this.polymerSegment.start;
                if (this.elementIndex < this.polymerSegment.end) {
                    this.state = 1 /* nextElement */;
                    break;
                }
            }
        }
        if (this.state === 1 /* nextElement */) {
            var elementIndexPrev2 = this.getElementIndex(this.elementIndex - 2);
            var elementIndexPrev1 = this.getElementIndex(this.elementIndex - 1);
            var elementIndexNext1 = this.getElementIndex(this.elementIndex + 1);
            var elementIndexNext2 = this.getElementIndex(this.elementIndex + 2);
            this.value.centerPrev.element = this.value.center.unit.elements[elementIndexPrev1];
            this.value.center.element = this.value.center.unit.elements[this.elementIndex];
            this.value.centerNext.element = this.value.center.unit.elements[elementIndexNext1];
            this.pos(this.value.p0, elementIndexPrev2);
            this.pos(this.value.p1, elementIndexPrev1);
            this.pos(this.value.p2, this.elementIndex);
            this.pos(this.value.p3, elementIndexNext1);
            this.pos(this.value.p4, elementIndexNext2);
            // extend termini
            var f = 0.5;
            if (this.elementIndex === elementIndexPrev1) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.value.p2, this.value.p3), f);
                linear_algebra["Vec3"].add(this.value.p1, this.value.p2, tmpDir);
                linear_algebra["Vec3"].add(this.value.p0, this.value.p1, tmpDir);
            }
            else if (elementIndexPrev1 === elementIndexPrev2) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.value.p1, this.value.p2), f);
                linear_algebra["Vec3"].add(this.value.p0, this.value.p1, tmpDir);
            }
            if (this.elementIndex === elementIndexNext1) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.value.p2, this.value.p1), f);
                linear_algebra["Vec3"].add(this.value.p3, this.value.p2, tmpDir);
                linear_algebra["Vec3"].add(this.value.p4, this.value.p3, tmpDir);
            }
            else if (elementIndexNext1 === elementIndexNext2) {
                linear_algebra["Vec3"].scale(tmpDir, linear_algebra["Vec3"].sub(tmpDir, this.value.p3, this.value.p2), f);
                linear_algebra["Vec3"].add(this.value.p4, this.value.p3, tmpDir);
            }
            this.value.first = this.elementIndex === this.polymerSegment.start;
            this.value.last = this.elementIndex === this.polymerSegment.end - 1;
            if (this.elementIndex + 1 >= this.polymerSegment.end) {
                this.state = 0 /* nextPolymer */;
            }
        }
        this.hasNext = this.elementIndex + 1 < this.polymerSegment.end || this.polymerIt.hasNext;
        this.elementIndex += 1;
        return this.value;
    };
    return CoarsePolymerTraceIterator;
}());

//# sourceMappingURL=trace-iterator.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/interpolate.js
var interpolate = __webpack_require__(78);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/polymer/curve-segment.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


function createCurveSegmentState(linearSegments) {
    var n = linearSegments + 1;
    var pn = n * 3;
    return {
        curvePoints: new Float32Array(pn),
        tangentVectors: new Float32Array(pn),
        normalVectors: new Float32Array(pn),
        binormalVectors: new Float32Array(pn),
        widthValues: new Float32Array(n),
        heightValues: new Float32Array(n),
        linearSegments: linearSegments
    };
}
function interpolateCurveSegment(state, controls, tension, shift) {
    interpolatePointsAndTangents(state, controls, tension, shift);
    interpolateNormals(state, controls);
}
var tanA = linear_algebra["Vec3"].zero();
var tanB = linear_algebra["Vec3"].zero();
var curvePoint = linear_algebra["Vec3"].zero();
function interpolatePointsAndTangents(state, controls, tension, shift) {
    var curvePoints = state.curvePoints, tangentVectors = state.tangentVectors, linearSegments = state.linearSegments;
    var p0 = controls.p0, p1 = controls.p1, p2 = controls.p2, p3 = controls.p3, p4 = controls.p4, secStrucFirst = controls.secStrucFirst, secStrucLast = controls.secStrucLast;
    var shift1 = 1 - shift;
    var tensionBeg = secStrucFirst ? 0.5 : tension;
    var tensionEnd = secStrucLast ? 0.5 : tension;
    for (var j = 0; j <= linearSegments; ++j) {
        var t = j * 1.0 / linearSegments;
        if (t < shift1) {
            var te = Object(interpolate["b" /* lerp */])(tensionBeg, tension, t);
            linear_algebra["Vec3"].spline(curvePoint, p0, p1, p2, p3, t + shift, te);
            linear_algebra["Vec3"].spline(tanA, p0, p1, p2, p3, t + shift + 0.01, tensionBeg);
            linear_algebra["Vec3"].spline(tanB, p0, p1, p2, p3, t + shift - 0.01, tensionBeg);
        }
        else {
            var te = Object(interpolate["b" /* lerp */])(tension, tensionEnd, t);
            linear_algebra["Vec3"].spline(curvePoint, p1, p2, p3, p4, t - shift1, te);
            linear_algebra["Vec3"].spline(tanA, p1, p2, p3, p4, t - shift1 + 0.01, te);
            linear_algebra["Vec3"].spline(tanB, p1, p2, p3, p4, t - shift1 - 0.01, te);
        }
        linear_algebra["Vec3"].toArray(curvePoint, curvePoints, j * 3);
        linear_algebra["Vec3"].normalize(tangentVec, linear_algebra["Vec3"].sub(tangentVec, tanA, tanB));
        linear_algebra["Vec3"].toArray(tangentVec, tangentVectors, j * 3);
    }
}
var tmpNormal = Object(linear_algebra["Vec3"])();
var tangentVec = Object(linear_algebra["Vec3"])();
var normalVec = Object(linear_algebra["Vec3"])();
var binormalVec = Object(linear_algebra["Vec3"])();
var prevNormal = Object(linear_algebra["Vec3"])();
var firstTangentVec = Object(linear_algebra["Vec3"])();
var lastTangentVec = Object(linear_algebra["Vec3"])();
var firstNormalVec = Object(linear_algebra["Vec3"])();
var lastNormalVec = Object(linear_algebra["Vec3"])();
/**
 * Populate normalVectors by interpolating from firstDirection to lastDirection with
 * resulting vector perpendicular to tangentVectors and binormalVectors
 */
function interpolateNormals(state, controls) {
    var curvePoints = state.curvePoints, tangentVectors = state.tangentVectors, normalVectors = state.normalVectors, binormalVectors = state.binormalVectors;
    var firstDirection = controls.d12, lastDirection = controls.d23;
    var n = curvePoints.length / 3;
    linear_algebra["Vec3"].fromArray(firstTangentVec, tangentVectors, 0);
    linear_algebra["Vec3"].fromArray(lastTangentVec, tangentVectors, (n - 1) * 3);
    linear_algebra["Vec3"].orthogonalize(firstNormalVec, firstTangentVec, firstDirection);
    linear_algebra["Vec3"].orthogonalize(lastNormalVec, lastTangentVec, lastDirection);
    linear_algebra["Vec3"].matchDirection(lastNormalVec, lastNormalVec, firstNormalVec);
    linear_algebra["Vec3"].copy(prevNormal, firstNormalVec);
    for (var i = 0; i < n; ++i) {
        var t = i === 0 ? 0 : 1 / (n - i);
        linear_algebra["Vec3"].fromArray(tangentVec, tangentVectors, i * 3);
        linear_algebra["Vec3"].orthogonalize(normalVec, tangentVec, linear_algebra["Vec3"].slerp(tmpNormal, prevNormal, lastNormalVec, t));
        linear_algebra["Vec3"].toArray(normalVec, normalVectors, i * 3);
        linear_algebra["Vec3"].copy(prevNormal, normalVec);
        linear_algebra["Vec3"].normalize(binormalVec, linear_algebra["Vec3"].cross(binormalVec, tangentVec, normalVec));
        linear_algebra["Vec3"].toArray(binormalVec, binormalVectors, i * 3);
    }
}
function interpolateSizes(state, w0, w1, w2, h0, h1, h2, shift) {
    var widthValues = state.widthValues, heightValues = state.heightValues, linearSegments = state.linearSegments;
    var shift1 = 1 - shift;
    for (var i = 0; i <= linearSegments; ++i) {
        var t = i * 1.0 / linearSegments;
        if (t < shift1) {
            widthValues[i] = Object(interpolate["b" /* lerp */])(w0, w1, t + shift);
            heightValues[i] = Object(interpolate["b" /* lerp */])(h0, h1, t + shift);
        }
        else {
            widthValues[i] = Object(interpolate["b" /* lerp */])(w1, w2, t - shift1);
            heightValues[i] = Object(interpolate["b" /* lerp */])(h1, h2, t - shift1);
        }
    }
}
//# sourceMappingURL=curve-segment.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/polymer.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */









var StandardTension = 0.5;
var HelixTension = 0.9;
var StandardShift = 0.5;
var NucleicShift = 0.3;
var OverhangFactor = 2;
function getPolymerRanges(unit) {
    switch (unit.kind) {
        case 0 /* Atomic */: return unit.model.atomicRanges.polymerRanges;
        case 1 /* Spheres */: return unit.model.coarseHierarchy.spheres.polymerRanges;
        case 2 /* Gaussians */: return unit.model.coarseHierarchy.gaussians.polymerRanges;
    }
}
function getGapRanges(unit) {
    switch (unit.kind) {
        case 0 /* Atomic */: return unit.model.atomicRanges.gapRanges;
        case 1 /* Spheres */: return unit.model.coarseHierarchy.spheres.gapRanges;
        case 2 /* Gaussians */: return unit.model.coarseHierarchy.gaussians.gapRanges;
    }
}
var polymer_PolymerLocationIterator;
(function (PolymerLocationIterator) {
    function fromGroup(structureGroup) {
        var group = structureGroup.group, structure = structureGroup.structure;
        var polymerElements = group.units[0].polymerElements;
        var groupCount = polymerElements.length;
        var instanceCount = group.units.length;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex, instanceIndex) {
            var unit = group.units[instanceIndex];
            location.unit = unit;
            location.element = polymerElements[groupIndex];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
    }
    PolymerLocationIterator.fromGroup = fromGroup;
})(polymer_PolymerLocationIterator || (polymer_PolymerLocationIterator = {}));
var polymer_PolymerGapLocationIterator;
(function (PolymerGapLocationIterator) {
    function fromGroup(structureGroup) {
        var group = structureGroup.group, structure = structureGroup.structure;
        var gapElements = group.units[0].gapElements;
        var groupCount = gapElements.length;
        var instanceCount = group.units.length;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex, instanceIndex) {
            var unit = group.units[instanceIndex];
            location.unit = unit;
            location.element = gapElements[groupIndex];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
    }
    PolymerGapLocationIterator.fromGroup = fromGroup;
})(polymer_PolymerGapLocationIterator || (polymer_PolymerGapLocationIterator = {}));
/** Return a Loci for the elements of the whole residue of a polymer element. */
function getPolymerElementLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        if (mol_model_structure["Unit"].isAtomic(unit)) {
            return Object(common["g" /* getResidueLoci */])(structure, unit, unit.polymerElements[groupId]);
        }
        else {
            var elements = unit.elements;
            var elementIndex = unit.polymerElements[groupId];
            var unitIndex = mol_data_int["OrderedSet"].indexOf(elements, elementIndex);
            if (unitIndex !== -1) {
                var indices = mol_data_int["OrderedSet"].ofSingleton(unitIndex);
                return mol_model_structure["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
            }
        }
    }
    return mol_model_loci["EmptyLoci"];
}
function tryApplyResidueInterval(offset, elements, traceElementIndex, apply, r1, r2) {
    var start = -1, startIdx = -1;
    for (var rI = r1; rI <= r2; rI++) {
        var eI = traceElementIndex[rI];
        if (eI < 0)
            continue;
        start = mol_data_int["OrderedSet"].indexOf(elements, eI);
        if (start >= 0) {
            startIdx = rI;
            break;
        }
    }
    if (start < 0) {
        return false;
    }
    var end = start;
    for (var rI = r2; rI > startIdx; rI--) {
        var eI = traceElementIndex[rI];
        if (eI < 0)
            continue;
        var e = mol_data_int["OrderedSet"].indexOf(elements, eI);
        if (e >= 0) {
            end = e;
            break;
        }
    }
    return apply(mol_data_int["Interval"].ofRange(offset + start, offset + end));
}
function eachAtomicUnitTracedElement(offset, groupSize, elementsSelector, apply, e) {
    var changed = false;
    var elements = e.unit.elements;
    var traceElementIndex = e.unit.model.atomicHierarchy.derived.residue.traceElementIndex;
    var resIndex = e.unit.model.atomicHierarchy.residueAtomSegments.index;
    var tracedElements = elementsSelector(e.unit);
    if (mol_data_int["Interval"].is(e.indices)) {
        if (mol_data_int["Interval"].start(e.indices) === 0 && mol_data_int["Interval"].end(e.indices) === e.unit.elements.length) {
            // full unit here
            changed = apply(mol_data_int["Interval"].ofBounds(offset, offset + groupSize)) || changed;
        }
        else {
            var r1 = resIndex[elements[mol_data_int["Interval"].min(e.indices)]];
            var r2 = resIndex[elements[mol_data_int["Interval"].max(e.indices)]];
            changed = tryApplyResidueInterval(offset, tracedElements, traceElementIndex, apply, r1, r2) || changed;
        }
    }
    else {
        var indices = e.indices;
        for (var i = 0, _i = indices.length; i < _i; i++) {
            var r1 = resIndex[elements[indices[i]]];
            var r2 = r1;
            var endI = i + 1;
            while (endI < _i) {
                var _r = resIndex[elements[indices[endI]]];
                if (_r - r2 > 1)
                    break;
                r2 = _r;
                endI++;
            }
            i = endI - 1;
            changed = tryApplyResidueInterval(offset, tracedElements, traceElementIndex, apply, r1, r2) || changed;
        }
    }
    return changed;
}
function selectPolymerElements(u) { return u.polymerElements; }
/** Mark a polymer element (e.g. part of a cartoon trace) */
function eachPolymerElement(loci, structureGroup, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    var structure = structureGroup.structure, group = structureGroup.group;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var groupCount = group.units[0].polymerElements.length;
    for (var _a = 0, _b = loci.elements; _a < _b.length; _a++) {
        var e = _b[_a];
        if (!group.unitIndexMap.has(e.unit.id))
            continue;
        var offset = group.unitIndexMap.get(e.unit.id) * groupCount; // to target unit instance
        if (mol_model_structure["Unit"].isAtomic(e.unit)) {
            changed = eachAtomicUnitTracedElement(offset, groupCount, selectPolymerElements, apply, e) || changed;
        }
        else {
            if (mol_data_int["Interval"].is(e.indices)) {
                var start = offset + mol_data_int["Interval"].start(e.indices);
                var end = offset + mol_data_int["Interval"].end(e.indices);
                changed = apply(mol_data_int["Interval"].ofBounds(start, end)) || changed;
            }
            else {
                for (var i = 0, _i = e.indices.length; i < _i; i++) {
                    var start = e.indices[i];
                    var endI = i + 1;
                    while (endI < _i && e.indices[endI] === start)
                        endI++;
                    i = endI - 1;
                    var end = e.indices[i];
                    changed = apply(mol_data_int["Interval"].ofRange(offset + start, offset + end)) || changed;
                }
            }
        }
    }
    return changed;
}
/** Return a Loci for both directions of the polymer gap element. */
function getPolymerGapElementLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        var unitIndexA = mol_data_int["OrderedSet"].indexOf(unit.elements, unit.gapElements[groupId]);
        var unitIndexB = mol_data_int["OrderedSet"].indexOf(unit.elements, unit.gapElements[groupId % 2 ? groupId - 1 : groupId + 1]);
        if (unitIndexA !== -1 && unitIndexB !== -1) {
            return mol_model_structure["Bond"].Loci(structure, [
                mol_model_structure["Bond"].Location(structure, unit, unitIndexA, structure, unit, unitIndexB),
                mol_model_structure["Bond"].Location(structure, unit, unitIndexB, structure, unit, unitIndexA)
            ]);
        }
    }
    return mol_model_loci["EmptyLoci"];
}
function eachPolymerGapElement(loci, structureGroup, apply) {
    var changed = false;
    if (mol_model_structure["Bond"].isLoci(loci)) {
        var structure = structureGroup.structure, group = structureGroup.group;
        if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
            return false;
        loci = mol_model_structure["Bond"].remapLoci(loci, structure);
        var groupCount = group.units[0].gapElements.length;
        for (var _a = 0, _b = loci.bonds; _a < _b.length; _a++) {
            var b = _b[_a];
            var unitIdx = group.unitIndexMap.get(b.aUnit.id);
            if (unitIdx !== undefined) {
                var idxA = mol_data_int["OrderedSet"].indexOf(b.aUnit.gapElements, b.aUnit.elements[b.aIndex]);
                var idxB = mol_data_int["OrderedSet"].indexOf(b.bUnit.gapElements, b.bUnit.elements[b.bIndex]);
                if (idxA !== -1 && idxB !== -1) {
                    if (apply(mol_data_int["Interval"].ofSingleton(unitIdx * groupCount + idxA)))
                        changed = true;
                }
            }
        }
    }
    else if (mol_model_structure["StructureElement"].Loci.is(loci)) {
        var structure = structureGroup.structure, group = structureGroup.group;
        if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
            return false;
        loci = mol_model_structure["StructureElement"].Loci.remap(loci, structure);
        var groupCount_1 = group.units[0].gapElements.length;
        var _loop_1 = function (e) {
            var unitIdx = group.unitIndexMap.get(e.unit.id);
            if (unitIdx !== undefined) {
                mol_data_int["OrderedSet"].forEach(e.indices, function (v) {
                    var idx = mol_data_int["OrderedSet"].indexOf(e.unit.gapElements, e.unit.elements[v]);
                    if (idx !== -1) {
                        if (apply(mol_data_int["Interval"].ofSingleton(unitIdx * groupCount_1 + idx)))
                            changed = true;
                    }
                });
            }
        };
        for (var _c = 0, _d = loci.elements; _c < _d.length; _c++) {
            var e = _d[_c];
            _loop_1(e);
        }
    }
    return changed;
}
//# sourceMappingURL=polymer.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/nucleotide.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





var nucleotide_NucleotideLocationIterator;
(function (NucleotideLocationIterator) {
    function fromGroup(structureGroup) {
        var group = structureGroup.group, structure = structureGroup.structure;
        var u = group.units[0];
        var nucleotideElementIndices = mol_model_structure["Unit"].isAtomic(u) ? u.nucleotideElements : [];
        var groupCount = nucleotideElementIndices.length;
        var instanceCount = group.units.length;
        var location = mol_model_structure["StructureElement"].Location.create(structure);
        var getLocation = function (groupIndex, instanceIndex) {
            var unit = group.units[instanceIndex];
            location.unit = unit;
            location.element = nucleotideElementIndices[groupIndex];
            return location;
        };
        return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
    }
    NucleotideLocationIterator.fromGroup = fromGroup;
})(nucleotide_NucleotideLocationIterator || (nucleotide_NucleotideLocationIterator = {}));
function getNucleotideElementLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId, groupId = pickingId.groupId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        if (mol_model_structure["Unit"].isAtomic(unit)) {
            return Object(common["g" /* getResidueLoci */])(structure, unit, unit.nucleotideElements[groupId]);
        }
    }
    return mol_model_loci["EmptyLoci"];
}
function selectNuclotideElements(u) { return u.nucleotideElements; }
/**
 * Mark a nucleotide element (e.g. part of a cartoon block)
 * - mark only when all its residue's elements are in a loci
 */
function eachNucleotideElement(loci, structureGroup, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    var structure = structureGroup.structure, group = structureGroup.group;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var unit = group.units[0];
    if (!mol_model_structure["Unit"].isAtomic(unit))
        return false;
    var nucleotideElements = unit.nucleotideElements;
    var groupCount = nucleotideElements.length;
    for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
        var e = _a[_i];
        if (!mol_model_structure["Unit"].isAtomic(e.unit))
            continue;
        if (!group.unitIndexMap.has(e.unit.id))
            continue;
        var intervalOffset = group.unitIndexMap.get(e.unit.id) * groupCount;
        if (mol_model_structure["Unit"].isAtomic(e.unit)) {
            changed = eachAtomicUnitTracedElement(intervalOffset, groupCount, selectNuclotideElements, apply, e) || changed;
        }
    }
    return changed;
}
//# sourceMappingURL=nucleotide.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/nucleotide-block-mesh.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














// TODO support blocks for multiple locations (including from microheterogeneity)
var nucleotide_block_mesh_p1 = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_p2 = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_p3 = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_p4 = linear_algebra["Vec3"].zero();
var p5 = linear_algebra["Vec3"].zero();
var p6 = linear_algebra["Vec3"].zero();
var v12 = linear_algebra["Vec3"].zero();
var v34 = linear_algebra["Vec3"].zero();
var vC = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_center = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_t = linear_algebra["Mat4"].identity();
var nucleotide_block_mesh_sVec = linear_algebra["Vec3"].zero();
var nucleotide_block_mesh_box = Object(primitive_box["a" /* Box */])();
var NucleotideBlockMeshParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
    radialSegments: param_definition["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
};
var DefaultNucleotideBlockMeshProps = param_definition["ParamDefinition"].getDefaultValues(NucleotideBlockMeshParams);
function createNucleotideBlockMesh(ctx, unit, structure, theme, props, mesh) {
    if (!mol_model_structure["Unit"].isAtomic(unit))
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var nucleotideElementCount = unit.nucleotideElements.length;
    if (!nucleotideElementCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor, radialSegments = props.radialSegments;
    var vertexCount = nucleotideElementCount * (nucleotide_block_mesh_box.vertices.length / 3 + radialSegments * 2);
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 4, mesh);
    var elements = unit.elements, model = unit.model;
    var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments, atoms = _a.atoms, atomicIndex = _a.index;
    var _b = model.atomicHierarchy.derived.residue, moleculeType = _b.moleculeType, traceElementIndex = _b.traceElementIndex;
    var label_comp_id = atoms.label_comp_id;
    var pos = unit.conformation.invariantPosition;
    var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, elements);
    var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
    var cylinderProps = { radiusTop: 1 * sizeFactor, radiusBottom: 1 * sizeFactor, radialSegments: radialSegments, bottomCap: true };
    var i = 0;
    while (chainIt.hasNext) {
        residueIt.setSegment(chainIt.move());
        while (residueIt.hasNext) {
            var residueIndex = residueIt.move().index;
            if (Object(types["isNucleic"])(moleculeType[residueIndex])) {
                var compId = label_comp_id.value(residueAtomSegments.offsets[residueIndex]);
                var idx1 = -1, idx2 = -1, idx3 = -1, idx4 = -1, idx5 = -1, idx6 = -1;
                var width = 4.5, height = 4.5, depth = 2.5 * sizeFactor;
                var isPurine = Object(types["isPurineBase"])(compId);
                var isPyrimidine = Object(types["isPyrimidineBase"])(compId);
                if (!isPurine && !isPyrimidine) {
                    // detect Purine or Pyrimidin based on geometry
                    var idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    var idxN9 = atomicIndex.findAtomOnResidue(residueIndex, 'N9');
                    if (idxC4 !== -1 && idxN9 !== -1 && linear_algebra["Vec3"].distance(pos(idxC4, nucleotide_block_mesh_p1), pos(idxN9, nucleotide_block_mesh_p2)) < 1.6) {
                        isPurine = true;
                    }
                    else {
                        isPyrimidine = true;
                    }
                }
                if (isPurine) {
                    height = 4.5;
                    idx1 = atomicIndex.findAtomOnResidue(residueIndex, 'N1');
                    idx2 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    idx3 = atomicIndex.findAtomOnResidue(residueIndex, 'C6');
                    idx4 = atomicIndex.findAtomOnResidue(residueIndex, 'C2');
                    idx5 = atomicIndex.findAtomOnResidue(residueIndex, 'N9');
                    idx6 = traceElementIndex[residueIndex];
                }
                else if (isPyrimidine) {
                    height = 3.0;
                    idx1 = atomicIndex.findAtomOnResidue(residueIndex, 'N3');
                    idx2 = atomicIndex.findAtomOnResidue(residueIndex, 'C6');
                    idx3 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    idx4 = atomicIndex.findAtomOnResidue(residueIndex, 'C2');
                    idx5 = atomicIndex.findAtomOnResidue(residueIndex, 'N1');
                    if (idx5 === -1) {
                        // modified ring, e.g. DZ
                        idx5 = atomicIndex.findAtomOnResidue(residueIndex, 'C1');
                    }
                    idx6 = traceElementIndex[residueIndex];
                }
                if (idx5 !== -1 && idx6 !== -1) {
                    pos(idx5, p5);
                    pos(idx6, p6);
                    builderState.currentGroup = i;
                    Object(cylinder["a" /* addCylinder */])(builderState, p5, p6, 1, cylinderProps);
                    if (idx1 !== -1 && idx2 !== -1 && idx3 !== -1 && idx4 !== -1) {
                        pos(idx1, nucleotide_block_mesh_p1);
                        pos(idx2, nucleotide_block_mesh_p2);
                        pos(idx3, nucleotide_block_mesh_p3);
                        pos(idx4, nucleotide_block_mesh_p4);
                        linear_algebra["Vec3"].normalize(v12, linear_algebra["Vec3"].sub(v12, nucleotide_block_mesh_p2, nucleotide_block_mesh_p1));
                        linear_algebra["Vec3"].normalize(v34, linear_algebra["Vec3"].sub(v34, nucleotide_block_mesh_p4, nucleotide_block_mesh_p3));
                        linear_algebra["Vec3"].normalize(vC, linear_algebra["Vec3"].cross(vC, v12, v34));
                        linear_algebra["Mat4"].targetTo(nucleotide_block_mesh_t, nucleotide_block_mesh_p1, nucleotide_block_mesh_p2, vC);
                        linear_algebra["Vec3"].scaleAndAdd(nucleotide_block_mesh_center, nucleotide_block_mesh_p1, v12, height / 2 - 0.2);
                        linear_algebra["Mat4"].scale(nucleotide_block_mesh_t, nucleotide_block_mesh_t, linear_algebra["Vec3"].set(nucleotide_block_mesh_sVec, width, depth, height));
                        linear_algebra["Mat4"].setTranslation(nucleotide_block_mesh_t, nucleotide_block_mesh_center);
                        mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, nucleotide_block_mesh_t, nucleotide_block_mesh_box);
                    }
                }
                ++i;
            }
        }
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var NucleotideBlockParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), NucleotideBlockMeshParams);
function NucleotideBlockVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(NucleotideBlockParams),
        createGeometry: createNucleotideBlockMesh,
        createLocationIterator: nucleotide_NucleotideLocationIterator.fromGroup,
        getLoci: getNucleotideElementLoci,
        eachLocation: eachNucleotideElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments);
        }
    }, materialId);
}
//# sourceMappingURL=nucleotide-block-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/nucleotide-ring-mesh.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














// TODO support rings for multiple locations (including from microheterogeneity)
var pTrace = linear_algebra["Vec3"].zero();
var pN1 = linear_algebra["Vec3"].zero();
var pC2 = linear_algebra["Vec3"].zero();
var pN3 = linear_algebra["Vec3"].zero();
var pC4 = linear_algebra["Vec3"].zero();
var pC5 = linear_algebra["Vec3"].zero();
var pC6 = linear_algebra["Vec3"].zero();
var pN7 = linear_algebra["Vec3"].zero();
var pC8 = linear_algebra["Vec3"].zero();
var pN9 = linear_algebra["Vec3"].zero();
var nucleotide_ring_mesh_normal = linear_algebra["Vec3"].zero();
var NucleotideRingMeshParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
    radialSegments: param_definition["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
    detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
};
var DefaultNucleotideRingMeshProps = param_definition["ParamDefinition"].getDefaultValues(NucleotideRingMeshParams);
var positionsRing5_6 = new Float32Array(2 * 9 * 3);
var stripIndicesRing5_6 = new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 14, 15, 12, 13, 8, 9, 10, 11, 0, 1]);
var fanIndicesTopRing5_6 = new Uint32Array([8, 12, 14, 16, 6, 4, 2, 0, 10]);
var fanIndicesBottomRing5_6 = new Uint32Array([9, 11, 1, 3, 5, 7, 17, 15, 13]);
var positionsRing6 = new Float32Array(2 * 6 * 3);
var stripIndicesRing6 = new Uint32Array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1]);
var fanIndicesTopRing6 = new Uint32Array([0, 10, 8, 6, 4, 2]);
var fanIndicesBottomRing6 = new Uint32Array([1, 3, 5, 7, 9, 11]);
var tmpShiftV = linear_algebra["Vec3"].zero();
function shiftPositions(out, dir) {
    var positions = [];
    for (var _i = 2; _i < arguments.length; _i++) {
        positions[_i - 2] = arguments[_i];
    }
    for (var i = 0, il = positions.length; i < il; ++i) {
        var v = positions[i];
        linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].add(tmpShiftV, v, dir), out, (i * 2) * 3);
        linear_algebra["Vec3"].toArray(linear_algebra["Vec3"].sub(tmpShiftV, v, dir), out, (i * 2 + 1) * 3);
    }
}
function createNucleotideRingMesh(ctx, unit, structure, theme, props, mesh) {
    if (!mol_model_structure["Unit"].isAtomic(unit))
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var nucleotideElementCount = unit.nucleotideElements.length;
    if (!nucleotideElementCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor, radialSegments = props.radialSegments, detail = props.detail;
    var vertexCount = nucleotideElementCount * (26 + radialSegments * 2);
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 4, mesh);
    var elements = unit.elements, model = unit.model;
    var _a = model.atomicHierarchy, chainAtomSegments = _a.chainAtomSegments, residueAtomSegments = _a.residueAtomSegments, atoms = _a.atoms, atomicIndex = _a.index;
    var _b = model.atomicHierarchy.derived.residue, moleculeType = _b.moleculeType, traceElementIndex = _b.traceElementIndex;
    var label_comp_id = atoms.label_comp_id;
    var pos = unit.conformation.invariantPosition;
    var chainIt = mol_data_int["Segmentation"].transientSegments(chainAtomSegments, elements);
    var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, elements);
    var radius = 1 * sizeFactor;
    var halfThickness = 1.25 * sizeFactor;
    var cylinderProps = { radiusTop: 1 * sizeFactor, radiusBottom: 1 * sizeFactor, radialSegments: radialSegments };
    var i = 0;
    while (chainIt.hasNext) {
        residueIt.setSegment(chainIt.move());
        while (residueIt.hasNext) {
            var residueIndex = residueIt.move().index;
            if (Object(types["isNucleic"])(moleculeType[residueIndex])) {
                var compId = label_comp_id.value(residueAtomSegments.offsets[residueIndex]);
                var idxTrace = -1, idxN1 = -1, idxC2 = -1, idxN3 = -1, idxC4 = -1, idxC5 = -1, idxC6 = -1, idxN7 = -1, idxC8 = -1, idxN9 = -1;
                builderState.currentGroup = i;
                var isPurine = Object(types["isPurineBase"])(compId);
                var isPyrimidine = Object(types["isPyrimidineBase"])(compId);
                if (!isPurine && !isPyrimidine) {
                    // detect Purine or Pyrimidin based on geometry
                    var idxC4_1 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    var idxN9_1 = atomicIndex.findAtomOnResidue(residueIndex, 'N9');
                    if (idxC4_1 !== -1 && idxN9_1 !== -1 && linear_algebra["Vec3"].distance(pos(idxC4_1, pC4), pos(idxN9_1, pN9)) < 1.6) {
                        isPurine = true;
                    }
                    else {
                        isPyrimidine = true;
                    }
                }
                if (isPurine) {
                    idxTrace = traceElementIndex[residueIndex];
                    idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'N1');
                    idxC2 = atomicIndex.findAtomOnResidue(residueIndex, 'C2');
                    idxN3 = atomicIndex.findAtomOnResidue(residueIndex, 'N3');
                    idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'C5');
                    if (idxC5 === -1) {
                        // modified ring, e.g. DP
                        idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'N5');
                    }
                    idxC6 = atomicIndex.findAtomOnResidue(residueIndex, 'C6');
                    idxN7 = atomicIndex.findAtomOnResidue(residueIndex, 'N7');
                    if (idxN7 === -1) {
                        // modified ring, e.g. DP
                        idxN7 = atomicIndex.findAtomOnResidue(residueIndex, 'C7');
                    }
                    idxC8 = atomicIndex.findAtomOnResidue(residueIndex, 'C8');
                    idxN9 = atomicIndex.findAtomOnResidue(residueIndex, 'N9');
                    if (idxN9 !== -1 && idxTrace !== -1) {
                        pos(idxN9, pN9);
                        pos(idxTrace, pTrace);
                        builderState.currentGroup = i;
                        Object(cylinder["a" /* addCylinder */])(builderState, pN9, pTrace, 1, cylinderProps);
                        Object(builder_sphere["a" /* addSphere */])(builderState, pN9, radius, detail);
                    }
                    if (idxN1 !== -1 && idxC2 !== -1 && idxN3 !== -1 && idxC4 !== -1 && idxC5 !== -1 && idxC6 !== -1 && idxN7 !== -1 && idxC8 !== -1 && idxN9 !== -1) {
                        pos(idxN1, pN1);
                        pos(idxC2, pC2);
                        pos(idxN3, pN3);
                        pos(idxC4, pC4);
                        pos(idxC5, pC5);
                        pos(idxC6, pC6);
                        pos(idxN7, pN7);
                        pos(idxC8, pC8);
                        linear_algebra["Vec3"].triangleNormal(nucleotide_ring_mesh_normal, pN1, pC4, pC5);
                        linear_algebra["Vec3"].scale(nucleotide_ring_mesh_normal, nucleotide_ring_mesh_normal, halfThickness);
                        shiftPositions(positionsRing5_6, nucleotide_ring_mesh_normal, pN1, pC2, pN3, pC4, pC5, pC6, pN7, pC8, pN9);
                        mesh_builder["a" /* MeshBuilder */].addTriangleStrip(builderState, positionsRing5_6, stripIndicesRing5_6);
                        mesh_builder["a" /* MeshBuilder */].addTriangleFan(builderState, positionsRing5_6, fanIndicesTopRing5_6);
                        mesh_builder["a" /* MeshBuilder */].addTriangleFan(builderState, positionsRing5_6, fanIndicesBottomRing5_6);
                    }
                }
                else if (isPyrimidine) {
                    idxTrace = traceElementIndex[residueIndex];
                    idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'N1');
                    if (idxN1 === -1) {
                        // modified ring, e.g. DZ
                        idxN1 = atomicIndex.findAtomOnResidue(residueIndex, 'C1');
                    }
                    idxC2 = atomicIndex.findAtomOnResidue(residueIndex, 'C2');
                    idxN3 = atomicIndex.findAtomOnResidue(residueIndex, 'N3');
                    idxC4 = atomicIndex.findAtomOnResidue(residueIndex, 'C4');
                    idxC5 = atomicIndex.findAtomOnResidue(residueIndex, 'C5');
                    idxC6 = atomicIndex.findAtomOnResidue(residueIndex, 'C6');
                    if (idxN1 !== -1 && idxTrace !== -1) {
                        pos(idxN1, pN1);
                        pos(idxTrace, pTrace);
                        builderState.currentGroup = i;
                        Object(cylinder["a" /* addCylinder */])(builderState, pN1, pTrace, 1, cylinderProps);
                        Object(builder_sphere["a" /* addSphere */])(builderState, pN1, radius, detail);
                    }
                    if (idxN1 !== -1 && idxC2 !== -1 && idxN3 !== -1 && idxC4 !== -1 && idxC5 !== -1 && idxC6 !== -1) {
                        pos(idxC2, pC2);
                        pos(idxN3, pN3);
                        pos(idxC4, pC4);
                        pos(idxC5, pC5);
                        pos(idxC6, pC6);
                        linear_algebra["Vec3"].triangleNormal(nucleotide_ring_mesh_normal, pN1, pC4, pC5);
                        linear_algebra["Vec3"].scale(nucleotide_ring_mesh_normal, nucleotide_ring_mesh_normal, halfThickness);
                        shiftPositions(positionsRing6, nucleotide_ring_mesh_normal, pN1, pC2, pN3, pC4, pC5, pC6);
                        mesh_builder["a" /* MeshBuilder */].addTriangleStrip(builderState, positionsRing6, stripIndicesRing6);
                        mesh_builder["a" /* MeshBuilder */].addTriangleFan(builderState, positionsRing6, fanIndicesTopRing6);
                        mesh_builder["a" /* MeshBuilder */].addTriangleFan(builderState, positionsRing6, fanIndicesBottomRing6);
                    }
                }
                ++i;
            }
        }
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var NucleotideRingParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), NucleotideRingMeshParams);
function NucleotideRingVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(NucleotideRingParams),
        createGeometry: createNucleotideRingMesh,
        createLocationIterator: nucleotide_NucleotideLocationIterator.fromGroup,
        getLoci: getNucleotideElementLoci,
        eachLocation: eachNucleotideElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments);
        }
    }, materialId);
}
//# sourceMappingURL=nucleotide-ring-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/primitive/wedge.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var wedge_a = linear_algebra["Vec3"].zero(), wedge_b = linear_algebra["Vec3"].zero(), wedge_c = linear_algebra["Vec3"].zero(), wedge_d = linear_algebra["Vec3"].zero();
var wedge_points = Object(polygon["a" /* polygon */])(3, false);
/**
 * Create a prism with a triangular base
 */
function createWedge() {
    var builder = Object(primitive["a" /* PrimitiveBuilder */])(8);
    // create sides
    for (var i = 0; i < 3; ++i) {
        var ni = (i + 1) % 3;
        linear_algebra["Vec3"].set(wedge_a, wedge_points[i * 3], wedge_points[i * 3 + 1], -0.5);
        linear_algebra["Vec3"].set(wedge_b, wedge_points[ni * 3], wedge_points[ni * 3 + 1], -0.5);
        linear_algebra["Vec3"].set(wedge_c, wedge_points[ni * 3], wedge_points[ni * 3 + 1], 0.5);
        linear_algebra["Vec3"].set(wedge_d, wedge_points[i * 3], wedge_points[i * 3 + 1], 0.5);
        builder.add(wedge_a, wedge_b, wedge_c);
        builder.add(wedge_c, wedge_d, wedge_a);
    }
    // create bases
    linear_algebra["Vec3"].set(wedge_a, wedge_points[0], wedge_points[1], -0.5);
    linear_algebra["Vec3"].set(wedge_b, wedge_points[3], wedge_points[4], -0.5);
    linear_algebra["Vec3"].set(wedge_c, wedge_points[6], wedge_points[7], -0.5);
    builder.add(wedge_c, wedge_b, wedge_a);
    linear_algebra["Vec3"].set(wedge_a, wedge_points[0], wedge_points[1], 0.5);
    linear_algebra["Vec3"].set(wedge_b, wedge_points[3], wedge_points[4], 0.5);
    linear_algebra["Vec3"].set(wedge_c, wedge_points[6], wedge_points[7], 0.5);
    builder.add(wedge_a, wedge_b, wedge_c);
    return builder.getPrimitive();
}
var wedge;
function Wedge() {
    if (!wedge)
        wedge = createWedge();
    return wedge;
}
var wedgeCage;
function WedgeCage() {
    if (!wedgeCage)
        wedgeCage = Object(prism["f" /* PrismCage */])(wedge_points);
    return wedgeCage;
}
//# sourceMappingURL=wedge.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/polymer-direction-wedge.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var polymer_direction_wedge_t = linear_algebra["Mat4"].identity();
var polymer_direction_wedge_sVec = linear_algebra["Vec3"].zero();
var n0 = linear_algebra["Vec3"].zero();
var polymer_direction_wedge_n1 = linear_algebra["Vec3"].zero();
var upVec = linear_algebra["Vec3"].zero();
var depthFactor = 4;
var widthFactor = 4;
var heightFactor = 6;
var polymer_direction_wedge_wedge = Wedge();
var PolymerDirectionWedgeParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
};
var DefaultPolymerDirectionWedgeProps = param_definition["ParamDefinition"].getDefaultValues(PolymerDirectionWedgeParams);
function createPolymerDirectionWedgeMesh(ctx, unit, structure, theme, props, mesh) {
    var polymerElementCount = unit.polymerElements.length;
    if (!polymerElementCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor;
    var vertexCount = polymerElementCount * 24;
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 10, mesh);
    var linearSegments = 1;
    var state = createCurveSegmentState(linearSegments);
    var normalVectors = state.normalVectors, binormalVectors = state.binormalVectors;
    var i = 0;
    var polymerTraceIt = PolymerTraceIterator(unit, structure);
    while (polymerTraceIt.hasNext) {
        var v = polymerTraceIt.move();
        builderState.currentGroup = i;
        var isNucleicType = Object(types["isNucleic"])(v.moleculeType);
        var isSheet = types["SecondaryStructureType"].is(v.secStrucType, 4 /* Beta */);
        var tension = (isNucleicType || isSheet) ? 0.5 : 0.9;
        var shift = isNucleicType ? 0.3 : 0.5;
        interpolateCurveSegment(state, v, tension, shift);
        if ((isSheet && !v.secStrucLast) || !isSheet) {
            var size = theme.size.size(v.center) * sizeFactor;
            var depth = depthFactor * size;
            var width = widthFactor * size;
            var height = heightFactor * size;
            var vectors = isNucleicType ? binormalVectors : normalVectors;
            linear_algebra["Vec3"].fromArray(n0, vectors, 0);
            linear_algebra["Vec3"].fromArray(polymer_direction_wedge_n1, vectors, 3);
            linear_algebra["Vec3"].normalize(upVec, linear_algebra["Vec3"].add(upVec, n0, polymer_direction_wedge_n1));
            linear_algebra["Mat4"].targetTo(polymer_direction_wedge_t, v.p3, v.p1, upVec);
            linear_algebra["Mat4"].mul(polymer_direction_wedge_t, polymer_direction_wedge_t, linear_algebra["Mat4"].rotY90Z180);
            linear_algebra["Mat4"].scale(polymer_direction_wedge_t, polymer_direction_wedge_t, linear_algebra["Vec3"].set(polymer_direction_wedge_sVec, height, width, depth));
            linear_algebra["Mat4"].setTranslation(polymer_direction_wedge_t, v.p2);
            mesh_builder["a" /* MeshBuilder */].addPrimitive(builderState, polymer_direction_wedge_t, polymer_direction_wedge_wedge);
        }
        ++i;
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var PolymerDirectionParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), PolymerDirectionWedgeParams);
function PolymerDirectionVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(PolymerDirectionParams),
        createGeometry: createPolymerDirectionWedgeMesh,
        createLocationIterator: polymer_PolymerLocationIterator.fromGroup,
        getLoci: getPolymerElementLoci,
        eachLocation: eachPolymerElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor);
        }
    }, materialId);
}
//# sourceMappingURL=polymer-direction-wedge.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/polymer-gap-cylinder.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










// import { TriangularPyramid } from '../../../mol-geo/primitive/pyramid';
var polymer_gap_cylinder_segmentCount = 10;
var PolymerGapCylinderParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
    radialSegments: param_definition["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
};
var DefaultPolymerGapCylinderProps = param_definition["ParamDefinition"].getDefaultValues(PolymerGapCylinderParams);
// const triangularPyramid = TriangularPyramid()
// const t = Mat4.identity()
// const pd = Vec3.zero()
function createPolymerGapCylinderMesh(ctx, unit, structure, theme, props, mesh) {
    var polymerGapCount = unit.gapElements.length;
    if (!polymerGapCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor, radialSegments = props.radialSegments;
    var vertexCountEstimate = polymer_gap_cylinder_segmentCount * radialSegments * 2 * polymerGapCount * 2;
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCountEstimate, vertexCountEstimate / 10, mesh);
    var pos = unit.conformation.invariantPosition;
    var pA = linear_algebra["Vec3"].zero();
    var pB = linear_algebra["Vec3"].zero();
    var cylinderProps = {
        radiusTop: 1, radiusBottom: 1, topCap: true, bottomCap: true,
        radialSegments: radialSegments
    };
    var i = 0;
    var polymerGapIt = PolymerGapIterator(structure, unit);
    while (polymerGapIt.hasNext) {
        var _a = polymerGapIt.move(), centerA = _a.centerA, centerB = _a.centerB;
        if (centerA.element === centerB.element) {
            // TODO
            // builderState.currentGroup = i
            // pos(centerA.element, pA)
            // Vec3.add(pd, pA, Vec3.create(1, 0, 0))
            // Mat4.targetTo(t, pA, pd, Vec3.create(0, 1, 0))
            // Mat4.setTranslation(t, pA)
            // Mat4.scale(t, t, Vec3.create(0.7, 0.7, 2.5))
            // MeshBuilder.addPrimitive(builderState, t, triangularPyramid)
        }
        else {
            pos(centerA.element, pA);
            pos(centerB.element, pB);
            cylinderProps.radiusTop = cylinderProps.radiusBottom = theme.size.size(centerA) * sizeFactor;
            builderState.currentGroup = i;
            Object(cylinder["c" /* addFixedCountDashedCylinder */])(builderState, pA, pB, 0.5, polymer_gap_cylinder_segmentCount, cylinderProps);
            cylinderProps.radiusTop = cylinderProps.radiusBottom = theme.size.size(centerB) * sizeFactor;
            builderState.currentGroup = i + 1;
            Object(cylinder["c" /* addFixedCountDashedCylinder */])(builderState, pB, pA, 0.5, polymer_gap_cylinder_segmentCount, cylinderProps);
        }
        i += 2;
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var PolymerGapParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), PolymerGapCylinderParams);
function PolymerGapVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(PolymerGapParams),
        createGeometry: createPolymerGapCylinderMesh,
        createLocationIterator: polymer_PolymerGapLocationIterator.fromGroup,
        getLoci: getPolymerGapElementLoci,
        eachLocation: eachPolymerGapElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.radialSegments !== currentProps.radialSegments);
        }
    }, materialId);
}
//# sourceMappingURL=polymer-gap-cylinder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/sheet.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var tA = linear_algebra["Vec3"].zero();
var tB = linear_algebra["Vec3"].zero();
var tV = linear_algebra["Vec3"].zero();
var horizontalVector = linear_algebra["Vec3"].zero();
var verticalVector = linear_algebra["Vec3"].zero();
var verticalRightVector = linear_algebra["Vec3"].zero();
var verticalLeftVector = linear_algebra["Vec3"].zero();
var normalOffset = linear_algebra["Vec3"].zero();
var positionVector = linear_algebra["Vec3"].zero();
var normalVector = linear_algebra["Vec3"].zero();
var torsionVector = linear_algebra["Vec3"].zero();
var sheet_p1 = linear_algebra["Vec3"].zero();
var sheet_p2 = linear_algebra["Vec3"].zero();
var sheet_p3 = linear_algebra["Vec3"].zero();
var sheet_p4 = linear_algebra["Vec3"].zero();
function addCap(offset, state, controlPoints, normalVectors, binormalVectors, width, leftHeight, rightHeight) {
    var vertices = state.vertices, normals = state.normals, indices = state.indices;
    var vertexCount = vertices.elementCount;
    linear_algebra["Vec3"].fromArray(verticalLeftVector, normalVectors, offset);
    linear_algebra["Vec3"].scale(verticalLeftVector, verticalLeftVector, leftHeight);
    linear_algebra["Vec3"].fromArray(verticalRightVector, normalVectors, offset);
    linear_algebra["Vec3"].scale(verticalRightVector, verticalRightVector, rightHeight);
    linear_algebra["Vec3"].fromArray(horizontalVector, binormalVectors, offset);
    linear_algebra["Vec3"].scale(horizontalVector, horizontalVector, width);
    linear_algebra["Vec3"].fromArray(positionVector, controlPoints, offset);
    linear_algebra["Vec3"].add(sheet_p1, linear_algebra["Vec3"].add(sheet_p1, positionVector, horizontalVector), verticalRightVector);
    linear_algebra["Vec3"].sub(sheet_p2, linear_algebra["Vec3"].add(sheet_p2, positionVector, horizontalVector), verticalLeftVector);
    linear_algebra["Vec3"].sub(sheet_p3, linear_algebra["Vec3"].sub(sheet_p3, positionVector, horizontalVector), verticalLeftVector);
    linear_algebra["Vec3"].add(sheet_p4, linear_algebra["Vec3"].sub(sheet_p4, positionVector, horizontalVector), verticalRightVector);
    if (leftHeight < rightHeight) {
        util["a" /* ChunkedArray */].add3(vertices, sheet_p4[0], sheet_p4[1], sheet_p4[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p3[0], sheet_p3[1], sheet_p3[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p2[0], sheet_p2[1], sheet_p2[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p1[0], sheet_p1[1], sheet_p1[2]);
        linear_algebra["Vec3"].copy(verticalVector, verticalRightVector);
    }
    else {
        util["a" /* ChunkedArray */].add3(vertices, sheet_p1[0], sheet_p1[1], sheet_p1[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p2[0], sheet_p2[1], sheet_p2[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p3[0], sheet_p3[1], sheet_p3[2]);
        util["a" /* ChunkedArray */].add3(vertices, sheet_p4[0], sheet_p4[1], sheet_p4[2]);
        linear_algebra["Vec3"].copy(verticalVector, verticalLeftVector);
    }
    linear_algebra["Vec3"].cross(normalVector, horizontalVector, verticalVector);
    for (var i = 0; i < 4; ++i) {
        util["a" /* ChunkedArray */].add3(normals, normalVector[0], normalVector[1], normalVector[2]);
    }
    util["a" /* ChunkedArray */].add3(indices, vertexCount + 2, vertexCount + 1, vertexCount);
    util["a" /* ChunkedArray */].add3(indices, vertexCount, vertexCount + 3, vertexCount + 2);
}
/** set arrowHeight = 0 for no arrow */
function addSheet(state, controlPoints, normalVectors, binormalVectors, linearSegments, widthValues, heightValues, arrowHeight, startCap, endCap) {
    var currentGroup = state.currentGroup, vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups;
    var vertexCount = vertices.elementCount;
    var offsetLength = 0;
    if (arrowHeight > 0) {
        linear_algebra["Vec3"].fromArray(tA, controlPoints, 0);
        linear_algebra["Vec3"].fromArray(tB, controlPoints, linearSegments * 3);
        offsetLength = arrowHeight / linear_algebra["Vec3"].magnitude(linear_algebra["Vec3"].sub(tV, tB, tA));
    }
    for (var i = 0; i <= linearSegments; ++i) {
        var width = widthValues[i];
        var height = heightValues[i];
        var actualHeight = arrowHeight === 0 ? height : arrowHeight * (1 - i / linearSegments);
        var i3 = i * 3;
        linear_algebra["Vec3"].fromArray(verticalVector, normalVectors, i3);
        linear_algebra["Vec3"].scale(verticalVector, verticalVector, actualHeight);
        linear_algebra["Vec3"].fromArray(horizontalVector, binormalVectors, i3);
        linear_algebra["Vec3"].scale(horizontalVector, horizontalVector, width);
        if (arrowHeight > 0) {
            linear_algebra["Vec3"].fromArray(tA, normalVectors, i3);
            linear_algebra["Vec3"].fromArray(tB, binormalVectors, i3);
            linear_algebra["Vec3"].scale(normalOffset, linear_algebra["Vec3"].cross(normalOffset, tA, tB), offsetLength);
        }
        linear_algebra["Vec3"].fromArray(positionVector, controlPoints, i3);
        linear_algebra["Vec3"].fromArray(normalVector, normalVectors, i3);
        linear_algebra["Vec3"].fromArray(torsionVector, binormalVectors, i3);
        linear_algebra["Vec3"].add(tA, linear_algebra["Vec3"].add(tA, positionVector, horizontalVector), verticalVector);
        linear_algebra["Vec3"].copy(tB, normalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        linear_algebra["Vec3"].add(tA, linear_algebra["Vec3"].sub(tA, positionVector, horizontalVector), verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        // Vec3.add(tA, Vec3.sub(tA, positionVector, horizontalVector), verticalVector) // reuse tA
        linear_algebra["Vec3"].add(tB, linear_algebra["Vec3"].negate(tB, torsionVector), normalOffset);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        linear_algebra["Vec3"].sub(tA, linear_algebra["Vec3"].sub(tA, positionVector, horizontalVector), verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        // Vec3.sub(tA, Vec3.sub(tA, positionVector, horizontalVector), verticalVector) // reuse tA
        linear_algebra["Vec3"].negate(tB, normalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        linear_algebra["Vec3"].sub(tA, linear_algebra["Vec3"].add(tA, positionVector, horizontalVector), verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        // Vec3.sub(tA, Vec3.add(tA, positionVector, horizontalVector), verticalVector) // reuse tA
        linear_algebra["Vec3"].add(tB, torsionVector, normalOffset);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
        linear_algebra["Vec3"].add(tA, linear_algebra["Vec3"].add(tA, positionVector, horizontalVector), verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, tA[0], tA[1], tA[2]);
        util["a" /* ChunkedArray */].add3(normals, tB[0], tB[1], tB[2]);
    }
    for (var i = 0; i < linearSegments; ++i) {
        // the triangles are arranged such that opposing triangles of the sheet align
        // which prevents triangle intersection within tight curves
        for (var j = 0; j < 2; j++) {
            util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 8 + 2 * j, // a
            vertexCount + (i + 1) * 8 + 2 * j + 1, // c
            vertexCount + i * 8 + 2 * j + 1 // b
            );
            util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 8 + 2 * j, // a
            vertexCount + (i + 1) * 8 + 2 * j, // d
            vertexCount + (i + 1) * 8 + 2 * j + 1 // c
            );
        }
        for (var j = 2; j < 4; j++) {
            util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 8 + 2 * j, // a
            vertexCount + (i + 1) * 8 + 2 * j, // d
            vertexCount + i * 8 + 2 * j + 1);
            util["a" /* ChunkedArray */].add3(indices, vertexCount + (i + 1) * 8 + 2 * j, // d
            vertexCount + (i + 1) * 8 + 2 * j + 1, // c
            vertexCount + i * 8 + 2 * j + 1);
        }
    }
    if (startCap) {
        var width = widthValues[0];
        var height = heightValues[0];
        var h = arrowHeight === 0 ? height : arrowHeight;
        addCap(0, state, controlPoints, normalVectors, binormalVectors, width, h, h);
    }
    else if (arrowHeight > 0) {
        var width = widthValues[0];
        var height = heightValues[0];
        addCap(0, state, controlPoints, normalVectors, binormalVectors, width, arrowHeight, -height);
        addCap(0, state, controlPoints, normalVectors, binormalVectors, width, -arrowHeight, height);
    }
    if (endCap && arrowHeight === 0) {
        var width = widthValues[linearSegments];
        var height = heightValues[linearSegments];
        // use negative height to flip the direction the cap's triangles are facing
        addCap(linearSegments * 3, state, controlPoints, normalVectors, binormalVectors, width, -height, -height);
    }
    var addedVertexCount = (linearSegments + 1) * 8 +
        (startCap ? 4 : (arrowHeight > 0 ? 8 : 0)) +
        (endCap && arrowHeight === 0 ? 4 : 0);
    for (var i = 0, il = addedVertexCount; i < il; ++i)
        util["a" /* ChunkedArray */].add(groups, currentGroup);
}
//# sourceMappingURL=sheet.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/tube.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var tube_normalVector = linear_algebra["Vec3"].zero();
var surfacePoint = linear_algebra["Vec3"].zero();
var controlPoint = linear_algebra["Vec3"].zero();
var tube_u = linear_algebra["Vec3"].zero();
var tube_v = linear_algebra["Vec3"].zero();
function add2AndScale2(out, a, b, sa, sb) {
    out[0] = (a[0] * sa) + (b[0] * sb);
    out[1] = (a[1] * sa) + (b[1] * sb);
    out[2] = (a[2] * sa) + (b[2] * sb);
}
function add3AndScale2(out, a, b, c, sa, sb) {
    out[0] = (a[0] * sa) + (b[0] * sb) + c[0];
    out[1] = (a[1] * sa) + (b[1] * sb) + c[1];
    out[2] = (a[2] * sa) + (b[2] * sb) + c[2];
}
function addTube(state, controlPoints, normalVectors, binormalVectors, linearSegments, radialSegments, widthValues, heightValues, waveFactor, startCap, endCap) {
    var currentGroup = state.currentGroup, vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups;
    var vertexCount = vertices.elementCount;
    var di = 1 / linearSegments;
    for (var i = 0; i <= linearSegments; ++i) {
        var i3 = i * 3;
        linear_algebra["Vec3"].fromArray(tube_u, normalVectors, i3);
        linear_algebra["Vec3"].fromArray(tube_v, binormalVectors, i3);
        linear_algebra["Vec3"].fromArray(controlPoint, controlPoints, i3);
        var width = widthValues[i];
        var height = heightValues[i];
        var tt = di * i - 0.5;
        var ff = 1 + (waveFactor - 1) * (Math.cos(2 * Math.PI * tt) + 1);
        var w = ff * width, h = ff * height;
        for (var j = 0; j < radialSegments; ++j) {
            var t = 2 * Math.PI * j / radialSegments;
            add3AndScale2(surfacePoint, tube_u, tube_v, controlPoint, h * Math.cos(t), w * Math.sin(t));
            if (radialSegments === 2) {
                // add2AndScale2(normalVector, u, v, w * Math.cos(t), h * Math.sin(t))
                linear_algebra["Vec3"].copy(tube_normalVector, tube_v);
                linear_algebra["Vec3"].normalize(tube_normalVector, tube_normalVector);
                if (t !== 0 || i % 2 === 0)
                    linear_algebra["Vec3"].negate(tube_normalVector, tube_normalVector);
            }
            else {
                add2AndScale2(tube_normalVector, tube_u, tube_v, w * Math.cos(t), h * Math.sin(t));
            }
            linear_algebra["Vec3"].normalize(tube_normalVector, tube_normalVector);
            util["a" /* ChunkedArray */].add3(vertices, surfacePoint[0], surfacePoint[1], surfacePoint[2]);
            util["a" /* ChunkedArray */].add3(normals, tube_normalVector[0], tube_normalVector[1], tube_normalVector[2]);
        }
    }
    for (var i = 0; i < linearSegments; ++i) {
        for (var j = 0; j < radialSegments; ++j) {
            util["a" /* ChunkedArray */].add3(indices, vertexCount + i * radialSegments + (j + 1) % radialSegments, vertexCount + (i + 1) * radialSegments + (j + 1) % radialSegments, vertexCount + i * radialSegments + j);
            util["a" /* ChunkedArray */].add3(indices, vertexCount + (i + 1) * radialSegments + (j + 1) % radialSegments, vertexCount + (i + 1) * radialSegments + j, vertexCount + i * radialSegments + j);
        }
    }
    if (startCap) {
        var offset = 0;
        var centerVertex = vertices.elementCount;
        linear_algebra["Vec3"].fromArray(tube_u, normalVectors, offset);
        linear_algebra["Vec3"].fromArray(tube_v, binormalVectors, offset);
        linear_algebra["Vec3"].fromArray(controlPoint, controlPoints, offset);
        linear_algebra["Vec3"].cross(tube_normalVector, tube_v, tube_u);
        util["a" /* ChunkedArray */].add3(vertices, controlPoint[0], controlPoint[1], controlPoint[2]);
        util["a" /* ChunkedArray */].add3(normals, tube_normalVector[0], tube_normalVector[1], tube_normalVector[2]);
        var width = widthValues[0];
        var height = heightValues[0];
        vertexCount = vertices.elementCount;
        for (var i = 0; i < radialSegments; ++i) {
            var t = 2 * Math.PI * i / radialSegments;
            add3AndScale2(surfacePoint, tube_u, tube_v, controlPoint, height * Math.cos(t), width * Math.sin(t));
            util["a" /* ChunkedArray */].add3(vertices, surfacePoint[0], surfacePoint[1], surfacePoint[2]);
            util["a" /* ChunkedArray */].add3(normals, tube_normalVector[0], tube_normalVector[1], tube_normalVector[2]);
            util["a" /* ChunkedArray */].add3(indices, vertexCount + (i + 1) % radialSegments, vertexCount + i, centerVertex);
        }
    }
    if (endCap) {
        var offset = linearSegments * 3;
        var centerVertex = vertices.elementCount;
        linear_algebra["Vec3"].fromArray(tube_u, normalVectors, offset);
        linear_algebra["Vec3"].fromArray(tube_v, binormalVectors, offset);
        linear_algebra["Vec3"].fromArray(controlPoint, controlPoints, offset);
        linear_algebra["Vec3"].cross(tube_normalVector, tube_u, tube_v);
        util["a" /* ChunkedArray */].add3(vertices, controlPoint[0], controlPoint[1], controlPoint[2]);
        util["a" /* ChunkedArray */].add3(normals, tube_normalVector[0], tube_normalVector[1], tube_normalVector[2]);
        var width = widthValues[linearSegments];
        var height = heightValues[linearSegments];
        vertexCount = vertices.elementCount;
        for (var i = 0; i < radialSegments; ++i) {
            var t = 2 * Math.PI * i / radialSegments;
            add3AndScale2(surfacePoint, tube_u, tube_v, controlPoint, height * Math.cos(t), width * Math.sin(t));
            util["a" /* ChunkedArray */].add3(vertices, surfacePoint[0], surfacePoint[1], surfacePoint[2]);
            util["a" /* ChunkedArray */].add3(normals, tube_normalVector[0], tube_normalVector[1], tube_normalVector[2]);
            util["a" /* ChunkedArray */].add3(indices, vertexCount + i, vertexCount + (i + 1) % radialSegments, centerVertex);
        }
    }
    var addedVertexCount = (linearSegments + 1) * radialSegments + (startCap ? radialSegments + 1 : 0) + (endCap ? radialSegments + 1 : 0);
    util["a" /* ChunkedArray */].addRepeat(groups, addedVertexCount, currentGroup);
}
//# sourceMappingURL=tube.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/ribbon.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */


var ribbon_tA = linear_algebra["Vec3"].zero();
var ribbon_tB = linear_algebra["Vec3"].zero();
var ribbon_tV = linear_algebra["Vec3"].zero();
var ribbon_horizontalVector = linear_algebra["Vec3"].zero();
var ribbon_verticalVector = linear_algebra["Vec3"].zero();
var ribbon_normalOffset = linear_algebra["Vec3"].zero();
var ribbon_positionVector = linear_algebra["Vec3"].zero();
var ribbon_normalVector = linear_algebra["Vec3"].zero();
var ribbon_torsionVector = linear_algebra["Vec3"].zero();
/** set arrowHeight = 0 for no arrow */
function addRibbon(state, controlPoints, normalVectors, binormalVectors, linearSegments, widthValues, heightValues, arrowHeight) {
    var currentGroup = state.currentGroup, vertices = state.vertices, normals = state.normals, indices = state.indices, groups = state.groups;
    var vertexCount = vertices.elementCount;
    var offsetLength = 0;
    if (arrowHeight > 0) {
        linear_algebra["Vec3"].fromArray(ribbon_tA, controlPoints, 0);
        linear_algebra["Vec3"].fromArray(ribbon_tB, controlPoints, linearSegments * 3);
        offsetLength = arrowHeight / linear_algebra["Vec3"].magnitude(linear_algebra["Vec3"].sub(ribbon_tV, ribbon_tB, ribbon_tA));
    }
    for (var i = 0; i <= linearSegments; ++i) {
        var width = widthValues[i];
        var height = heightValues[i];
        var actualHeight = arrowHeight === 0 ? height : arrowHeight * (1 - i / linearSegments);
        var i3 = i * 3;
        linear_algebra["Vec3"].fromArray(ribbon_verticalVector, normalVectors, i3);
        linear_algebra["Vec3"].scale(ribbon_verticalVector, ribbon_verticalVector, actualHeight);
        linear_algebra["Vec3"].fromArray(ribbon_horizontalVector, binormalVectors, i3);
        linear_algebra["Vec3"].scale(ribbon_horizontalVector, ribbon_horizontalVector, width);
        if (arrowHeight > 0) {
            linear_algebra["Vec3"].fromArray(ribbon_tA, normalVectors, i3);
            linear_algebra["Vec3"].fromArray(ribbon_tB, binormalVectors, i3);
            linear_algebra["Vec3"].scale(ribbon_normalOffset, linear_algebra["Vec3"].cross(ribbon_normalOffset, ribbon_tA, ribbon_tB), offsetLength);
        }
        linear_algebra["Vec3"].fromArray(ribbon_positionVector, controlPoints, i3);
        linear_algebra["Vec3"].fromArray(ribbon_normalVector, normalVectors, i3);
        linear_algebra["Vec3"].fromArray(ribbon_torsionVector, binormalVectors, i3);
        linear_algebra["Vec3"].add(ribbon_tA, ribbon_positionVector, ribbon_verticalVector);
        linear_algebra["Vec3"].negate(ribbon_tB, ribbon_torsionVector);
        util["a" /* ChunkedArray */].add3(vertices, ribbon_tA[0], ribbon_tA[1], ribbon_tA[2]);
        util["a" /* ChunkedArray */].add3(normals, ribbon_tB[0], ribbon_tB[1], ribbon_tB[2]);
        linear_algebra["Vec3"].sub(ribbon_tA, ribbon_positionVector, ribbon_verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, ribbon_tA[0], ribbon_tA[1], ribbon_tA[2]);
        util["a" /* ChunkedArray */].add3(normals, ribbon_tB[0], ribbon_tB[1], ribbon_tB[2]);
        linear_algebra["Vec3"].add(ribbon_tA, ribbon_positionVector, ribbon_verticalVector);
        linear_algebra["Vec3"].copy(ribbon_tB, ribbon_torsionVector);
        util["a" /* ChunkedArray */].add3(vertices, ribbon_tA[0], ribbon_tA[1], ribbon_tA[2]);
        util["a" /* ChunkedArray */].add3(normals, ribbon_tB[0], ribbon_tB[1], ribbon_tB[2]);
        linear_algebra["Vec3"].sub(ribbon_tA, ribbon_positionVector, ribbon_verticalVector);
        util["a" /* ChunkedArray */].add3(vertices, ribbon_tA[0], ribbon_tA[1], ribbon_tA[2]);
        util["a" /* ChunkedArray */].add3(normals, ribbon_tB[0], ribbon_tB[1], ribbon_tB[2]);
    }
    for (var i = 0; i < linearSegments; ++i) {
        util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 4, vertexCount + (i + 1) * 4 + 1, vertexCount + i * 4 + 1);
        util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 4, vertexCount + (i + 1) * 4, vertexCount + (i + 1) * 4 + 1);
        util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 4 + 2 + 1, vertexCount + (i + 1) * 4 + 2 + 1, vertexCount + i * 4 + 2);
        util["a" /* ChunkedArray */].add3(indices, vertexCount + i * 4 + 2, vertexCount + (i + 1) * 4 + 2 + 1, vertexCount + (i + 1) * 4 + 2);
    }
    var addedVertexCount = (linearSegments + 1) * 4;
    for (var i = 0, il = addedVertexCount; i < il; ++i)
        util["a" /* ChunkedArray */].add(groups, currentGroup);
}
//# sourceMappingURL=ribbon.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/polymer-trace-mesh.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var PolymerTraceMeshParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
    aspectRatio: param_definition["ParamDefinition"].Numeric(5, { min: 0.1, max: 10, step: 0.1 }),
    arrowFactor: param_definition["ParamDefinition"].Numeric(1.5, { min: 0, max: 3, step: 0.1 }),
    detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
    linearSegments: param_definition["ParamDefinition"].Numeric(8, { min: 1, max: 48, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
    radialSegments: param_definition["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, base["a" /* BaseGeometry */].CustomQualityParamInfo)
};
var DefaultPolymerTraceMeshProps = param_definition["ParamDefinition"].getDefaultValues(PolymerTraceMeshParams);
var tmpV1 = Object(linear_algebra["Vec3"])();
function createPolymerTraceMesh(ctx, unit, structure, theme, props, mesh) {
    var _a, _b, _c;
    var polymerElementCount = unit.polymerElements.length;
    if (!polymerElementCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor, detail = props.detail, linearSegments = props.linearSegments, radialSegments = props.radialSegments, aspectRatio = props.aspectRatio, arrowFactor = props.arrowFactor;
    var vertexCount = linearSegments * radialSegments * polymerElementCount + (radialSegments + 1) * polymerElementCount * 2;
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 10, mesh);
    var isCoarse = mol_model_structure["Unit"].isCoarse(unit);
    var state = createCurveSegmentState(linearSegments);
    var curvePoints = state.curvePoints, normalVectors = state.normalVectors, binormalVectors = state.binormalVectors, widthValues = state.widthValues, heightValues = state.heightValues;
    var i = 0;
    var polymerTraceIt = PolymerTraceIterator(unit, structure);
    while (polymerTraceIt.hasNext) {
        var v = polymerTraceIt.move();
        builderState.currentGroup = i;
        var isNucleicType = Object(types["isNucleic"])(v.moleculeType);
        var isSheet = types["SecondaryStructureType"].is(v.secStrucType, 4 /* Beta */);
        var isHelix = types["SecondaryStructureType"].is(v.secStrucType, 2 /* Helix */);
        var tension = isHelix ? HelixTension : StandardTension;
        var shift = isNucleicType ? NucleicShift : StandardShift;
        interpolateCurveSegment(state, v, tension, shift);
        var w0 = theme.size.size(v.centerPrev) * sizeFactor;
        var w1 = theme.size.size(v.center) * sizeFactor;
        var w2 = theme.size.size(v.centerNext) * sizeFactor;
        if (isCoarse) {
            w0 *= aspectRatio / 2;
            w1 *= aspectRatio / 2;
            w2 *= aspectRatio / 2;
        }
        var startCap = v.secStrucFirst || v.coarseBackboneFirst || v.first;
        var endCap = v.secStrucLast || v.coarseBackboneLast || v.last;
        var segmentCount = linearSegments;
        if (v.initial) {
            segmentCount = Math.max(Math.round(linearSegments * shift), 1);
            var offset = linearSegments - segmentCount;
            curvePoints.copyWithin(0, offset * 3);
            binormalVectors.copyWithin(0, offset * 3);
            normalVectors.copyWithin(0, offset * 3);
            linear_algebra["Vec3"].fromArray(tmpV1, curvePoints, 3);
            linear_algebra["Vec3"].normalize(tmpV1, linear_algebra["Vec3"].sub(tmpV1, v.p2, tmpV1));
            linear_algebra["Vec3"].scaleAndAdd(tmpV1, v.p2, tmpV1, w1 * OverhangFactor);
            linear_algebra["Vec3"].toArray(tmpV1, curvePoints, 0);
        }
        else if (v.final) {
            segmentCount = Math.max(Math.round(linearSegments * (1 - shift)), 1);
            linear_algebra["Vec3"].fromArray(tmpV1, curvePoints, segmentCount * 3 - 3);
            linear_algebra["Vec3"].normalize(tmpV1, linear_algebra["Vec3"].sub(tmpV1, v.p2, tmpV1));
            linear_algebra["Vec3"].scaleAndAdd(tmpV1, v.p2, tmpV1, w1 * OverhangFactor);
            linear_algebra["Vec3"].toArray(tmpV1, curvePoints, segmentCount * 3);
        }
        if (v.initial === true && v.final === true) {
            Object(builder_sphere["a" /* addSphere */])(builderState, v.p2, w1 * 2, detail);
        }
        else if (isSheet) {
            var h0 = w0 * aspectRatio;
            var h1 = w1 * aspectRatio;
            var h2 = w2 * aspectRatio;
            var arrowHeight = v.secStrucLast ? h1 * arrowFactor : 0;
            interpolateSizes(state, w0, w1, w2, h0, h1, h2, shift);
            if (radialSegments === 2) {
                addRibbon(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, arrowHeight);
            }
            else {
                addSheet(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, arrowHeight, startCap, endCap);
            }
        }
        else {
            var h0 = void 0, h1 = void 0, h2 = void 0;
            if (isHelix && !v.isCoarseBackbone) {
                h0 = w0 * aspectRatio;
                h1 = w1 * aspectRatio;
                h2 = w2 * aspectRatio;
            }
            else if (isNucleicType && !v.isCoarseBackbone) {
                h0 = w0 * aspectRatio;
                h1 = w1 * aspectRatio;
                h2 = w2 * aspectRatio;
                _a = [h0, w0], w0 = _a[0], h0 = _a[1];
                _b = [h1, w1], w1 = _b[0], h1 = _b[1];
                _c = [h2, w2], w2 = _c[0], h2 = _c[1];
            }
            else {
                h0 = w0;
                h1 = w1;
                h2 = w2;
            }
            interpolateSizes(state, w0, w1, w2, h0, h1, h2, shift);
            if (radialSegments === 2) {
                if (isNucleicType && !v.isCoarseBackbone) {
                    // TODO find a cleaner way to swap normal and binormal for nucleic types
                    for (var i_1 = 0, il = binormalVectors.length; i_1 < il; i_1++)
                        binormalVectors[i_1] *= -1;
                    addRibbon(builderState, curvePoints, binormalVectors, normalVectors, segmentCount, heightValues, widthValues, 0);
                }
                else {
                    addRibbon(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, 0);
                }
            }
            else if (radialSegments === 4) {
                addSheet(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, 0, startCap, endCap);
            }
            else {
                addTube(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, radialSegments, widthValues, heightValues, 1, startCap, endCap);
            }
        }
        ++i;
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var PolymerTraceParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), PolymerTraceMeshParams);
function PolymerTraceVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(PolymerTraceParams),
        createGeometry: createPolymerTraceMesh,
        createLocationIterator: polymer_PolymerLocationIterator.fromGroup,
        getLoci: getPolymerElementLoci,
        eachLocation: eachPolymerElement,
        setUpdateState: function (state, newProps, currentProps, newTheme, currentTheme, newStructureGroup, currentStructureGroup) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail ||
                newProps.linearSegments !== currentProps.linearSegments ||
                newProps.radialSegments !== currentProps.radialSegments ||
                newProps.aspectRatio !== currentProps.aspectRatio ||
                newProps.arrowFactor !== currentProps.arrowFactor);
            var secondaryStructureHash = secondary_structure["a" /* SecondaryStructureProvider */].get(newStructureGroup.structure).version;
            if (state.info.secondaryStructureHash !== secondaryStructureHash) {
                state.createGeometry = true;
                state.info.secondaryStructureHash = secondaryStructureHash;
            }
        }
    }, materialId);
}
//# sourceMappingURL=polymer-trace-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/cartoon.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












var CartoonVisuals = {
    'polymer-trace': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Polymer trace mesh', ctx, getParams, PolymerTraceVisual); },
    'polymer-gap': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Polymer gap cylinder', ctx, getParams, PolymerGapVisual); },
    'nucleotide-block': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Nucleotide block mesh', ctx, getParams, NucleotideBlockVisual); },
    'nucleotide-ring': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Nucleotide ring mesh', ctx, getParams, NucleotideRingVisual); },
    'direction-wedge': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Polymer direction wedge', ctx, getParams, PolymerDirectionVisual); }
};
var CartoonParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, PolymerTraceParams), PolymerGapParams), NucleotideBlockParams), NucleotideRingParams), PolymerDirectionParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }), visuals: param_definition["ParamDefinition"].MultiSelect(['polymer-trace', 'polymer-gap', 'nucleotide-block'], param_definition["ParamDefinition"].objectToOptions(CartoonVisuals)) });
function getCartoonParams(ctx, structure) {
    var params = param_definition["ParamDefinition"].clone(CartoonParams);
    var hasNucleotides = false;
    var hasGaps = false;
    structure.units.forEach(function (u) {
        if (!hasNucleotides && mol_model_structure["Unit"].isAtomic(u) && u.nucleotideElements.length)
            hasNucleotides = true;
        if (!hasGaps && u.gapElements.length)
            hasGaps = true;
    });
    params.visuals.defaultValue = ['polymer-trace'];
    if (hasNucleotides)
        params.visuals.defaultValue.push('nucleotide-block');
    if (hasGaps)
        params.visuals.defaultValue.push('polymer-gap');
    return params;
}
function CartoonRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Cartoon', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], CartoonVisuals);
}
var CartoonRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'cartoon',
    label: 'Cartoon',
    description: 'Displays ribbons, planks, tubes smoothly following the trace atoms of polymers.',
    factory: CartoonRepresentation,
    getParams: getCartoonParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(CartoonParams),
    defaultColorTheme: { name: 'chain-id' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.polymerResidueCount > 0; },
    ensureCustomProperties: {
        attach: function (ctx, structure) { return secondary_structure["a" /* SecondaryStructureProvider */].attach(ctx, structure, void 0, true); },
        detach: function (data) { return secondary_structure["a" /* SecondaryStructureProvider */].ref(data, false); }
    }
});
//# sourceMappingURL=cartoon.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/mesh/builder/ellipsoid.js
var ellipsoid = __webpack_require__(309);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/anisotropic.js
var anisotropic = __webpack_require__(211);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d/common.js
var _3d_common = __webpack_require__(82);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/ellipsoid-mesh.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















var EllipsoidMeshParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(1, { min: 0, max: 10, step: 0.1 }), detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function EllipsoidMeshVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(EllipsoidMeshParams),
        createGeometry: createEllipsoidMesh,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens);
        }
    }, materialId);
}
function createEllipsoidMesh(ctx, unit, structure, theme, props, mesh) {
    var detail = props.detail, sizeFactor = props.sizeFactor;
    var elements = unit.elements, model = unit.model;
    var elementCount = elements.length;
    var vertexCount = elementCount * Object(primitive_sphere["b" /* sphereVertexCount */])(detail);
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 2, mesh);
    var atomSiteAnisotrop = anisotropic["a" /* AtomSiteAnisotrop */].Provider.get(model);
    if (!atomSiteAnisotrop)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var v = Object(linear_algebra["Vec3"])();
    var mat = Object(linear_algebra["Mat3"])();
    var eigvals = Object(linear_algebra["Vec3"])();
    var eigvec1 = Object(linear_algebra["Vec3"])();
    var eigvec2 = Object(linear_algebra["Vec3"])();
    var elementToAnsiotrop = atomSiteAnisotrop.elementToAnsiotrop, data = atomSiteAnisotrop.data;
    var U = data.U;
    var space = data._schema.U.space;
    var pos = unit.conformation.invariantPosition;
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    l.unit = unit;
    for (var i = 0; i < elementCount; i++) {
        var ei = elements[i];
        var ai = elementToAnsiotrop[ei];
        if (ai === -1)
            continue;
        if (props.ignoreHydrogens && Object(common["k" /* isHydrogen */])(unit, ei))
            continue;
        l.element = ei;
        pos(ei, v);
        builderState.currentGroup = i;
        linear_algebra["Tensor"].toMat3(mat, space, U.value(ai));
        linear_algebra["Mat3"].symmtricFromLower(mat, mat);
        linear_algebra["Mat3"].symmetricEigenvalues(eigvals, mat);
        linear_algebra["Mat3"].eigenvector(eigvec1, mat, eigvals[1]);
        linear_algebra["Mat3"].eigenvector(eigvec2, mat, eigvals[2]);
        for (var j = 0; j < 3; ++j) {
            // show 50% probability surface, needs sqrt as U matrix is in angstrom-squared
            // take abs of eigenvalue to avoid reflection
            // multiply by given size-factor
            eigvals[j] = sizeFactor * 1.5958 * Math.sqrt(Math.abs(eigvals[j]));
        }
        if (Object(_3d_common["b" /* equalEps */])(eigvals[0], eigvals[1], linear_algebra["EPSILON"]) && Object(_3d_common["b" /* equalEps */])(eigvals[1], eigvals[2], linear_algebra["EPSILON"])) {
            Object(builder_sphere["a" /* addSphere */])(builderState, v, eigvals[0], detail);
        }
        else {
            Object(ellipsoid["a" /* addEllipsoid */])(builderState, v, eigvec2, eigvec1, eigvals, detail);
        }
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
//# sourceMappingURL=ellipsoid-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/ellipsoid.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var EllipsoidVisuals = {
    'ellipsoid-mesh': function (ctx, getParams) { return Object(structure_representation["d" /* UnitsRepresentation */])('Ellipsoid Mesh', ctx, getParams, EllipsoidMeshVisual); },
    'intra-bond': function (ctx, getParams) { return Object(structure_representation["d" /* UnitsRepresentation */])('Intra-unit bond cylinder', ctx, getParams, IntraUnitBondCylinderVisual); },
    'inter-bond': function (ctx, getParams) { return Object(structure_representation["a" /* ComplexRepresentation */])('Inter-unit bond cylinder', ctx, getParams, InterUnitBondCylinderVisual); },
};
var EllipsoidParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, EllipsoidMeshParams), IntraUnitBondCylinderParams), InterUnitBondCylinderParams), { unitKinds: Object(structure_params["i" /* getUnitKindsParam */])(['atomic']), sizeFactor: param_definition["ParamDefinition"].Numeric(1, { min: 0.01, max: 10, step: 0.01 }), sizeAspectRatio: param_definition["ParamDefinition"].Numeric(0.1, { min: 0.01, max: 3, step: 0.01 }), linkCap: param_definition["ParamDefinition"].Boolean(true), visuals: param_definition["ParamDefinition"].MultiSelect(['ellipsoid-mesh', 'intra-bond', 'inter-bond'], param_definition["ParamDefinition"].objectToOptions(EllipsoidVisuals)) });
function getEllipsoidParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(EllipsoidParams);
}
function EllipsoidRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Ellipsoid', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], EllipsoidVisuals);
}
var EllipsoidRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'ellipsoid',
    label: 'Ellipsoid',
    description: 'Displays anisotropic displacement ellipsoids of atomic elements plus bonds as cylinders.',
    factory: EllipsoidRepresentation,
    getParams: getEllipsoidParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(EllipsoidParams),
    defaultColorTheme: { name: 'element-symbol' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0 && structure.models.some(function (m) { return anisotropic["a" /* AtomSiteAnisotrop */].Provider.isApplicable(m); }); }
});
//# sourceMappingURL=ellipsoid.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/gaussian-density/cpu.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




function GaussianDensityCPU(ctx, position, box, radius, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        function accumulateRange(begI, endI) {
            for (var i = begI; i < endI; ++i) {
                var j = mol_data_int["OrderedSet"].getAt(indices, i);
                var vx = x[j], vy = y[j], vz = z[j];
                var rad = radii[i];
                var rSq = rad * rad;
                var rSqInv = 1 / rSq;
                var r2 = rad * 2;
                var r2sq = r2 * r2;
                // Number of grid points, round this up...
                var ng = Math.ceil(r2 * scaleFactor);
                // Center of the atom, mapped to grid points (take floor)
                var iax = Math.floor(scaleFactor * (vx - min[0]));
                var iay = Math.floor(scaleFactor * (vy - min[1]));
                var iaz = Math.floor(scaleFactor * (vz - min[2]));
                // Extents of grid to consider for this atom
                var begX = Math.max(0, iax - ng);
                var begY = Math.max(0, iay - ng);
                var begZ = Math.max(0, iaz - ng);
                // Add two to these points:
                // - iax are floor'd values so this ensures coverage
                // - these are loop limits (exclusive)
                var endX = Math.min(dimX, iax + ng + 2);
                var endY = Math.min(dimY, iay + ng + 2);
                var endZ = Math.min(dimZ, iaz + ng + 2);
                for (var xi = begX; xi < endX; ++xi) {
                    var dx = gridx[xi] - vx;
                    var xIdx = xi * iuv;
                    for (var yi = begY; yi < endY; ++yi) {
                        var dy = gridy[yi] - vy;
                        var dxySq = dx * dx + dy * dy;
                        var xyIdx = yi * iu + xIdx;
                        for (var zi = begZ; zi < endZ; ++zi) {
                            var dz = gridz[zi] - vz;
                            var dSq = dxySq + dz * dz;
                            if (dSq <= r2sq) {
                                var dens = Math.exp(-alpha * (dSq * rSqInv));
                                var idx = zi + xyIdx;
                                data[idx] += dens;
                                if (dens > densData[idx]) {
                                    densData[idx] = dens;
                                    idData[idx] = id ? id[i] : i;
                                }
                            }
                        }
                    }
                }
            }
        }
        function accumulate() {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var i;
                return Object(tslib_es6["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            i = 0;
                            _a.label = 1;
                        case 1:
                            if (!(i < n)) return [3 /*break*/, 4];
                            accumulateRange(i, Math.min(i + updateChunk, n));
                            if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                            return [4 /*yield*/, ctx.update({ message: 'filling density grid', current: i, max: n })];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            i += updateChunk;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        }
        var resolution, radiusOffset, smoothness, scaleFactor, indices, x, y, z, id, n, radii, maxRadius, i, r, pad, expandedBox, min, scaledBox, dim, space, data, field, idData, idField, dimX, dimY, dimZ, iu, iv, iuv, gridx, gridy, gridz, densData, alpha, updateChunk, transform;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    resolution = props.resolution, radiusOffset = props.radiusOffset, smoothness = props.smoothness;
                    scaleFactor = 1 / resolution;
                    indices = position.indices, x = position.x, y = position.y, z = position.z, id = position.id;
                    n = mol_data_int["OrderedSet"].size(indices);
                    radii = new Float32Array(n);
                    maxRadius = 0;
                    for (i = 0; i < n; ++i) {
                        r = radius(mol_data_int["OrderedSet"].getAt(indices, i)) + radiusOffset;
                        if (maxRadius < r)
                            maxRadius = r;
                        radii[i] = r;
                    }
                    pad = maxRadius * 2 + resolution;
                    expandedBox = geometry["b" /* Box3D */].expand(Object(geometry["b" /* Box3D */])(), box, linear_algebra["Vec3"].create(pad, pad, pad));
                    min = expandedBox.min;
                    scaledBox = geometry["b" /* Box3D */].scale(Object(geometry["b" /* Box3D */])(), expandedBox, scaleFactor);
                    dim = geometry["b" /* Box3D */].size(Object(linear_algebra["Vec3"])(), scaledBox);
                    linear_algebra["Vec3"].ceil(dim, dim);
                    space = linear_algebra["Tensor"].Space(dim, [0, 1, 2], Float32Array);
                    data = space.create();
                    field = linear_algebra["Tensor"].create(space, data);
                    idData = space.create();
                    idData.fill(-1);
                    idField = linear_algebra["Tensor"].create(space, idData);
                    dimX = dim[0], dimY = dim[1], dimZ = dim[2];
                    iu = dimZ, iv = dimY, iuv = iu * iv;
                    gridx = Object(geometry["i" /* fillGridDim */])(dim[0], min[0], resolution);
                    gridy = Object(geometry["i" /* fillGridDim */])(dim[1], min[1], resolution);
                    gridz = Object(geometry["i" /* fillGridDim */])(dim[2], min[2], resolution);
                    densData = space.create();
                    alpha = smoothness;
                    updateChunk = Math.ceil(100000 / ((Math.pow(Math.pow(maxRadius, 3), 3) * scaleFactor)));
                    // console.time('gaussian density cpu')
                    return [4 /*yield*/, accumulate()];
                case 1:
                    // console.time('gaussian density cpu')
                    _a.sent();
                    transform = linear_algebra["Mat4"].identity();
                    linear_algebra["Mat4"].fromScaling(transform, linear_algebra["Vec3"].create(resolution, resolution, resolution));
                    linear_algebra["Mat4"].setTranslation(transform, expandedBox.min);
                    return [2 /*return*/, { field: field, idField: idField, transform: transform }];
            }
        });
    });
}
//# sourceMappingURL=cpu.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/geometry/gaussian-density/gpu.js + 2 modules
var gpu = __webpack_require__(247);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/gaussian-density.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




// import { GaussianDensityGPU, GaussianDensityTexture } from './gaussian-density/gpu';
var GaussianDensityGPU = typeof document !== 'undefined'
    ? __webpack_require__(247).GaussianDensityGPU
    : void 0;
var GaussianDensityTexture = typeof document !== 'undefined'
    ? __webpack_require__(247).GaussianDensityTexture
    : void 0;
var DefaultGaussianDensityGPUProps = {
    resolution: 1,
    radiusOffset: 0,
    smoothness: 1.5,
};
var DefaultGaussianDensityProps = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, DefaultGaussianDensityGPUProps), { useGpu: true });
function computeGaussianDensity(position, box, radius, props, webgl) {
    var _this = this;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, GaussianDensity(ctx, position, box, radius, props, webgl)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
function GaussianDensity(ctx, position, box, radius, props, webgl) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!props.useGpu) return [3 /*break*/, 1];
                    if (!GaussianDensityGPU)
                        throw 'GPU computation not supported on this platform';
                    if (!webgl)
                        throw 'No WebGL context provided';
                    return [2 /*return*/, GaussianDensityGPU(position, box, radius, props, webgl)];
                case 1: return [4 /*yield*/, GaussianDensityCPU(ctx, position, box, radius, props)];
                case 2: return [2 /*return*/, _a.sent()];
            }
        });
    });
}
function computeGaussianDensityTexture(position, box, radius, props, webgl, texture) {
    return _computeGaussianDensityTexture(webgl.isWebGL2 ? '3d' : '2d', position, box, radius, props, webgl, texture);
}
function computeGaussianDensityTexture2d(position, box, radius, props, webgl, texture) {
    return _computeGaussianDensityTexture('2d', position, box, radius, props, webgl, texture);
}
function computeGaussianDensityTexture3d(position, box, radius, props, webgl, texture) {
    return _computeGaussianDensityTexture('2d', position, box, radius, props, webgl, texture);
}
function _computeGaussianDensityTexture(type, position, box, radius, props, webgl, texture) {
    var _this = this;
    if (!GaussianDensityTexture)
        throw 'GPU computation not supported on this platform';
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, type === '2d' ?
                    Object(gpu["GaussianDensityTexture2d"])(webgl, position, box, radius, props, texture) :
                    Object(gpu["GaussianDensityTexture3d"])(webgl, position, box, radius, props, texture)];
        });
    }); });
}
//# sourceMappingURL=gaussian-density.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/gaussian.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var SharedGaussianDensityParams = Object(tslib_es6["__assign"])({ resolution: param_definition["ParamDefinition"].Numeric(1, { min: 0.1, max: 20, step: 0.1 }, Object(tslib_es6["__assign"])({ description: 'Grid resolution/cell spacing.' }, base["a" /* BaseGeometry */].CustomQualityParamInfo)), radiusOffset: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 10, step: 0.1 }, { description: 'Extra/offset radius added to the atoms/coarse elements for gaussian calculation. Useful to create coarse, low resolution surfaces.' }), smoothness: param_definition["ParamDefinition"].Numeric(1.5, { min: 0.5, max: 2.5, step: 0.1 }, { description: 'Smoothness of the gausian surface, lower is smoother.' }) }, common["a" /* CommonSurfaceParams */]);
var GaussianDensityParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, SharedGaussianDensityParams), { useGpu: param_definition["ParamDefinition"].Boolean(false) });
var gaussian_DefaultGaussianDensityProps = param_definition["ParamDefinition"].getDefaultValues(GaussianDensityParams);
var GaussianDensityTextureParams = Object(tslib_es6["__assign"])({}, SharedGaussianDensityParams);
var DefaultGaussianDensityTextureProps = param_definition["ParamDefinition"].getDefaultValues(GaussianDensityTextureParams);
//
function computeUnitGaussianDensity(structure, unit, props, webgl) {
    var _this = this;
    var box = unit.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = Object(common["i" /* getUnitConformationAndRadius */])(structure, unit, p), position = _a.position, radius = _a.radius;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, GaussianDensity(ctx, position, box, radius, p, webgl)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
function computeUnitGaussianDensityTexture(structure, unit, props, webgl, texture) {
    var _this = this;
    var box = unit.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = Object(common["i" /* getUnitConformationAndRadius */])(structure, unit, p), position = _a.position, radius = _a.radius;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, Object(gpu["GaussianDensityTexture"])(webgl, position, box, radius, p, texture)];
        });
    }); });
}
function computeUnitGaussianDensityTexture2d(structure, unit, props, webgl, texture) {
    var _this = this;
    var box = unit.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = Object(common["i" /* getUnitConformationAndRadius */])(structure, unit, p), position = _a.position, radius = _a.radius;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, Object(gpu["GaussianDensityTexture2d"])(webgl, position, box, radius, p, texture)];
        });
    }); });
}
//
function computeStructureGaussianDensity(structure, props, webgl) {
    var _this = this;
    var box = structure.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = Object(common["h" /* getStructureConformationAndRadius */])(structure, props.ignoreHydrogens, props.traceOnly), position = _a.position, radius = _a.radius;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, GaussianDensity(ctx, position, box, radius, p, webgl)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
function computeStructureGaussianDensityTexture(structure, props, webgl, texture) {
    var _this = this;
    var box = structure.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = Object(common["h" /* getStructureConformationAndRadius */])(structure, props.ignoreHydrogens, props.traceOnly), position = _a.position, radius = _a.radius;
    return mol_task["b" /* Task */].create('Gaussian Density', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, Object(gpu["GaussianDensityTexture"])(webgl, position, box, radius, p, texture)];
        });
    }); });
}
//# sourceMappingURL=gaussian.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/marching-cubes/algorithm.js + 1 modules
var algorithm = __webpack_require__(210);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/texture-mesh/texture-mesh.js
var texture_mesh = __webpack_require__(259);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable.js
var mol_gl_renderable = __webpack_require__(98);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/webgl/render-item.js
var render_item = __webpack_require__(99);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/schema.js
var renderable_schema = __webpack_require__(17);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader-code.js + 40 modules
var shader_code = __webpack_require__(92);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/compute/util.js
var compute_util = __webpack_require__(148);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/util/marching-cubes/tables.js
var tables = __webpack_require__(187);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/renderable/util.js
var renderable_util = __webpack_require__(53);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/compute/marching-cubes/tables.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var TriCount;
function getTriCount() {
    if (TriCount !== undefined)
        return TriCount;
    TriCount = Object(renderable_util["c" /* createTextureImage */])(16 * 16, 1, Uint8Array);
    var array = TriCount.array;
    for (var i = 0, il = tables["e" /* TriTable */].length; i < il; ++i) {
        array[i] = tables["e" /* TriTable */][i].length / 3;
    }
    return TriCount;
}
var TriIndices;
function getTriIndices() {
    if (TriIndices !== undefined)
        return TriIndices;
    TriIndices = Object(renderable_util["c" /* createTextureImage */])(64 * 64, 1, Uint8Array);
    var array = TriIndices.array;
    for (var i = 0, il = tables["e" /* TriTable */].length; i < il; ++i) {
        for (var j = 0; j < 16; ++j) {
            if (j < tables["e" /* TriTable */][i].length) {
                array[i * 16 + j] = tables["e" /* TriTable */][i][j];
            }
            else {
                array[i * 16 + j] = 255;
            }
        }
    }
    return TriIndices;
}
//# sourceMappingURL=tables.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-gl/shader/quad.vert.js
var quad_vert = __webpack_require__(205);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/marching-cubes/active-voxels.frag.js
/* harmony default export */ var active_voxels_frag = ("\nprecision highp float;\nprecision highp sampler2D;\n\nuniform sampler2D tTriCount;\nuniform sampler2D tVolumeData;\n\nuniform float uIsoValue;\nuniform vec3 uGridDim;\nuniform vec3 uGridTexDim;\nuniform vec2 uScale;\n\n// cube corners\nconst vec3 c0 = vec3(0., 0., 0.);\nconst vec3 c1 = vec3(1., 0., 0.);\nconst vec3 c2 = vec3(1., 1., 0.);\nconst vec3 c3 = vec3(0., 1., 0.);\nconst vec3 c4 = vec3(0., 0., 1.);\nconst vec3 c5 = vec3(1., 0., 1.);\nconst vec3 c6 = vec3(1., 1., 1.);\nconst vec3 c7 = vec3(0., 1., 1.);\n\nvec3 index3dFrom2d(vec2 coord) {\n    vec2 gridTexPos = coord * uGridTexDim.xy;\n    vec2 columnRow = floor(gridTexPos / uGridDim.xy);\n    vec2 posXY = gridTexPos - columnRow * uGridDim.xy;\n    float posZ = columnRow.y * floor(uGridTexDim.x / uGridDim.x) + columnRow.x;\n    vec3 posXYZ = vec3(posXY, posZ) / uGridDim;\n    return posXYZ;\n}\n\nfloat intDiv(float a, float b) { return float(int(a) / int(b)); }\nfloat intMod(float a, float b) { return a - b * float(int(a) / int(b)); }\n\nvec4 texture3dFrom2dNearest(sampler2D tex, vec3 pos, vec3 gridDim, vec2 texDim) {\n    float zSlice = floor(pos.z * gridDim.z + 0.5); // round to nearest z-slice\n    float column = intMod(zSlice * gridDim.x, texDim.x) / gridDim.x;\n    float row = floor(intDiv(zSlice * gridDim.x, texDim.x));\n    vec2 coord = (vec2(column * gridDim.x, row * gridDim.y) + (pos.xy * gridDim.xy)) / (texDim / uScale);\n    // return texture2D(tex, coord + 0.5 / texDim);\n    return texture2D(tex, coord);\n}\n\nvec4 voxel(vec3 pos) {\n    return texture3dFrom2dNearest(tVolumeData, pos, uGridDim, uGridTexDim.xy);\n}\n\nvoid main(void) {\n    vec2 uv = gl_FragCoord.xy / uGridTexDim.xy;\n    vec3 posXYZ = index3dFrom2d(uv);\n\n    // get MC case as the sum of corners that are below the given iso level\n    float c = step(voxel(posXYZ).a, uIsoValue)\n        + 2. * step(voxel(posXYZ + c1 / uGridDim).a, uIsoValue)\n        + 4. * step(voxel(posXYZ + c2 / uGridDim).a, uIsoValue)\n        + 8. * step(voxel(posXYZ + c3 / uGridDim).a, uIsoValue)\n        + 16. * step(voxel(posXYZ + c4 / uGridDim).a, uIsoValue)\n        + 32. * step(voxel(posXYZ + c5 / uGridDim).a, uIsoValue)\n        + 64. * step(voxel(posXYZ + c6 / uGridDim).a, uIsoValue)\n        + 128. * step(voxel(posXYZ + c7 / uGridDim).a, uIsoValue);\n    c *= step(c, 254.);\n\n    // get total triangles to generate for calculated MC case from triCount texture\n    float totalTrianglesToGenerate = texture2D(tTriCount, vec2(intMod(c, 16.), floor(c / 16.)) / 16.).a;\n    gl_FragColor = vec4(vec3(floor(totalTrianglesToGenerate * 255.0 + 0.5) * 3.0), c);\n\n    // gl_FragColor = vec4(255.0, 0.0, 0.0, voxel(posXYZ + c4 / uGridDim).a * 255.0);\n    // gl_FragColor = vec4(255.0, 0.0, 0.0, voxel(posXYZ).a * 255.0);\n\n    // vec2 uv = vCoordinate;\n    // uv = gl_FragCoord.xy / uGridTexDim.xy;\n\n    // if (uv.y < 0.91) discard;\n    // gl_FragColor = vec4(vCoordinate * 255.0, 0.0, 255.0);\n    // gl_FragColor = vec4(250.0, 0.0, 0.0, 255.0);\n}\n");
//# sourceMappingURL=active-voxels.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/compute/marching-cubes/active-voxels.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var ActiveVoxelsSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["a" /* QuadSchema */]), { tTriCount: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'nearest'), tVolumeData: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'ubyte', 'nearest'), uIsoValue: Object(renderable_schema["i" /* UniformSpec */])('f'), uGridDim: Object(renderable_schema["i" /* UniformSpec */])('v3'), uGridTexDim: Object(renderable_schema["i" /* UniformSpec */])('v3'), uScale: Object(renderable_schema["i" /* UniformSpec */])('v2') });
function getActiveVoxelsRenderable(ctx, volumeData, gridDim, gridTexDim, isoValue, scale) {
    var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["b" /* QuadValues */]), { uQuadScale: mol_util["e" /* ValueCell */].create(scale), tTriCount: mol_util["e" /* ValueCell */].create(getTriCount()), tVolumeData: mol_util["e" /* ValueCell */].create(volumeData), uIsoValue: mol_util["e" /* ValueCell */].create(isoValue), uGridDim: mol_util["e" /* ValueCell */].create(gridDim), uGridTexDim: mol_util["e" /* ValueCell */].create(gridTexDim), uScale: mol_util["e" /* ValueCell */].create(scale) });
    var schema = Object(tslib_es6["__assign"])({}, ActiveVoxelsSchema);
    var shaderCode = Object(shader_code["f" /* ShaderCode */])('active-voxels', quad_vert["a" /* default */], active_voxels_frag);
    var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
    return Object(mol_gl_renderable["a" /* createComputeRenderable */])(renderItem, values);
}
function setRenderingDefaults(ctx) {
    var gl = ctx.gl, state = ctx.state;
    state.disable(gl.CULL_FACE);
    state.disable(gl.BLEND);
    state.disable(gl.DEPTH_TEST);
    state.disable(gl.SCISSOR_TEST);
    state.depthMask(false);
    state.colorMask(true, true, true, true);
    state.clearColor(0, 0, 0, 0);
}
function calcActiveVoxels(ctx, volumeData, gridDim, gridTexDim, isoValue, gridScale) {
    var gl = ctx.gl, resources = ctx.resources;
    var width = volumeData.getWidth();
    var height = volumeData.getHeight();
    var framebuffer = resources.framebuffer();
    framebuffer.bind();
    var activeVoxelsTex = resources.texture('image-float32', 'rgba', 'float', 'nearest');
    activeVoxelsTex.define(width, height);
    var renderable = getActiveVoxelsRenderable(ctx, volumeData, gridDim, gridTexDim, isoValue, gridScale);
    ctx.state.currentRenderItemId = -1;
    activeVoxelsTex.attachFramebuffer(framebuffer, 0);
    setRenderingDefaults(ctx);
    gl.viewport(0, 0, width, height);
    renderable.render();
    // console.log('gridScale', gridScale, 'gridTexDim', gridTexDim, 'gridDim', gridDim)
    // console.log('volumeData', volumeData)
    // console.log('at', readTexture(ctx, activeVoxelsTex))
    gl.finish();
    return activeVoxelsTex;
}
//# sourceMappingURL=active-voxels.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/float-packing.js
var float_packing = __webpack_require__(217);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/histogram-pyramid/sum.frag.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
/* harmony default export */ var sum_frag = ("\nprecision highp float;\nprecision highp sampler2D;\n\nuniform sampler2D tTexture;\n\n#include common\n\nvoid main(void) {\n    gl_FragColor = vec4(encodeFloatRGB(texture2D(tTexture, vec2(0.5)).r), 1.0);\n}\n");
//# sourceMappingURL=sum.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/compute/histogram-pyramid/sum.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var HistopyramidSumSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["a" /* QuadSchema */]), { tTexture: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest') });
var HistopyramidSumRenderable;
function getHistopyramidSumRenderable(ctx, texture) {
    if (HistopyramidSumRenderable) {
        mol_util["e" /* ValueCell */].update(HistopyramidSumRenderable.values.tTexture, texture);
        HistopyramidSumRenderable.update();
        return HistopyramidSumRenderable;
    }
    else {
        var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["b" /* QuadValues */]), { tTexture: mol_util["e" /* ValueCell */].create(texture) });
        var schema = Object(tslib_es6["__assign"])({}, HistopyramidSumSchema);
        var shaderCode = Object(shader_code["f" /* ShaderCode */])('sum', quad_vert["a" /* default */], sum_frag);
        var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
        HistopyramidSumRenderable = Object(mol_gl_renderable["a" /* createComputeRenderable */])(renderItem, values);
        return HistopyramidSumRenderable;
    }
}
var SumTexture;
function getSumTexture(ctx) {
    if (SumTexture)
        return SumTexture;
    SumTexture = ctx.resources.texture('image-uint8', 'rgba', 'ubyte', 'nearest');
    SumTexture.define(1, 1);
    return SumTexture;
}
function sum_setRenderingDefaults(ctx) {
    var gl = ctx.gl, state = ctx.state;
    state.disable(gl.CULL_FACE);
    state.disable(gl.BLEND);
    state.disable(gl.DEPTH_TEST);
    state.disable(gl.SCISSOR_TEST);
    state.depthMask(false);
    state.colorMask(true, true, true, true);
    state.clearColor(0, 0, 0, 0);
}
var sumArray = new Uint8Array(4);
function getHistopyramidSum(ctx, pyramidTopTexture) {
    var gl = ctx.gl, resources = ctx.resources;
    var renderable = getHistopyramidSumRenderable(ctx, pyramidTopTexture);
    ctx.state.currentRenderItemId = -1;
    var framebuffer = resources.framebuffer();
    var sumTexture = getSumTexture(ctx);
    sumTexture.attachFramebuffer(framebuffer, 0);
    sum_setRenderingDefaults(ctx);
    gl.viewport(0, 0, 1, 1);
    renderable.render();
    gl.finish();
    ctx.readPixels(0, 0, 1, 1, sumArray);
    ctx.unbindFramebuffer();
    return Object(float_packing["b" /* decodeFloatRGB */])(sumArray[0], sumArray[1], sumArray[2]);
}
//# sourceMappingURL=sum.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/misc.js
var misc = __webpack_require__(46);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/histogram-pyramid/reduction.frag.js
/* harmony default export */ var reduction_frag = ("\nprecision highp float;\nprecision highp sampler2D;\n\n// input texture (previous level used to evaluate the new level)\nuniform sampler2D tPreviousLevel;\n\n// 1/size of the previous level texture.\nuniform float uSize;\nuniform float uTexSize;\n\nvoid main(void) {\n    float k = 0.5 * uSize;\n    vec2 position = floor((gl_FragCoord.xy / uTexSize) / uSize) * uSize;\n    float a = texture2D(tPreviousLevel, position).r;\n    float b = texture2D(tPreviousLevel, position + vec2(k, 0.)).r;\n    float c = texture2D(tPreviousLevel, position + vec2(0., k)).r;\n    float d = texture2D(tPreviousLevel, position + vec2(k, k)).r;\n    gl_FragColor.a = a;\n    gl_FragColor.b = a + b;\n    gl_FragColor.g = gl_FragColor.b + c;\n    gl_FragColor.r = gl_FragColor.g + d;\n}\n");
//# sourceMappingURL=reduction.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/compute/histogram-pyramid/reduction.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var HistopyramidReductionSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["a" /* QuadSchema */]), { tPreviousLevel: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'), uSize: Object(renderable_schema["i" /* UniformSpec */])('f'), uTexSize: Object(renderable_schema["i" /* UniformSpec */])('f') });
var HistopyramidReductionRenderable;
function getHistopyramidReductionRenderable(ctx, initialTexture) {
    if (HistopyramidReductionRenderable) {
        mol_util["e" /* ValueCell */].update(HistopyramidReductionRenderable.values.tPreviousLevel, initialTexture);
        HistopyramidReductionRenderable.update();
        return HistopyramidReductionRenderable;
    }
    else {
        var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["b" /* QuadValues */]), { tPreviousLevel: mol_util["e" /* ValueCell */].create(initialTexture), uSize: mol_util["e" /* ValueCell */].create(0), uTexSize: mol_util["e" /* ValueCell */].create(0) });
        var schema = Object(tslib_es6["__assign"])({}, HistopyramidReductionSchema);
        var shaderCode = Object(shader_code["f" /* ShaderCode */])('reduction', quad_vert["a" /* default */], reduction_frag);
        var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
        HistopyramidReductionRenderable = Object(mol_gl_renderable["a" /* createComputeRenderable */])(renderItem, values);
        return HistopyramidReductionRenderable;
    }
}
var LevelTexturesFramebuffers = [];
function getLevelTextureFramebuffer(ctx, level) {
    var textureFramebuffer = LevelTexturesFramebuffers[level];
    var size = Math.pow(2, level);
    if (textureFramebuffer === undefined) {
        var texture = ctx.resources.texture('image-float32', 'rgba', 'float', 'nearest');
        var framebuffer = ctx.resources.framebuffer();
        texture.attachFramebuffer(framebuffer, 0);
        textureFramebuffer = { texture: texture, framebuffer: framebuffer };
        textureFramebuffer.texture.define(size, size);
        LevelTexturesFramebuffers[level] = textureFramebuffer;
    }
    return textureFramebuffer;
}
function reduction_setRenderingDefaults(ctx) {
    var gl = ctx.gl, state = ctx.state;
    state.disable(gl.CULL_FACE);
    state.disable(gl.BLEND);
    state.disable(gl.DEPTH_TEST);
    state.disable(gl.SCISSOR_TEST);
    state.depthMask(false);
    state.colorMask(true, true, true, true);
    state.clearColor(0, 0, 0, 0);
}
function createHistogramPyramid(ctx, inputTexture, scale) {
    var gl = ctx.gl, resources = ctx.resources;
    // printTexture(ctx, inputTexture, 2)
    if (inputTexture.getWidth() !== inputTexture.getHeight() || !Object(misc["e" /* isPowerOfTwo */])(inputTexture.getWidth())) {
        throw new Error('inputTexture must be of square power-of-two size');
    }
    // This part set the levels
    var levels = Math.ceil(Math.log(inputTexture.getWidth()) / Math.log(2));
    var maxSize = Math.pow(2, levels);
    // console.log('levels', levels, 'maxSize', maxSize)
    var pyramidTexture = resources.texture('image-float32', 'rgba', 'float', 'nearest');
    pyramidTexture.define(maxSize, maxSize);
    var framebuffer = resources.framebuffer();
    pyramidTexture.attachFramebuffer(framebuffer, 0);
    gl.clear(gl.COLOR_BUFFER_BIT);
    var levelTexturesFramebuffers = [];
    for (var i = 0; i < levels; ++i)
        levelTexturesFramebuffers.push(getLevelTextureFramebuffer(ctx, i));
    var renderable = getHistopyramidReductionRenderable(ctx, inputTexture);
    ctx.state.currentRenderItemId = -1;
    reduction_setRenderingDefaults(ctx);
    var offset = 0;
    for (var i = 0; i < levels; i++) {
        var currLevel = levels - 1 - i;
        var tf = levelTexturesFramebuffers[currLevel];
        tf.framebuffer.bind();
        // levelTextures[currLevel].attachFramebuffer(framebuffer, 0)
        var size = Math.pow(2, currLevel);
        // console.log('size', size, 'draw-level', currLevel, 'read-level', levels - i)
        gl.clear(gl.COLOR_BUFFER_BIT);
        gl.viewport(0, 0, size, size);
        mol_util["e" /* ValueCell */].update(renderable.values.uSize, Math.pow(2, i + 1) / maxSize);
        mol_util["e" /* ValueCell */].update(renderable.values.uTexSize, size);
        if (i > 0) {
            mol_util["e" /* ValueCell */].update(renderable.values.tPreviousLevel, levelTexturesFramebuffers[levels - i].texture);
            renderable.update();
        }
        ctx.state.currentRenderItemId = -1;
        renderable.render();
        pyramidTexture.bind(0);
        gl.copyTexSubImage2D(gl.TEXTURE_2D, 0, offset, 0, 0, 0, size, size);
        pyramidTexture.unbind(0);
        offset += size;
    }
    gl.finish();
    // printTexture(ctx, pyramidTexture, 2)
    //
    var finalCount = getHistopyramidSum(ctx, levelTexturesFramebuffers[0].texture);
    var height = Math.ceil(finalCount / Math.pow(2, levels));
    // const scale = Vec2.create(maxSize / inputTexture.width, maxSize / inputTexture.height)
    // console.log('height', height, 'finalCount', finalCount, 'scale', scale)
    return {
        pyramidTex: pyramidTexture,
        count: finalCount,
        height: height,
        levels: levels,
        scale: scale
    };
}
//# sourceMappingURL=reduction.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/shader/marching-cubes/isosurface.frag.js
/* harmony default export */ var isosurface_frag = ("\nprecision highp float;\nprecision highp sampler2D;\n\nuniform sampler2D tActiveVoxelsPyramid;\nuniform sampler2D tActiveVoxelsBase;\nuniform sampler2D tVolumeData;\nuniform sampler2D tTriIndices;\n\nuniform float uIsoValue;\nuniform float uLevels;\nuniform float uSize;\nuniform float uCount;\n\nuniform vec3 uGridDim;\nuniform vec3 uGridTexDim;\nuniform mat4 uGridTransform;\n\n// scale to volume data coord\nuniform vec2 uScale;\n\n// varying vec2 vCoordinate;\n\n#include common\n\n// cube corners\nconst vec3 c0 = vec3(0., 0., 0.);\nconst vec3 c1 = vec3(1., 0., 0.);\nconst vec3 c2 = vec3(1., 1., 0.);\nconst vec3 c3 = vec3(0., 1., 0.);\nconst vec3 c4 = vec3(0., 0., 1.);\nconst vec3 c5 = vec3(1., 0., 1.);\nconst vec3 c6 = vec3(1., 1., 1.);\nconst vec3 c7 = vec3(0., 1., 1.);\n\nconst float EPS = 0.00001;\n\nvec3 index3dFrom2d(vec2 coord) {\n    vec2 gridTexPos = coord * uGridTexDim.xy;\n    vec2 columnRow = floor(gridTexPos / uGridDim.xy);\n    vec2 posXY = gridTexPos - columnRow * uGridDim.xy;\n    float posZ = columnRow.y * floor(uGridTexDim.x / uGridDim.x) + columnRow.x;\n    vec3 posXYZ = vec3(posXY, posZ);\n    return posXYZ;\n}\n\nvec4 texture3dFrom2dNearest(sampler2D tex, vec3 pos, vec3 gridDim, vec2 texDim) {\n    float zSlice = floor(pos.z * gridDim.z + 0.5); // round to nearest z-slice\n    float column = intMod(zSlice * gridDim.x, texDim.x) / gridDim.x;\n    float row = floor(intDiv(zSlice * gridDim.x, texDim.x));\n    vec2 coord = (vec2(column * gridDim.x, row * gridDim.y) + (pos.xy * gridDim.xy)) / (texDim / uScale);\n    return texture2D(tex, coord + 0.5 / (texDim / uScale));\n    // return texture2D(tex, coord);\n}\n\nvec4 voxel(vec3 pos) {\n    return texture3dFrom2dNearest(tVolumeData, pos, uGridDim, uGridTexDim.xy);\n}\n\nvoid main(void) {\n    // get 1D index\n    float vI = dot(floor(uSize * (gl_FragCoord.xy / uSize)), vec2(1.0, uSize));\n\n    // ignore 1D indices outside of the grid\n    if(vI >= uCount) discard;\n\n    float offset = uSize - 2.;\n    float k = 1. / uSize;\n\n    vec2 relativePosition = k * vec2(offset, 0.);\n    vec4 partialSums = texture2D(tActiveVoxelsPyramid, relativePosition);\n    float start = 0.;\n    vec4 starts = vec4(0.);\n    vec4 ends = vec4(0.);\n    float diff = 2.;\n    vec4 m = vec4(0.);\n    vec2 position = vec2(0.);\n    vec4 vI4 = vec4(vI);\n\n    // traverse the different levels of the pyramid\n    for(int i = 1; i < 12; i++) {\n        if(float(i) >= uLevels) break;\n\n        offset -= diff;\n        diff *= 2.;\n        relativePosition = position + k * vec2(offset, 0.);\n\n        ends = partialSums.wzyx + vec4(start);\n        starts = vec4(start, ends.xyz);\n        m = vec4(greaterThanEqual(vI4, starts)) * vec4(lessThan(vI4, ends));\n        relativePosition += m.y * vec2(k, 0.) + m.z * vec2(0., k) + m.w * vec2(k, k);\n\n        start = dot(m, starts);\n        position = 2. * (relativePosition - k * vec2(offset, 0.));\n        partialSums = texture2D(tActiveVoxelsPyramid, relativePosition);\n    }\n\n    ends = partialSums.wzyx + vec4(start);\n    starts = vec4(start, ends.xyz);\n    m = vec4(greaterThanEqual(vI4, starts)) * vec4(lessThan(vI4, ends));\n    position += m.y * vec2(k, 0.) + m.z * vec2(0., k) + m.w * vec2(k, k);\n\n    vec2 coord2d = position / uScale;\n    vec3 coord3d = floor(index3dFrom2d(coord2d) + 0.5);\n\n    float edgeIndex = floor(texture2D(tActiveVoxelsBase, position).a + 0.5);\n\n    // current vertex for the up to 15 MC cases\n    float currentVertex = vI - dot(m, starts);\n\n    // get index into triIndices table\n    float mcIndex = 16. * edgeIndex + currentVertex;\n    vec4 mcData = texture2D(tTriIndices, vec2(intMod(mcIndex, 64.), floor(mcIndex / 64.)) / 64.);\n\n    // bit mask to avoid conditionals (see comment below) for getting MC case corner\n    vec4 m0 = vec4(floor(mcData.a * 255.0 + 0.5));\n\n    // get edge value masks\n    vec4 m1 = vec4(equal(m0, vec4(0., 1., 2., 3.)));\n    vec4 m2 = vec4(equal(m0, vec4(4., 5., 6., 7.)));\n    vec4 m3 = vec4(equal(m0, vec4(8., 9., 10., 11.)));\n\n    // apply bit masks\n    vec3 b0 = coord3d +\n                m1.y * c1 +\n                m1.z * c2 +\n                m1.w * c3 +\n                m2.x * c4 +\n                m2.y * c5 +\n                m2.z * c6 +\n                m2.w * c7 +\n                m3.y * c1 +\n                m3.z * c2 +\n                m3.w * c3;\n    vec3 b1 = coord3d +\n                m1.x * c1 +\n                m1.y * c2 +\n                m1.z * c3 +\n                m2.x * c5 +\n                m2.y * c6 +\n                m2.z * c7 +\n                m2.w * c4 +\n                m3.x * c4 +\n                m3.y * c5 +\n                m3.z * c6 +\n                m3.w * c7;\n\n    // the conditionals that are avoided by above bitmasks\n    // vec3 b0 = coord3d;\n    // vec3 b1 = coord3d;\n    // if (mcIndex == 0.0) {\n    //     b0 += c0; b1 += c1;\n    // } else if (mcIndex == 1.0) {\n    //     b0 += c1; b1 += c2;\n    // } else if (mcIndex == 2.0) {\n    //     b0 += c2; b1 += c3;\n    // } else if (mcIndex == 3.0) {\n    //     b0 += c3; b1 += c0;\n    // } else if (mcIndex == 4.0) {\n    //     b0 += c4; b1 += c5;\n    // } else if (mcIndex == 5.0) {\n    //     b0 += c5; b1 += c6;\n    // } else if (mcIndex == 6.0) {\n    //     b0 += c6; b1 += c7;\n    // } else if (mcIndex == 7.0) {\n    //     b0 += c7; b1 += c4;\n    // } else if (mcIndex == 8.0) {\n    //     b0 += c0; b1 += c4;\n    // } else if (mcIndex == 9.0) {\n    //     b0 += c1; b1 += c5;\n    // } else if (mcIndex == 10.0) {\n    //     b0 += c2; b1 += c6;\n    // } else if (mcIndex == 11.0) {\n    //     b0 += c3; b1 += c7;\n    // }\n    // b0 = floor(b0 + 0.5);\n    // b1 = floor(b1 + 0.5);\n\n    vec4 d0 = voxel(b0 / uGridDim);\n    vec4 d1 = voxel(b1 / uGridDim);\n\n    float v0 = d0.a;\n    float v1 = d1.a;\n\n    float t = (uIsoValue - v0) / (v0 - v1);\n    // t = -0.5;\n    gl_FragData[0].xyz = (uGridTransform * vec4(b0 + t * (b0 - b1), 1.0)).xyz;\n    gl_FragData[0].w = decodeFloatRGB(d0.rgb); // group id\n\n    // normals from gradients\n    vec3 n0 = -normalize(vec3(\n        voxel((b0 - c1) / uGridDim).a - voxel((b0 + c1) / uGridDim).a,\n        voxel((b0 - c3) / uGridDim).a - voxel((b0 + c3) / uGridDim).a,\n        voxel((b0 - c4) / uGridDim).a - voxel((b0 + c4) / uGridDim).a\n    ));\n    vec3 n1 = -normalize(vec3(\n        voxel((b1 - c1) / uGridDim).a - voxel((b1 + c1) / uGridDim).a,\n        voxel((b1 - c3) / uGridDim).a - voxel((b1 + c3) / uGridDim).a,\n        voxel((b1 - c4) / uGridDim).a - voxel((b1 + c4) / uGridDim).a\n    ));\n    gl_FragData[1].xyz = -vec3(\n        n0.x + t * (n0.x - n1.x),\n        n0.y + t * (n0.y - n1.y),\n        n0.z + t * (n0.z - n1.z)\n    );\n\n    mat3 normalMatrix = transpose3(inverse3(mat3(uGridTransform)));\n    gl_FragData[1].xyz = normalMatrix * gl_FragData[1].xyz;\n}\n");
//# sourceMappingURL=isosurface.frag.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-gl/compute/marching-cubes/isosurface.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var IsosurfaceSchema = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["a" /* QuadSchema */]), { tTriIndices: Object(renderable_schema["h" /* TextureSpec */])('image-uint8', 'alpha', 'ubyte', 'nearest'), tActiveVoxelsPyramid: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'), tActiveVoxelsBase: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'float', 'nearest'), tVolumeData: Object(renderable_schema["h" /* TextureSpec */])('texture', 'rgba', 'ubyte', 'nearest'), uIsoValue: Object(renderable_schema["i" /* UniformSpec */])('f'), uSize: Object(renderable_schema["i" /* UniformSpec */])('f'), uLevels: Object(renderable_schema["i" /* UniformSpec */])('f'), uCount: Object(renderable_schema["i" /* UniformSpec */])('f'), uGridDim: Object(renderable_schema["i" /* UniformSpec */])('v3'), uGridTexDim: Object(renderable_schema["i" /* UniformSpec */])('v3'), uGridTransform: Object(renderable_schema["i" /* UniformSpec */])('m4'), uScale: Object(renderable_schema["i" /* UniformSpec */])('v2') });
function getIsosurfaceRenderable(ctx, activeVoxelsPyramid, activeVoxelsBase, volumeData, gridDim, gridTexDim, transform, isoValue, levels, scale, count, height) {
    // console.log('uSize', Math.pow(2, levels))
    var values = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, compute_util["b" /* QuadValues */]), { uQuadScale: mol_util["e" /* ValueCell */].create(linear_algebra["Vec2"].create(1, height / Math.pow(2, levels))), tTriIndices: mol_util["e" /* ValueCell */].create(getTriIndices()), tActiveVoxelsPyramid: mol_util["e" /* ValueCell */].create(activeVoxelsPyramid), tActiveVoxelsBase: mol_util["e" /* ValueCell */].create(activeVoxelsBase), tVolumeData: mol_util["e" /* ValueCell */].create(volumeData), uIsoValue: mol_util["e" /* ValueCell */].create(isoValue), uSize: mol_util["e" /* ValueCell */].create(Math.pow(2, levels)), uLevels: mol_util["e" /* ValueCell */].create(levels), uCount: mol_util["e" /* ValueCell */].create(count), uGridDim: mol_util["e" /* ValueCell */].create(gridDim), uGridTexDim: mol_util["e" /* ValueCell */].create(gridTexDim), uGridTransform: mol_util["e" /* ValueCell */].create(transform), uScale: mol_util["e" /* ValueCell */].create(scale) });
    var schema = Object(tslib_es6["__assign"])({}, IsosurfaceSchema);
    var shaderCode = Object(shader_code["f" /* ShaderCode */])('isosurface', quad_vert["a" /* default */], isosurface_frag, { drawBuffers: true });
    var renderItem = Object(render_item["a" /* createComputeRenderItem */])(ctx, 'triangles', shaderCode, schema, values);
    return Object(mol_gl_renderable["a" /* createComputeRenderable */])(renderItem, values);
}
function isosurface_setRenderingDefaults(ctx) {
    var gl = ctx.gl, state = ctx.state;
    state.disable(gl.CULL_FACE);
    state.disable(gl.BLEND);
    state.disable(gl.DEPTH_TEST);
    state.disable(gl.SCISSOR_TEST);
    state.depthMask(false);
    state.colorMask(true, true, true, true);
    state.clearColor(0, 0, 0, 0);
}
function createIsosurfaceBuffers(ctx, activeVoxelsBase, volumeData, histogramPyramid, gridDim, gridTexDim, transform, isoValue, vertexGroupTexture, normalTexture) {
    var gl = ctx.gl, resources = ctx.resources;
    var pyramidTex = histogramPyramid.pyramidTex, height = histogramPyramid.height, levels = histogramPyramid.levels, scale = histogramPyramid.scale, count = histogramPyramid.count;
    // console.log('iso', 'gridDim', gridDim, 'scale', scale, 'gridTexDim', gridTexDim)
    // console.log('iso volumeData', volumeData)
    var framebuffer = resources.framebuffer();
    var needsClear = false;
    if (!vertexGroupTexture) {
        vertexGroupTexture = resources.texture('image-float32', 'rgba', 'float', 'nearest');
        vertexGroupTexture.define(pyramidTex.getWidth(), pyramidTex.getHeight());
    }
    else if (vertexGroupTexture.getWidth() !== pyramidTex.getWidth() || vertexGroupTexture.getHeight() !== pyramidTex.getHeight()) {
        vertexGroupTexture.define(pyramidTex.getWidth(), pyramidTex.getHeight());
    }
    else {
        needsClear = true;
    }
    if (!normalTexture) {
        normalTexture = resources.texture('image-float32', 'rgba', 'float', 'nearest');
        normalTexture.define(pyramidTex.getWidth(), pyramidTex.getHeight());
    }
    else if (normalTexture.getWidth() !== pyramidTex.getWidth() || normalTexture.getHeight() !== pyramidTex.getHeight()) {
        normalTexture.define(pyramidTex.getWidth(), pyramidTex.getHeight());
    }
    else {
        needsClear = true;
    }
    // const infoTex = createTexture(ctx, 'image-float32', 'rgba', 'float', 'nearest')
    // infoTex.define(pyramidTex.width, pyramidTex.height)
    // const pointTexA = createTexture(ctx, 'image-float32', 'rgba', 'float', 'nearest')
    // pointTexA.define(pyramidTex.width, pyramidTex.height)
    // const pointTexB = createTexture(ctx, 'image-float32', 'rgba', 'float', 'nearest')
    // pointTexB.define(pyramidTex.width, pyramidTex.height)
    // const coordTex = createTexture(ctx, 'image-float32', 'rgba', 'float', 'nearest')
    // coordTex.define(pyramidTex.width, pyramidTex.height)
    // const indexTex = createTexture(ctx, 'image-float32', 'rgba', 'float', 'nearest')
    // indexTex.define(pyramidTex.width, pyramidTex.height)
    var renderable = getIsosurfaceRenderable(ctx, pyramidTex, activeVoxelsBase, volumeData, gridDim, gridTexDim, transform, isoValue, levels, scale, count, height);
    ctx.state.currentRenderItemId = -1;
    vertexGroupTexture.attachFramebuffer(framebuffer, 0);
    normalTexture.attachFramebuffer(framebuffer, 1);
    // infoTex.attachFramebuffer(framebuffer, 1)
    // pointTexA.attachFramebuffer(framebuffer, 2)
    // pointTexB.attachFramebuffer(framebuffer, 3)
    // coordTex.attachFramebuffer(framebuffer, 4)
    // indexTex.attachFramebuffer(framebuffer, 5)
    var drawBuffers = ctx.extensions.drawBuffers;
    if (!drawBuffers)
        throw new Error('need WebGL draw buffers');
    drawBuffers.drawBuffers([
        drawBuffers.COLOR_ATTACHMENT0,
        drawBuffers.COLOR_ATTACHMENT1,
    ]);
    isosurface_setRenderingDefaults(ctx);
    gl.viewport(0, 0, pyramidTex.getWidth(), pyramidTex.getHeight());
    if (needsClear)
        gl.clear(gl.COLOR_BUFFER_BIT);
    renderable.render();
    gl.finish();
    // const vgt = readTexture(ctx, vertexGroupTexture, pyramidTex.width, height)
    // console.log('vertexGroupTexture', vgt.array.subarray(0, 4 * count))
    // const vt = readTexture(ctx, verticesTex, pyramidTex.width, height)
    // console.log('vt', vt)
    // const vertices = new Float32Array(3 * compacted.count)
    // for (let i = 0; i < compacted.count; ++i) {
    //     vertices[i * 3] = vt.array[i * 4]
    //     vertices[i * 3 + 1] = vt.array[i * 4 + 1]
    //     vertices[i * 3 + 2] = vt.array[i * 4 + 2]
    // }
    // console.log('vertices', vertices)
    // const it = readTexture(ctx, infoTex, pyramidTex.width, height)
    // console.log('info', it.array.subarray(0, 4 * compacted.count))
    // const pat = readTexture(ctx, pointTexA, pyramidTex.width, height)
    // console.log('point a', pat.array.subarray(0, 4 * compacted.count))
    // const pbt = readTexture(ctx, pointTexB, pyramidTex.width, height)
    // console.log('point b', pbt.array.subarray(0, 4 * compacted.count))
    // const ct = readTexture(ctx, coordTex, pyramidTex.width, height)
    // console.log('coord', ct.array.subarray(0, 4 * compacted.count))
    // const idxt = readTexture(ctx, indexTex, pyramidTex.width, height)
    // console.log('index', idxt.array.subarray(0, 4 * compacted.count))
    // const { field, idField } = await fieldFromTexture2d(ctx, volumeData, gridDimensions)
    // console.log({ field, idField })
    // const valuesA = new Float32Array(compacted.count)
    // const valuesB = new Float32Array(compacted.count)
    // for (let i = 0; i < compacted.count; ++i) {
    //     valuesA[i] = field.space.get(field.data, pat.array[i * 4], pat.array[i * 4 + 1], pat.array[i * 4 + 2])
    //     valuesB[i] = field.space.get(field.data, pbt.array[i * 4], pbt.array[i * 4 + 1], pbt.array[i * 4 + 2])
    // }
    // console.log('valuesA', valuesA)
    // console.log('valuesB', valuesB)
    return { vertexGroupTexture: vertexGroupTexture, normalTexture: normalTexture, vertexCount: count };
}
//# sourceMappingURL=isosurface.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/gaussian-surface-mesh.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var GaussianSurfaceMeshParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), units_visual["i" /* UnitsTextureMeshParams */]), GaussianDensityParams);
function getGaussianSurfaceVisual(webgl) {
    return webgl && webgl.extensions.drawBuffers ? GaussianSurfaceTextureMeshVisual : GaussianSurfaceMeshVisual;
}
//
function createGaussianSurfaceMesh(ctx, unit, structure, theme, props, mesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var smoothness, _a, transform, field, idField, params, surface, sphere;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    smoothness = props.smoothness;
                    return [4 /*yield*/, computeUnitGaussianDensity(structure, unit, props, ctx.webgl).runInContext(ctx.runtime)];
                case 1:
                    _a = _b.sent(), transform = _a.transform, field = _a.field, idField = _a.idField;
                    params = {
                        isoLevel: Math.exp(-smoothness),
                        scalarField: field,
                        idField: idField
                    };
                    return [4 /*yield*/, Object(algorithm["b" /* computeMarchingCubesMesh */])(params, mesh).runAsChild(ctx.runtime)];
                case 2:
                    surface = _b.sent();
                    mesh_mesh["a" /* Mesh */].transform(surface, transform);
                    if (ctx.webgl && !ctx.webgl.isWebGL2)
                        mesh_mesh["a" /* Mesh */].uniformTriangleGroup(surface);
                    sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, props.radiusOffset);
                    surface.setBoundingSphere(sphere);
                    return [2 /*return*/, surface];
            }
        });
    });
}
function GaussianSurfaceMeshVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(GaussianSurfaceMeshParams),
        createGeometry: createGaussianSurfaceMesh,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.radiusOffset !== currentProps.radiusOffset)
                state.createGeometry = true;
            if (newProps.smoothness !== currentProps.smoothness)
                state.createGeometry = true;
            if (newProps.useGpu !== currentProps.useGpu)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.traceOnly !== currentProps.traceOnly)
                state.createGeometry = true;
            if (newProps.includeParent !== currentProps.includeParent)
                state.createGeometry = true;
        }
    }, materialId);
}
//
var StructureGaussianSurfaceMeshParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["c" /* ComplexMeshParams */]), GaussianDensityParams), { ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function createStructureGaussianSurfaceMesh(ctx, structure, theme, props, mesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var smoothness, _a, transform, field, idField, params, surface, sphere;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    smoothness = props.smoothness;
                    return [4 /*yield*/, computeStructureGaussianDensity(structure, props, ctx.webgl).runInContext(ctx.runtime)];
                case 1:
                    _a = _b.sent(), transform = _a.transform, field = _a.field, idField = _a.idField;
                    params = {
                        isoLevel: Math.exp(-smoothness),
                        scalarField: field,
                        idField: idField
                    };
                    return [4 /*yield*/, Object(algorithm["b" /* computeMarchingCubesMesh */])(params, mesh).runAsChild(ctx.runtime)];
                case 2:
                    surface = _b.sent();
                    mesh_mesh["a" /* Mesh */].transform(surface, transform);
                    if (ctx.webgl && !ctx.webgl.isWebGL2)
                        mesh_mesh["a" /* Mesh */].uniformTriangleGroup(surface);
                    sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), structure.boundary.sphere, props.radiusOffset);
                    surface.setBoundingSphere(sphere);
                    return [2 /*return*/, surface];
            }
        });
    });
}
function StructureGaussianSurfaceMeshVisual(materialId) {
    return Object(complex_visual["d" /* ComplexMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(StructureGaussianSurfaceMeshParams),
        createGeometry: createStructureGaussianSurfaceMesh,
        createLocationIterator: element_ElementIterator.fromStructure,
        getLoci: getSerialElementLoci,
        eachLocation: eachSerialElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.radiusOffset !== currentProps.radiusOffset)
                state.createGeometry = true;
            if (newProps.smoothness !== currentProps.smoothness)
                state.createGeometry = true;
            if (newProps.useGpu !== currentProps.useGpu)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.traceOnly !== currentProps.traceOnly)
                state.createGeometry = true;
        }
    }, materialId);
}
//
function createGaussianSurfaceTextureMesh(ctx, unit, structure, theme, props, textureMesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var isoLevel, densityTextureData, activeVoxelsTex, compacted, gv, boundingSphere, surface;
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!ctx.webgl)
                        throw new Error('webgl context required to create gaussian surface texture-mesh');
                    isoLevel = Math.exp(-props.smoothness);
                    return [4 /*yield*/, computeUnitGaussianDensityTexture2d(structure, unit, props, ctx.webgl).runInContext(ctx.runtime)];
                case 1:
                    densityTextureData = _a.sent();
                    activeVoxelsTex = calcActiveVoxels(ctx.webgl, densityTextureData.texture, densityTextureData.gridDim, densityTextureData.gridTexDim, isoLevel, densityTextureData.gridTexScale);
                    compacted = createHistogramPyramid(ctx.webgl, activeVoxelsTex, densityTextureData.gridTexScale);
                    gv = createIsosurfaceBuffers(ctx.webgl, activeVoxelsTex, densityTextureData.texture, compacted, densityTextureData.gridDim, densityTextureData.gridTexDim, densityTextureData.transform, isoLevel, textureMesh ? textureMesh.vertexGroupTexture.ref.value : undefined, textureMesh ? textureMesh.normalTexture.ref.value : undefined);
                    boundingSphere = geometry["g" /* Sphere3D */].fromBox3D(Object(geometry["g" /* Sphere3D */])(), densityTextureData.bbox);
                    surface = texture_mesh["a" /* TextureMesh */].create(gv.vertexCount, 1, gv.vertexGroupTexture, gv.normalTexture, boundingSphere, textureMesh);
                    // ctx.webgl.waitForGpuCommandsCompleteSync()
                    return [2 /*return*/, surface];
            }
        });
    });
}
function GaussianSurfaceTextureMeshVisual(materialId) {
    return Object(units_visual["j" /* UnitsTextureMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(GaussianSurfaceMeshParams),
        createGeometry: createGaussianSurfaceTextureMesh,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.radiusOffset !== currentProps.radiusOffset)
                state.createGeometry = true;
            if (newProps.smoothness !== currentProps.smoothness)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.traceOnly !== currentProps.traceOnly)
                state.createGeometry = true;
            if (newProps.includeParent !== currentProps.includeParent)
                state.createGeometry = true;
        }
    }, materialId);
}
//# sourceMappingURL=gaussian-surface-mesh.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/lines/lines.js
var lines_lines = __webpack_require__(74);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/gaussian-surface-wireframe.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








function createGaussianWireframe(ctx, unit, structure, theme, props, lines) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var smoothness, _a, transform, field, idField, params, wireframe, sphere;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0:
                    smoothness = props.smoothness;
                    return [4 /*yield*/, computeUnitGaussianDensity(structure, unit, props, ctx.webgl).runInContext(ctx.runtime)];
                case 1:
                    _a = _b.sent(), transform = _a.transform, field = _a.field, idField = _a.idField;
                    params = {
                        isoLevel: Math.exp(-smoothness),
                        scalarField: field,
                        idField: idField
                    };
                    return [4 /*yield*/, Object(algorithm["a" /* computeMarchingCubesLines */])(params, lines).runAsChild(ctx.runtime)];
                case 2:
                    wireframe = _b.sent();
                    lines_lines["a" /* Lines */].transform(wireframe, transform);
                    sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, props.radiusOffset);
                    wireframe.setBoundingSphere(sphere);
                    return [2 /*return*/, wireframe];
            }
        });
    });
}
var GaussianWireframeParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["a" /* UnitsLinesParams */]), GaussianDensityParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(1.5, { min: 0, max: 10, step: 0.1 }), lineSizeAttenuation: param_definition["ParamDefinition"].Boolean(false), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function GaussianWireframeVisual(materialId) {
    return Object(units_visual["b" /* UnitsLinesVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(GaussianWireframeParams),
        createGeometry: createGaussianWireframe,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.radiusOffset !== currentProps.radiusOffset)
                state.createGeometry = true;
            if (newProps.smoothness !== currentProps.smoothness)
                state.createGeometry = true;
            if (newProps.useGpu !== currentProps.useGpu)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.traceOnly !== currentProps.traceOnly)
                state.createGeometry = true;
            if (newProps.includeParent !== currentProps.includeParent)
                state.createGeometry = true;
        }
    }, materialId);
}
//# sourceMappingURL=gaussian-surface-wireframe.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/gaussian-surface.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var GaussianSurfaceVisuals = {
    'gaussian-surface-mesh': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Gaussian surface mesh', ctx, getParams, GaussianSurfaceMeshVisual); },
    'structure-gaussian-surface-mesh': function (ctx, getParams) { return Object(structure_representation["a" /* ComplexRepresentation */])('Structure-Gaussian surface mesh', ctx, getParams, StructureGaussianSurfaceMeshVisual); },
    'gaussian-surface-texture-mesh': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Gaussian surface texture-mesh', ctx, getParams, GaussianSurfaceTextureMeshVisual); },
    'gaussian-surface-wireframe': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Gaussian surface wireframe', ctx, getParams, GaussianWireframeVisual); },
};
var GaussianSurfaceParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, GaussianSurfaceMeshParams), GaussianWireframeParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['gaussian-surface-mesh'], param_definition["ParamDefinition"].objectToOptions(GaussianSurfaceVisuals)) });
function getGaussianSurfaceParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(GaussianSurfaceParams);
}
function GaussianSurfaceRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Gaussian Surface', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], GaussianSurfaceVisuals);
}
var GaussianSurfaceRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'gaussian-surface',
    label: 'Gaussian Surface',
    description: 'Displays a gaussian molecular surface.',
    factory: GaussianSurfaceRepresentation,
    getParams: getGaussianSurfaceParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(GaussianSurfaceParams),
    defaultColorTheme: { name: 'chain-id' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=gaussian-surface.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/text/text-builder.js
var text_builder = __webpack_require__(209);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size/physical.js
var physical = __webpack_require__(282);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/label-text.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */










var LabelTextParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["e" /* ComplexTextParams */]), { background: param_definition["ParamDefinition"].Boolean(true), backgroundMargin: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 1, step: 0.01 }), backgroundColor: param_definition["ParamDefinition"].Color(names["a" /* ColorNames */].black), backgroundOpacity: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 1, step: 0.01 }), level: param_definition["ParamDefinition"].Select('residue', [['chain', 'Chain'], ['residue', 'Residue'], ['element', 'Element']]), chainScale: param_definition["ParamDefinition"].Numeric(10, { min: 0, max: 20, step: 0.1 }), residueScale: param_definition["ParamDefinition"].Numeric(1, { min: 0, max: 20, step: 0.1 }), elementScale: param_definition["ParamDefinition"].Numeric(0.5, { min: 0, max: 20, step: 0.1 }) });
function LabelTextVisual(materialId) {
    return Object(complex_visual["f" /* ComplexTextVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(LabelTextParams),
        createGeometry: createLabelText,
        createLocationIterator: element_ElementIterator.fromStructure,
        getLoci: getSerialElementLoci,
        eachLocation: eachSerialElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.level !== currentProps.level ||
                (newProps.level === 'chain' && newProps.chainScale !== currentProps.chainScale) ||
                (newProps.level === 'residue' && newProps.residueScale !== currentProps.residueScale) ||
                (newProps.level === 'element' && newProps.elementScale !== currentProps.elementScale));
        }
    }, materialId);
}
function createLabelText(ctx, structure, theme, props, text) {
    switch (props.level) {
        case 'chain': return createChainText(ctx, structure, theme, props, text);
        case 'residue': return createResidueText(ctx, structure, theme, props, text);
        case 'element': return createElementText(ctx, structure, theme, props, text);
    }
}
//
var tmpVec = Object(linear_algebra["Vec3"])();
var label_text_boundaryHelper = new boundary_helper["a" /* BoundaryHelper */]('98');
function createChainText(ctx, structure, theme, props, text) {
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var units = structure.units, serialMapping = structure.serialMapping;
    var _a = mol_model_structure["StructureProperties"].chain, auth_asym_id = _a.auth_asym_id, label_asym_id = _a.label_asym_id;
    var cumulativeUnitElementCount = serialMapping.cumulativeUnitElementCount;
    var count = units.length;
    var chainScale = props.chainScale;
    var builder = text_builder["a" /* TextBuilder */].create(props, count, count / 2, text);
    for (var i = 0, il = units.length; i < il; ++i) {
        var unit = units[i];
        l.unit = unit;
        l.element = unit.elements[0];
        var _b = unit.lookup3d.boundary.sphere, center = _b.center, radius = _b.radius;
        linear_algebra["Vec3"].transformMat4(tmpVec, center, unit.conformation.operator.matrix);
        var authId = auth_asym_id(l);
        var labelId = label_asym_id(l);
        var text_1 = authId === labelId ? labelId : labelId + " [" + authId + "]";
        builder.add(text_1, tmpVec[0], tmpVec[1], tmpVec[2], radius, chainScale, cumulativeUnitElementCount[i]);
    }
    return builder.getText();
}
function createResidueText(ctx, structure, theme, props, text) {
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var units = structure.units, serialMapping = structure.serialMapping;
    var label_comp_id = mol_model_structure["StructureProperties"].atom.label_comp_id;
    var auth_seq_id = mol_model_structure["StructureProperties"].residue.auth_seq_id;
    var cumulativeUnitElementCount = serialMapping.cumulativeUnitElementCount;
    var count = structure.polymerResidueCount * 2;
    var residueScale = props.residueScale;
    var builder = text_builder["a" /* TextBuilder */].create(props, count, count / 2, text);
    for (var i = 0, il = units.length; i < il; ++i) {
        var unit = units[i];
        var pos = unit.conformation.position;
        var elements = unit.elements;
        l.unit = unit;
        l.element = unit.elements[0];
        var residueIndex = unit.model.atomicHierarchy.residueAtomSegments.index;
        var groupOffset = cumulativeUnitElementCount[i];
        var j = 0, jl = elements.length;
        while (j < jl) {
            var start = j, rI = residueIndex[elements[j]];
            j++;
            while (j < jl && residueIndex[elements[j]] === rI)
                j++;
            label_text_boundaryHelper.reset();
            for (var eI = start; eI < j; eI++) {
                pos(elements[eI], tmpVec);
                label_text_boundaryHelper.includePosition(tmpVec);
            }
            label_text_boundaryHelper.finishedIncludeStep();
            for (var eI = start; eI < j; eI++) {
                pos(elements[eI], tmpVec);
                label_text_boundaryHelper.radiusPosition(tmpVec);
            }
            l.element = elements[start];
            var _a = label_text_boundaryHelper.getSphere(), center = _a.center, radius = _a.radius;
            var authSeqId = auth_seq_id(l);
            var compId = label_comp_id(l);
            var text_2 = compId + " " + authSeqId;
            builder.add(text_2, center[0], center[1], center[2], radius, residueScale, groupOffset + start);
        }
    }
    return builder.getText();
}
function createElementText(ctx, structure, theme, props, text) {
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var units = structure.units, serialMapping = structure.serialMapping;
    var _a = mol_model_structure["StructureProperties"].atom, label_atom_id = _a.label_atom_id, label_alt_id = _a.label_alt_id;
    var cumulativeUnitElementCount = serialMapping.cumulativeUnitElementCount;
    var sizeTheme = Object(physical["a" /* PhysicalSizeTheme */])({}, { scale: 1 });
    var count = structure.elementCount;
    var elementScale = props.elementScale;
    var builder = text_builder["a" /* TextBuilder */].create(props, count, count / 2, text);
    for (var i = 0, il = units.length; i < il; ++i) {
        var unit = units[i];
        var pos = unit.conformation.position;
        var elements = unit.elements;
        l.unit = unit;
        var groupOffset = cumulativeUnitElementCount[i];
        for (var j = 0, _j = elements.length; j < _j; j++) {
            l.element = elements[j];
            pos(l.element, tmpVec);
            var atomId = label_atom_id(l);
            var altId = label_alt_id(l);
            var text_3 = altId ? atomId + "%" + altId : atomId;
            builder.add(text_3, tmpVec[0], tmpVec[1], tmpVec[2], sizeTheme.size(l), elementScale, groupOffset + j);
        }
    }
    return builder.getText();
}
//# sourceMappingURL=label-text.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/label.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var LabelVisuals = {
    'label-text': function (ctx, getParams) { return Object(structure_representation["a" /* ComplexRepresentation */])('Label text', ctx, getParams, LabelTextVisual); },
};
var LabelParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, LabelTextParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['label-text'], param_definition["ParamDefinition"].objectToOptions(LabelVisuals)) });
function getLabelParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(LabelParams);
}
function LabelRepresentation(ctx, getParams) {
    var repr = mol_repr_representation["a" /* Representation */].createMulti('Label', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], LabelVisuals);
    repr.setState({ pickable: false, markerActions: marker_action["a" /* MarkerAction */].None });
    return repr;
}
var LabelRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'label',
    label: 'Label',
    description: 'Displays labels.',
    factory: LabelRepresentation,
    getParams: getLabelParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(LabelParams),
    defaultColorTheme: { name: 'uniform' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=label.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-math/linear-algebra/3d.js + 4 modules
var _3d = __webpack_require__(25);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-math/geometry/molecular-surface.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Fred Ludlow <fred.ludlow@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 *
 * ported from NGL (https://github.com/arose/ngl), licensed under MIT
 */







function normalToLine(out, p) {
    out[0] = out[1] = out[2] = 1.0;
    if (p[0] !== 0) {
        out[0] = (p[1] + p[2]) / -p[0];
    }
    else if (p[1] !== 0) {
        out[1] = (p[0] + p[2]) / -p[1];
    }
    else if (p[2] !== 0) {
        out[2] = (p[0] + p[1]) / -p[2];
    }
    return out;
}
function getAngleTables(probePositions) {
    var theta = 0.0;
    var step = 2 * Math.PI / probePositions;
    var cosTable = new Float32Array(probePositions);
    var sinTable = new Float32Array(probePositions);
    for (var i = 0; i < probePositions; i++) {
        cosTable[i] = Math.cos(theta);
        sinTable[i] = Math.sin(theta);
        theta += step;
    }
    return { cosTable: cosTable, sinTable: sinTable };
}
//
var MolecularSurfaceCalculationParams = {
    probeRadius: param_definition["ParamDefinition"].Numeric(1.4, { min: 0, max: 10, step: 0.1 }, { description: 'Radius of the probe tracing the molecular surface.' }),
    resolution: param_definition["ParamDefinition"].Numeric(0.5, { min: 0.01, max: 20, step: 0.01 }, Object(tslib_es6["__assign"])({ description: 'Grid resolution/cell spacing.' }, base["a" /* BaseGeometry */].CustomQualityParamInfo)),
    probePositions: param_definition["ParamDefinition"].Numeric(30, { min: 12, max: 90, step: 1 }, Object(tslib_es6["__assign"])({ description: 'Number of positions tested for probe target intersection.' }, base["a" /* BaseGeometry */].CustomQualityParamInfo)),
};
var DefaultMolecularSurfaceCalculationProps = param_definition["ParamDefinition"].getDefaultValues(MolecularSurfaceCalculationParams);
function calcMolecularSurface(ctx, position, boundary, maxRadius, box, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        /**
         * Is the point at x,y,z obscured by any of the atoms specifeid by indices in neighbours.
         * Ignore indices a and b (these are the relevant atoms in projectPoints/Torii)
         *
         * Cache the last clipped atom (as very often the same one in subsequent calls)
         *
         * `a` and `b` must be resolved indices
         */
        function obscured(x, y, z, a, b) {
            if (lastClip !== -1) {
                var ai = lastClip;
                if (ai !== a && ai !== b && singleAtomObscures(ai, x, y, z)) {
                    return ai;
                }
                else {
                    lastClip = -1;
                }
            }
            for (var j = 0, jl = neighbours.count; j < jl; ++j) {
                var ai = mol_data_int["OrderedSet"].getAt(indices, neighbours.indices[j]);
                if (ai !== a && ai !== b && singleAtomObscures(ai, x, y, z)) {
                    lastClip = ai;
                    return ai;
                }
            }
            return -1;
        }
        /**
         * `ai` must be a resolved index
         */
        function singleAtomObscures(ai, x, y, z) {
            var r = radius[ai];
            var dx = px[ai] - x;
            var dy = py[ai] - y;
            var dz = pz[ai] - z;
            var dSq = dx * dx + dy * dy + dz * dz;
            return dSq < (r * r);
        }
        /**
         * For each atom:
         *     Iterate over a subsection of the grid, for each point:
         *         If current value < 0.0, unvisited, set positive
         *
         *         In any case: Project this point onto surface of the atomic sphere
         *         If this projected point is not obscured by any other atom
         *             Calculate delta distance and set grid value to minimum of
         *             itself and delta
         */
        function projectPointsRange(begI, endI) {
            for (var i = begI; i < endI; ++i) {
                var j = mol_data_int["OrderedSet"].getAt(indices, i);
                var vx = px[j], vy = py[j], vz = pz[j];
                var rad = radius[j];
                var rSq = rad * rad;
                lookup3d.find(vx, vy, vz, rad);
                // Number of grid points, round this up...
                var ng = Math.ceil(rad * scaleFactor);
                // Center of the atom, mapped to grid points (take floor)
                var iax = Math.floor(scaleFactor * (vx - minX));
                var iay = Math.floor(scaleFactor * (vy - minY));
                var iaz = Math.floor(scaleFactor * (vz - minZ));
                // Extents of grid to consider for this atom
                var begX = Math.max(0, iax - ng);
                var begY = Math.max(0, iay - ng);
                var begZ = Math.max(0, iaz - ng);
                // Add two to these points:
                // - iax are floor'd values so this ensures coverage
                // - these are loop limits (exclusive)
                var endX = Math.min(dimX, iax + ng + 2);
                var endY = Math.min(dimY, iay + ng + 2);
                var endZ = Math.min(dimZ, iaz + ng + 2);
                for (var xi = begX; xi < endX; ++xi) {
                    var dx = gridx[xi] - vx;
                    var xIdx = xi * iuv;
                    for (var yi = begY; yi < endY; ++yi) {
                        var dy = gridy[yi] - vy;
                        var dxySq = dx * dx + dy * dy;
                        var xyIdx = yi * iu + xIdx;
                        for (var zi = begZ; zi < endZ; ++zi) {
                            var dz = gridz[zi] - vz;
                            var dSq = dxySq + dz * dz;
                            if (dSq < rSq) {
                                var idx = zi + xyIdx;
                                // if unvisited, make positive
                                if (data[idx] < 0.0)
                                    data[idx] *= -1;
                                // Project on to the surface of the sphere
                                // sp is the projected point ( dx, dy, dz ) * ( ra / d )
                                var d = Math.sqrt(dSq);
                                var ap = rad / d;
                                var spx = dx * ap + vx;
                                var spy = dy * ap + vy;
                                var spz = dz * ap + vz;
                                if (obscured(spx, spy, spz, j, -1) === -1) {
                                    var dd = rad - d;
                                    if (dd < data[idx]) {
                                        data[idx] = dd;
                                        idData[idx] = id[i];
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        function projectPoints() {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var i;
                return Object(tslib_es6["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            i = 0;
                            _a.label = 1;
                        case 1:
                            if (!(i < n)) return [3 /*break*/, 4];
                            projectPointsRange(i, Math.min(i + updateChunk, n));
                            if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                            return [4 /*yield*/, ctx.update({ message: 'projecting points', current: i, max: n })];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            i += updateChunk;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        }
        /**
         * `a` and `b` must be resolved indices
         */
        function projectTorus(a, b) {
            var rA = radius[a];
            var rB = radius[b];
            var dx = atob[0] = px[b] - px[a];
            var dy = atob[1] = py[b] - py[a];
            var dz = atob[2] = pz[b] - pz[a];
            var dSq = dx * dx + dy * dy + dz * dz;
            // This check now redundant as already done in AVHash.withinRadii
            // if (dSq > ((rA + rB) * (rA + rB))) { return }
            var d = Math.sqrt(dSq);
            // Find angle between a->b vector and the circle
            // of their intersection by cosine rule
            var cosA = (rA * rA + d * d - rB * rB) / (2.0 * rA * d);
            // distance along a->b at intersection
            var dmp = rA * cosA;
            linear_algebra["Vec3"].normalize(atob, atob);
            // Create normal to line
            normalToLine(n1, atob);
            linear_algebra["Vec3"].normalize(n1, n1);
            // Cross together for second normal vector
            linear_algebra["Vec3"].cross(n2, atob, n1);
            linear_algebra["Vec3"].normalize(n2, n2);
            // r is radius of circle of intersection
            var rInt = Math.sqrt(rA * rA - dmp * dmp);
            linear_algebra["Vec3"].scale(n1, n1, rInt);
            linear_algebra["Vec3"].scale(n2, n2, rInt);
            linear_algebra["Vec3"].scale(atob, atob, dmp);
            mid[0] = atob[0] + px[a];
            mid[1] = atob[1] + py[a];
            mid[2] = atob[2] + pz[a];
            lastClip = -1;
            for (var i = 0; i < probePositions; ++i) {
                var cost = cosTable[i];
                var sint = sinTable[i];
                var px_1 = mid[0] + cost * n1[0] + sint * n2[0];
                var py_1 = mid[1] + cost * n1[1] + sint * n2[1];
                var pz_1 = mid[2] + cost * n1[2] + sint * n2[2];
                if (obscured(px_1, py_1, pz_1, a, b) === -1) {
                    var iax = Math.floor(scaleFactor * (px_1 - minX));
                    var iay = Math.floor(scaleFactor * (py_1 - minY));
                    var iaz = Math.floor(scaleFactor * (pz_1 - minZ));
                    var begX = Math.max(0, iax - ngTorus);
                    var begY = Math.max(0, iay - ngTorus);
                    var begZ = Math.max(0, iaz - ngTorus);
                    var endX = Math.min(dimX, iax + ngTorus + 2);
                    var endY = Math.min(dimY, iay + ngTorus + 2);
                    var endZ = Math.min(dimZ, iaz + ngTorus + 2);
                    for (var xi = begX; xi < endX; ++xi) {
                        var dx_1 = px_1 - gridx[xi];
                        var xIdx = xi * iuv;
                        for (var yi = begY; yi < endY; ++yi) {
                            var dy_1 = py_1 - gridy[yi];
                            var dxySq = dx_1 * dx_1 + dy_1 * dy_1;
                            var xyIdx = yi * iu + xIdx;
                            for (var zi = begZ; zi < endZ; ++zi) {
                                var dz_1 = pz_1 - gridz[zi];
                                var dSq_1 = dxySq + dz_1 * dz_1;
                                var idx = zi + xyIdx;
                                var current = data[idx];
                                if (current > 0.0 && dSq_1 < (current * current)) {
                                    data[idx] = Math.sqrt(dSq_1);
                                    // Is this grid point closer to a or b?
                                    // Take dot product of atob and gridpoint->p (dx, dy, dz)
                                    var dp = dx_1 * atob[0] + dy_1 * atob[1] + dz_1 * atob[2];
                                    idData[idx] = id[mol_data_int["OrderedSet"].indexOf(indices, dp < 0.0 ? b : a)];
                                }
                            }
                        }
                    }
                }
            }
        }
        function projectToriiRange(begI, endI) {
            for (var i = begI; i < endI; ++i) {
                var k = mol_data_int["OrderedSet"].getAt(indices, i);
                lookup3d.find(px[k], py[k], pz[k], radius[k]);
                for (var j = 0, jl = neighbours.count; j < jl; ++j) {
                    var l = mol_data_int["OrderedSet"].getAt(indices, neighbours.indices[j]);
                    if (k < l)
                        projectTorus(k, l);
                }
            }
        }
        function projectTorii() {
            return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
                var i;
                return Object(tslib_es6["__generator"])(this, function (_a) {
                    switch (_a.label) {
                        case 0:
                            i = 0;
                            _a.label = 1;
                        case 1:
                            if (!(i < n)) return [3 /*break*/, 4];
                            projectToriiRange(i, Math.min(i + updateChunk, n));
                            if (!ctx.shouldUpdate) return [3 /*break*/, 3];
                            return [4 /*yield*/, ctx.update({ message: 'projecting torii', current: i, max: n })];
                        case 2:
                            _a.sent();
                            _a.label = 3;
                        case 3:
                            i += updateChunk;
                            return [3 /*break*/, 1];
                        case 4: return [2 /*return*/];
                    }
                });
            });
        }
        var lastClip, atob, mid, n1, n2, resolution, probeRadius, probePositions, scaleFactor, ngTorus, cellSize, lookup3d, neighbours, indices, px, py, pz, id, radius, n, pad, expandedBox, _a, minX, minY, minZ, scaledBox, dim, dimX, dimY, dimZ, iu, iv, iuv, _b, cosTable, sinTable, space, data, idData, gridx, gridy, gridz, updateChunk, field, idField, transform;
        return Object(tslib_es6["__generator"])(this, function (_c) {
            switch (_c.label) {
                case 0:
                    lastClip = -1;
                    atob = Object(linear_algebra["Vec3"])();
                    mid = Object(linear_algebra["Vec3"])();
                    n1 = Object(linear_algebra["Vec3"])();
                    n2 = Object(linear_algebra["Vec3"])();
                    resolution = props.resolution, probeRadius = props.probeRadius, probePositions = props.probePositions;
                    scaleFactor = 1 / resolution;
                    ngTorus = Math.max(5, 2 + Math.floor(probeRadius * scaleFactor));
                    cellSize = linear_algebra["Vec3"].create(maxRadius, maxRadius, maxRadius);
                    linear_algebra["Vec3"].scale(cellSize, cellSize, 2);
                    lookup3d = Object(geometry["c" /* GridLookup3D */])(position, boundary, cellSize);
                    neighbours = lookup3d.result;
                    if (box === null)
                        box = lookup3d.boundary.box;
                    indices = position.indices, px = position.x, py = position.y, pz = position.z, id = position.id, radius = position.radius;
                    n = mol_data_int["OrderedSet"].size(indices);
                    pad = maxRadius + resolution;
                    expandedBox = geometry["b" /* Box3D */].expand(Object(geometry["b" /* Box3D */])(), box, linear_algebra["Vec3"].create(pad, pad, pad));
                    _a = expandedBox.min, minX = _a[0], minY = _a[1], minZ = _a[2];
                    scaledBox = geometry["b" /* Box3D */].scale(Object(geometry["b" /* Box3D */])(), expandedBox, scaleFactor);
                    dim = geometry["b" /* Box3D */].size(Object(linear_algebra["Vec3"])(), scaledBox);
                    linear_algebra["Vec3"].ceil(dim, dim);
                    dimX = dim[0], dimY = dim[1], dimZ = dim[2];
                    iu = dimZ, iv = dimY, iuv = iu * iv;
                    _b = getAngleTables(probePositions), cosTable = _b.cosTable, sinTable = _b.sinTable;
                    space = linear_algebra["Tensor"].Space(dim, [0, 1, 2], Float32Array);
                    data = space.create();
                    idData = space.create();
                    data.fill(-1001.0);
                    idData.fill(-1);
                    gridx = Object(geometry["i" /* fillGridDim */])(dimX, minX, resolution);
                    gridy = Object(geometry["i" /* fillGridDim */])(dimY, minY, resolution);
                    gridz = Object(geometry["i" /* fillGridDim */])(dimZ, minZ, resolution);
                    updateChunk = Math.ceil(100000 / ((Math.pow(Math.pow(maxRadius, 3), 3) * scaleFactor)));
                    // console.timeEnd('MolecularSurface createState')
                    // console.time('MolecularSurface projectPoints')
                    return [4 /*yield*/, projectPoints()];
                case 1:
                    // console.timeEnd('MolecularSurface createState')
                    // console.time('MolecularSurface projectPoints')
                    _c.sent();
                    // console.timeEnd('MolecularSurface projectPoints')
                    // console.time('MolecularSurface projectTorii')
                    return [4 /*yield*/, projectTorii()];
                case 2:
                    // console.timeEnd('MolecularSurface projectPoints')
                    // console.time('MolecularSurface projectTorii')
                    _c.sent();
                    field = linear_algebra["Tensor"].create(space, data);
                    idField = linear_algebra["Tensor"].create(space, idData);
                    transform = _3d["c" /* Mat4 */].identity();
                    _3d["c" /* Mat4 */].fromScaling(transform, linear_algebra["Vec3"].create(resolution, resolution, resolution));
                    _3d["c" /* Mat4 */].setTranslation(transform, expandedBox.min);
                    // console.log({ field, idField, transform, updateChunk })
                    return [2 /*return*/, { field: field, idField: idField, transform: transform }];
            }
        });
    });
}
//# sourceMappingURL=molecular-surface.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/util/molecular-surface.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */





function getPositionDataAndMaxRadius(structure, unit, props) {
    var probeRadius = props.probeRadius;
    var _a = Object(common["i" /* getUnitConformationAndRadius */])(structure, unit, props), position = _a.position, boundary = _a.boundary, radius = _a.radius;
    var indices = position.indices;
    var n = mol_data_int["OrderedSet"].size(indices);
    var radii = new Float32Array(mol_data_int["OrderedSet"].end(indices));
    var maxRadius = 0;
    for (var i = 0; i < n; ++i) {
        var j = mol_data_int["OrderedSet"].getAt(indices, i);
        var r = radius(j);
        if (maxRadius < r)
            maxRadius = r;
        radii[j] = r + probeRadius;
    }
    return { position: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, position), { radius: radii }), boundary: boundary, maxRadius: maxRadius };
}
function computeUnitMolecularSurface(structure, unit, props) {
    var _this = this;
    var box = unit.lookup3d.boundary.box;
    var p = Object(common["d" /* ensureReasonableResolution */])(box, props);
    var _a = getPositionDataAndMaxRadius(structure, unit, p), position = _a.position, boundary = _a.boundary, maxRadius = _a.maxRadius;
    return mol_task["b" /* Task */].create('Molecular Surface', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, MolecularSurface(ctx, position, boundary, maxRadius, box, p)];
                case 1: return [2 /*return*/, _a.sent()];
            }
        });
    }); });
}
//
function MolecularSurface(ctx, position, boundary, maxRadius, box, props) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        return Object(tslib_es6["__generator"])(this, function (_a) {
            return [2 /*return*/, calcMolecularSurface(ctx, position, boundary, maxRadius, box, props)];
        });
    });
}
//# sourceMappingURL=molecular-surface.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/molecular-surface-mesh.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var MolecularSurfaceMeshParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), MolecularSurfaceCalculationParams), common["a" /* CommonSurfaceParams */]);
//
function createMolecularSurfaceMesh(ctx, unit, structure, theme, props, mesh) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _a, transform, field, idField, params, surface, sphere;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, computeUnitMolecularSurface(structure, unit, props).runInContext(ctx.runtime)];
                case 1:
                    _a = _b.sent(), transform = _a.transform, field = _a.field, idField = _a.idField;
                    params = {
                        isoLevel: props.probeRadius,
                        scalarField: field,
                        idField: idField
                    };
                    return [4 /*yield*/, Object(algorithm["b" /* computeMarchingCubesMesh */])(params, mesh).runAsChild(ctx.runtime)];
                case 2:
                    surface = _b.sent();
                    mesh_mesh["a" /* Mesh */].transform(surface, transform);
                    if (ctx.webgl && !ctx.webgl.isWebGL2)
                        mesh_mesh["a" /* Mesh */].uniformTriangleGroup(surface);
                    sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, props.probeRadius);
                    surface.setBoundingSphere(sphere);
                    return [2 /*return*/, surface];
            }
        });
    });
}
function MolecularSurfaceMeshVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(MolecularSurfaceMeshParams),
        createGeometry: createMolecularSurfaceMesh,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.probeRadius !== currentProps.probeRadius)
                state.createGeometry = true;
            if (newProps.probePositions !== currentProps.probePositions)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.includeParent !== currentProps.includeParent)
                state.createGeometry = true;
        }
    }, materialId);
}
//# sourceMappingURL=molecular-surface-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/molecular-surface-wireframe.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */










var MolecularSurfaceWireframeParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["a" /* UnitsLinesParams */]), MolecularSurfaceCalculationParams), common["a" /* CommonSurfaceParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(1.5, { min: 0, max: 10, step: 0.1 }) });
//
function createMolecularSurfaceWireframe(ctx, unit, structure, theme, props, lines) {
    return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
        var _a, transform, field, idField, params, wireframe, sphere;
        return Object(tslib_es6["__generator"])(this, function (_b) {
            switch (_b.label) {
                case 0: return [4 /*yield*/, computeUnitMolecularSurface(structure, unit, props).runInContext(ctx.runtime)];
                case 1:
                    _a = _b.sent(), transform = _a.transform, field = _a.field, idField = _a.idField;
                    params = {
                        isoLevel: props.probeRadius,
                        scalarField: field,
                        idField: idField
                    };
                    return [4 /*yield*/, Object(algorithm["a" /* computeMarchingCubesLines */])(params, lines).runAsChild(ctx.runtime)];
                case 2:
                    wireframe = _b.sent();
                    lines_lines["a" /* Lines */].transform(wireframe, transform);
                    sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, props.probeRadius);
                    wireframe.setBoundingSphere(sphere);
                    return [2 /*return*/, wireframe];
            }
        });
    });
}
function MolecularSurfaceWireframeVisual(materialId) {
    return Object(units_visual["b" /* UnitsLinesVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(MolecularSurfaceWireframeParams),
        createGeometry: createMolecularSurfaceWireframe,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            if (newProps.resolution !== currentProps.resolution)
                state.createGeometry = true;
            if (newProps.probeRadius !== currentProps.probeRadius)
                state.createGeometry = true;
            if (newProps.probePositions !== currentProps.probePositions)
                state.createGeometry = true;
            if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens)
                state.createGeometry = true;
            if (newProps.includeParent !== currentProps.includeParent)
                state.createGeometry = true;
        }
    }, materialId);
}
//# sourceMappingURL=molecular-surface-wireframe.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/molecular-surface.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */







var MolecularSurfaceVisuals = {
    'molecular-surface-mesh': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Molecular surface mesh', ctx, getParams, MolecularSurfaceMeshVisual); },
    'molecular-surface-wireframe': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Molecular surface wireframe', ctx, getParams, MolecularSurfaceWireframeVisual); },
};
var MolecularSurfaceParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, MolecularSurfaceMeshParams), MolecularSurfaceWireframeParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['molecular-surface-mesh'], param_definition["ParamDefinition"].objectToOptions(MolecularSurfaceVisuals)) });
function getMolecularSurfaceParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(MolecularSurfaceParams);
}
function MolecularSurfaceRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Molecular Surface', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], MolecularSurfaceVisuals);
}
var MolecularSurfaceRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'molecular-surface',
    label: 'Molecular Surface',
    description: 'Displays a molecular surface.',
    factory: MolecularSurfaceRepresentation,
    getParams: getMolecularSurfaceParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(MolecularSurfaceParams),
    defaultColorTheme: { name: 'chain-id' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=molecular-surface.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/orientation-ellipsoid-mesh.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */













var OrientationEllipsoidMeshParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), { sizeFactor: param_definition["ParamDefinition"].Numeric(1, { min: 0, max: 2, step: 0.1 }), detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo) });
function OrientationEllipsoidMeshVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(OrientationEllipsoidMeshParams),
        createGeometry: createOrientationEllipsoidMesh,
        createLocationIterator: UnitIterator,
        getLoci: getUnitLoci,
        eachLocation: eachUnit,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail);
        }
    }, materialId);
}
function isUnitApplicable(unit) {
    if (mol_model_structure["Unit"].Traits.is(unit.traits, 1 /* MultiChain */))
        return false;
    if (mol_model_structure["Unit"].Traits.is(unit.traits, 2 /* Partitioned */))
        return false;
    if (mol_model_structure["Unit"].isCoarse(unit))
        return true;
    if (unit.elements.length === 0)
        return false;
    unit.model.atomicHierarchy.derived.residue.moleculeType;
    var rI = unit.residueIndex[unit.elements[0]];
    var mt = unit.model.atomicHierarchy.derived.residue.moleculeType[rI];
    if (mt === 3 /* Ion */)
        return false;
    if (mt === 2 /* Water */)
        return false;
    return true;
}
function createOrientationEllipsoidMesh(ctx, unit, structure, theme, props, mesh) {
    if (!isUnitApplicable(unit))
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var detail = props.detail, sizeFactor = props.sizeFactor;
    var vertexCount = 256;
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 2, mesh);
    var axes = unit.principalAxes.boxAxes;
    var origin = axes.origin, dirA = axes.dirA, dirB = axes.dirB;
    var size = geometry["a" /* Axes3D */].size(Object(linear_algebra["Vec3"])(), axes);
    linear_algebra["Vec3"].scale(size, size, sizeFactor / 2);
    var radiusScale = linear_algebra["Vec3"].create(size[2], size[1], size[0]);
    builderState.currentGroup = 0;
    Object(ellipsoid["a" /* addEllipsoid */])(builderState, origin, dirA, dirB, radiusScale, detail + 1);
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
//
function UnitIterator(structureGroup) {
    var group = structureGroup.group, structure = structureGroup.structure;
    var groupCount = 1;
    var instanceCount = group.units.length;
    var location = mol_model_structure["StructureElement"].Location.create(structure);
    var getLocation = function (groupIndex, instanceIndex) {
        var unit = group.units[instanceIndex];
        location.unit = unit;
        location.element = unit.elements[groupIndex];
        return location;
    };
    return Object(location_iterator["a" /* LocationIterator */])(groupCount, instanceCount, getLocation);
}
function getUnitLoci(pickingId, structureGroup, id) {
    var objectId = pickingId.objectId, instanceId = pickingId.instanceId;
    if (id === objectId) {
        var structure = structureGroup.structure, group = structureGroup.group;
        var unit = group.units[instanceId];
        var indices = mol_data_int["OrderedSet"].ofBounds(0, unit.elements.length);
        return mol_model_structure["StructureElement"].Loci(structure, [{ unit: unit, indices: indices }]);
    }
    return mol_model_loci["EmptyLoci"];
}
function eachUnit(loci, structureGroup, apply) {
    var changed = false;
    if (!mol_model_structure["StructureElement"].Loci.is(loci))
        return false;
    var structure = structureGroup.structure, group = structureGroup.group;
    if (!mol_model_structure["Structure"].areEquivalent(loci.structure, structure))
        return false;
    var elementCount = group.elements.length;
    for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
        var e = _a[_i];
        var unitIdx = group.unitIndexMap.get(e.unit.id);
        if (unitIdx !== undefined) {
            if (mol_data_int["OrderedSet"].size(e.indices) === elementCount) {
                if (apply(mol_data_int["Interval"].ofSingleton(unitIdx)))
                    changed = true;
            }
        }
    }
    return changed;
}
//# sourceMappingURL=orientation-ellipsoid-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/orientation.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var OrientationVisuals = {
    'orientation-ellipsoid-mesh': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Orientation ellipsoid mesh', ctx, getParams, OrientationEllipsoidMeshVisual); },
};
var OrientationParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, OrientationEllipsoidMeshParams), { visuals: param_definition["ParamDefinition"].MultiSelect(['orientation-ellipsoid-mesh'], param_definition["ParamDefinition"].objectToOptions(OrientationVisuals)) });
function getOrientationParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(OrientationParams);
}
function OrientationRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Orientation', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], OrientationVisuals);
}
var OrientationRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'orientation',
    label: 'Orientation',
    description: 'Displays orientation ellipsoids for polymer chains.',
    factory: OrientationRepresentation,
    getParams: getOrientationParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(OrientationParams),
    defaultColorTheme: { name: 'chain-id' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=orientation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-geo/geometry/points/points.js
var points_points = __webpack_require__(257);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-geo/geometry/points/points-builder.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */


var points_builder_PointsBuilder;
(function (PointsBuilder) {
    function create(initialCount, chunkSize, points) {
        if (initialCount === void 0) { initialCount = 2048; }
        if (chunkSize === void 0) { chunkSize = 1024; }
        var centers = util["a" /* ChunkedArray */].create(Float32Array, 3, chunkSize, points ? points.centerBuffer.ref.value : initialCount);
        var groups = util["a" /* ChunkedArray */].create(Float32Array, 1, chunkSize, points ? points.groupBuffer.ref.value : initialCount);
        return {
            add: function (x, y, z, group) {
                util["a" /* ChunkedArray */].add3(centers, x, y, z);
                util["a" /* ChunkedArray */].add(groups, group);
            },
            getPoints: function () {
                var cb = util["a" /* ChunkedArray */].compact(centers, true);
                var gb = util["a" /* ChunkedArray */].compact(groups, true);
                return points_points["a" /* Points */].create(cb, gb, centers.elementCount, points);
            }
        };
    }
    PointsBuilder.create = create;
})(points_builder_PointsBuilder || (points_builder_PointsBuilder = {}));
//# sourceMappingURL=points-builder.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/element-point.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */








var ElementPointParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["e" /* UnitsPointsParams */]), {
    // sizeFactor: PD.Numeric(1.0, { min: 0, max: 10, step: 0.01 }),
    pointSizeAttenuation: param_definition["ParamDefinition"].Boolean(false), ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false), traceOnly: param_definition["ParamDefinition"].Boolean(false) });
// TODO size
function createElementPoint(ctx, unit, structure, theme, props, points) {
    var ignoreHydrogens = props.ignoreHydrogens, traceOnly = props.traceOnly; // TODO sizeFactor
    var elements = unit.elements;
    var n = elements.length;
    var builder = points_builder_PointsBuilder.create(n, n / 10, points);
    var pos = unit.conformation.invariantPosition;
    var p = linear_algebra["Vec3"].zero();
    for (var i = 0; i < n; ++i) {
        if (ignoreHydrogens && Object(common["k" /* isHydrogen */])(unit, elements[i]))
            continue;
        if (traceOnly && !Object(common["l" /* isTrace */])(unit, elements[i]))
            continue;
        pos(elements[i], p);
        builder.add(p[0], p[1], p[2], i);
    }
    var pt = builder.getPoints();
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    pt.setBoundingSphere(sphere);
    return pt;
}
function ElementPointVisual(materialId) {
    return Object(units_visual["f" /* UnitsPointsVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(ElementPointParams),
        createGeometry: createElementPoint,
        createLocationIterator: element_ElementIterator.fromGroup,
        getLoci: getElementLoci,
        eachLocation: eachElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                newProps.traceOnly !== currentProps.traceOnly);
        }
    }, materialId);
}
//# sourceMappingURL=element-point.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/point.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var PointVisuals = {
    'element-point': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Points', ctx, getParams, ElementPointVisual); },
};
var PointParams = Object(tslib_es6["__assign"])({}, ElementPointParams);
function getPointParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(PointParams);
}
function PointRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Point', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], PointVisuals);
}
var PointRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'point',
    label: 'Point',
    description: 'Displays elements (atoms, coarse spheres) as spheres.',
    factory: PointRepresentation,
    getParams: getPointParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(PointParams),
    defaultColorTheme: { name: 'element-symbol' },
    defaultSizeTheme: { name: 'physical' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=point.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/polymer-tube-mesh.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */














var PolymerTubeMeshParams = {
    sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }),
    detail: param_definition["ParamDefinition"].Numeric(0, { min: 0, max: 3, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
    linearSegments: param_definition["ParamDefinition"].Numeric(8, { min: 1, max: 48, step: 1 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
    radialSegments: param_definition["ParamDefinition"].Numeric(16, { min: 2, max: 56, step: 2 }, base["a" /* BaseGeometry */].CustomQualityParamInfo),
};
var DefaultPolymerTubeMeshProps = param_definition["ParamDefinition"].getDefaultValues(PolymerTubeMeshParams);
var polymer_tube_mesh_tmpV1 = Object(linear_algebra["Vec3"])();
function createPolymerTubeMesh(ctx, unit, structure, theme, props, mesh) {
    var polymerElementCount = unit.polymerElements.length;
    if (!polymerElementCount)
        return mesh_mesh["a" /* Mesh */].createEmpty(mesh);
    var sizeFactor = props.sizeFactor, detail = props.detail, linearSegments = props.linearSegments, radialSegments = props.radialSegments;
    var vertexCount = linearSegments * radialSegments * polymerElementCount + (radialSegments + 1) * polymerElementCount * 2;
    var builderState = mesh_builder["a" /* MeshBuilder */].createState(vertexCount, vertexCount / 10, mesh);
    var state = createCurveSegmentState(linearSegments);
    var curvePoints = state.curvePoints, normalVectors = state.normalVectors, binormalVectors = state.binormalVectors, widthValues = state.widthValues, heightValues = state.heightValues;
    var i = 0;
    var polymerTraceIt = PolymerTraceIterator(unit, structure);
    while (polymerTraceIt.hasNext) {
        var v = polymerTraceIt.move();
        builderState.currentGroup = i;
        var isNucleicType = Object(types["isNucleic"])(v.moleculeType);
        var isHelix = types["SecondaryStructureType"].is(v.secStrucType, 2 /* Helix */);
        var tension = isHelix ? HelixTension : StandardTension;
        var shift = isNucleicType ? NucleicShift : StandardShift;
        interpolateCurveSegment(state, v, tension, shift);
        var startCap = v.secStrucFirst || v.coarseBackboneFirst || v.first;
        var endCap = v.secStrucLast || v.coarseBackboneLast || v.last;
        var s0 = theme.size.size(v.centerPrev) * sizeFactor;
        var s1 = theme.size.size(v.center) * sizeFactor;
        var s2 = theme.size.size(v.centerNext) * sizeFactor;
        interpolateSizes(state, s0, s1, s2, s0, s1, s2, shift);
        var segmentCount = linearSegments;
        if (v.initial) {
            segmentCount = Math.max(Math.round(linearSegments * shift), 1);
            var offset = linearSegments - segmentCount;
            curvePoints.copyWithin(0, offset * 3);
            binormalVectors.copyWithin(0, offset * 3);
            normalVectors.copyWithin(0, offset * 3);
            widthValues.copyWithin(0, offset * 3);
            heightValues.copyWithin(0, offset * 3);
            linear_algebra["Vec3"].fromArray(polymer_tube_mesh_tmpV1, curvePoints, 3);
            linear_algebra["Vec3"].normalize(polymer_tube_mesh_tmpV1, linear_algebra["Vec3"].sub(polymer_tube_mesh_tmpV1, v.p2, polymer_tube_mesh_tmpV1));
            linear_algebra["Vec3"].scaleAndAdd(polymer_tube_mesh_tmpV1, v.p2, polymer_tube_mesh_tmpV1, s1 * OverhangFactor);
            linear_algebra["Vec3"].toArray(polymer_tube_mesh_tmpV1, curvePoints, 0);
        }
        else if (v.final) {
            segmentCount = Math.max(Math.round(linearSegments * (1 - shift)), 1);
            linear_algebra["Vec3"].fromArray(polymer_tube_mesh_tmpV1, curvePoints, segmentCount * 3 - 3);
            linear_algebra["Vec3"].normalize(polymer_tube_mesh_tmpV1, linear_algebra["Vec3"].sub(polymer_tube_mesh_tmpV1, v.p2, polymer_tube_mesh_tmpV1));
            linear_algebra["Vec3"].scaleAndAdd(polymer_tube_mesh_tmpV1, v.p2, polymer_tube_mesh_tmpV1, s1 * OverhangFactor);
            linear_algebra["Vec3"].toArray(polymer_tube_mesh_tmpV1, curvePoints, segmentCount * 3);
        }
        if (v.initial === true && v.final === true) {
            Object(builder_sphere["a" /* addSphere */])(builderState, v.p2, s1 * 2, detail);
        }
        else if (radialSegments === 2) {
            addRibbon(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, 0);
        }
        else if (radialSegments === 4) {
            addSheet(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, widthValues, heightValues, 0, startCap, endCap);
        }
        else {
            addTube(builderState, curvePoints, normalVectors, binormalVectors, segmentCount, radialSegments, widthValues, heightValues, 1, startCap, endCap);
        }
        ++i;
    }
    var m = mesh_builder["a" /* MeshBuilder */].getMesh(builderState);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * props.sizeFactor);
    m.setBoundingSphere(sphere);
    return m;
}
var PolymerTubeParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["c" /* UnitsMeshParams */]), PolymerTubeMeshParams);
function PolymerTubeVisual(materialId) {
    return Object(units_visual["d" /* UnitsMeshVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(PolymerTubeParams),
        createGeometry: createPolymerTubeMesh,
        createLocationIterator: polymer_PolymerLocationIterator.fromGroup,
        getLoci: getPolymerElementLoci,
        eachLocation: eachPolymerElement,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.detail !== currentProps.detail ||
                newProps.linearSegments !== currentProps.linearSegments ||
                newProps.radialSegments !== currentProps.radialSegments);
        }
    }, materialId);
}
//# sourceMappingURL=polymer-tube-mesh.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/putty.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var PuttyVisuals = {
    'polymer-tube': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Polymer tube mesh', ctx, getParams, PolymerTubeVisual); },
    'polymer-gap': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Polymer gap cylinder', ctx, getParams, PolymerGapVisual); },
};
var PuttyParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, PolymerTubeParams), PolymerGapParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(0.2, { min: 0, max: 10, step: 0.01 }), visuals: param_definition["ParamDefinition"].MultiSelect(['polymer-tube', 'polymer-gap'], param_definition["ParamDefinition"].objectToOptions(PuttyVisuals)) });
function getPuttyParams(ctx, structure) {
    var params = param_definition["ParamDefinition"].clone(PuttyParams);
    var hasNucleotides = false;
    var hasGaps = false;
    structure.units.forEach(function (u) {
        if (!hasNucleotides && mol_model_structure["Unit"].isAtomic(u) && u.nucleotideElements.length)
            hasNucleotides = true;
        if (!hasGaps && u.gapElements.length)
            hasGaps = true;
    });
    params.visuals.defaultValue = ['polymer-tube'];
    if (hasGaps)
        params.visuals.defaultValue.push('polymer-gap');
    return params;
}
function PuttyRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Putty', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], PuttyVisuals);
}
var PuttyRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'putty',
    label: 'Putty',
    description: 'Displays a tube smoothly following the trace atoms of polymers.',
    factory: PuttyRepresentation,
    getParams: getPuttyParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(PuttyParams),
    defaultColorTheme: { name: 'chain-id' },
    defaultSizeTheme: { name: 'uncertainty' },
    isApplicable: function (structure) { return structure.polymerResidueCount > 0; },
    ensureCustomProperties: {
        attach: function (ctx, structure) { return secondary_structure["a" /* SecondaryStructureProvider */].attach(ctx, structure, void 0, true); },
        detach: function (data) { return secondary_structure["a" /* SecondaryStructureProvider */].ref(data, false); }
    }
});
//# sourceMappingURL=putty.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/spacefill.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var SpacefillVisuals = {
    'element-sphere': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Sphere mesh', ctx, getParams, getElementSphereVisual(ctx.webgl)); },
};
var SpacefillParams = Object(tslib_es6["__assign"])({}, ElementSphereParams);
function getSpacefillParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(SpacefillParams);
}
function SpacefillRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Spacefill', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], SpacefillVisuals);
}
var SpacefillRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'spacefill',
    label: 'Spacefill',
    description: 'Displays atomic/coarse elements as spheres.',
    factory: SpacefillRepresentation,
    getParams: getSpacefillParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(SpacefillParams),
    defaultColorTheme: { name: 'element-symbol' },
    defaultSizeTheme: { name: 'physical' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=spacefill.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/bond-intra-unit-line.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */












function createIntraUnitBondLines(ctx, unit, structure, theme, props, lines) {
    if (!mol_model_structure["Unit"].isAtomic(unit))
        return lines_lines["a" /* Lines */].createEmpty(lines);
    var location = mol_model_structure["StructureElement"].Location.create(structure, unit);
    var elements = unit.elements;
    var bonds = unit.bonds;
    var edgeCount = bonds.edgeCount, a = bonds.a, b = bonds.b, edgeProps = bonds.edgeProps, offset = bonds.offset;
    var _order = edgeProps.order, _flags = edgeProps.flags;
    var sizeFactor = props.sizeFactor, ignoreHydrogens = props.ignoreHydrogens, includeTypes = props.includeTypes, excludeTypes = props.excludeTypes;
    var include = types["BondType"].fromNames(includeTypes);
    var exclude = types["BondType"].fromNames(excludeTypes);
    var ignoreHydrogen = ignoreHydrogens ? function (edgeIndex) {
        return Object(common["k" /* isHydrogen */])(unit, elements[a[edgeIndex]]) || Object(common["k" /* isHydrogen */])(unit, elements[b[edgeIndex]]);
    } : function () { return false; };
    if (!edgeCount)
        return lines_lines["a" /* Lines */].createEmpty(lines);
    var vRef = linear_algebra["Vec3"].zero();
    var pos = unit.conformation.invariantPosition;
    var builderProps = {
        linkCount: edgeCount * 2,
        referencePosition: function (edgeIndex) {
            var _a, _b;
            var aI = a[edgeIndex], bI = b[edgeIndex];
            if (aI > bI)
                _a = [bI, aI], aI = _a[0], bI = _a[1];
            if (offset[aI + 1] - offset[aI] === 1)
                _b = [bI, aI], aI = _b[0], bI = _b[1];
            // TODO prefer reference atoms in rings
            for (var i = offset[aI], il = offset[aI + 1]; i < il; ++i) {
                var _bI = b[i];
                if (_bI !== bI && _bI !== aI)
                    return pos(elements[_bI], vRef);
            }
            for (var i = offset[bI], il = offset[bI + 1]; i < il; ++i) {
                var _aI = a[i];
                if (_aI !== aI && _aI !== bI)
                    return pos(elements[_aI], vRef);
            }
            return null;
        },
        position: function (posA, posB, edgeIndex) {
            pos(elements[a[edgeIndex]], posA);
            pos(elements[b[edgeIndex]], posB);
        },
        style: function (edgeIndex) {
            var o = _order[edgeIndex];
            var f = mol_util["a" /* BitFlags */].create(_flags[edgeIndex]);
            if (types["BondType"].is(f, 2 /* MetallicCoordination */) || types["BondType"].is(f, 4 /* HydrogenBond */)) {
                // show metall coordinations and hydrogen bonds with dashed cylinders
                return util_link["c" /* LinkStyle */].Dashed;
            }
            else if (o === 2) {
                return util_link["c" /* LinkStyle */].Double;
            }
            else if (o === 3) {
                return util_link["c" /* LinkStyle */].Triple;
            }
            else {
                return util_link["c" /* LinkStyle */].Solid;
            }
        },
        radius: function (edgeIndex) {
            location.element = elements[a[edgeIndex]];
            var sizeA = theme.size.size(location);
            location.element = elements[b[edgeIndex]];
            var sizeB = theme.size.size(location);
            return Math.min(sizeA, sizeB) * sizeFactor;
        },
        ignore: function (edgeIndex) { return ignoreHydrogen(edgeIndex) || ignoreBondType(include, exclude, _flags[edgeIndex]); }
    };
    var l = Object(util_link["e" /* createLinkLines */])(ctx, builderProps, props, lines);
    var sphere = geometry["g" /* Sphere3D */].expand(Object(geometry["g" /* Sphere3D */])(), unit.boundary.sphere, 1 * sizeFactor);
    l.setBoundingSphere(sphere);
    return l;
}
var IntraUnitBondLineParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, units_visual["a" /* UnitsLinesParams */]), BondLineParams), { ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function IntraUnitBondLineVisual(materialId) {
    return Object(units_visual["b" /* UnitsLinesVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(IntraUnitBondLineParams),
        createGeometry: createIntraUnitBondLines,
        createLocationIterator: bond_BondIterator.fromGroup,
        getLoci: getIntraBondLoci,
        eachLocation: eachIntraBond,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.linkScale !== currentProps.linkScale ||
                newProps.linkSpacing !== currentProps.linkSpacing ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.includeTypes, currentProps.includeTypes) ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.excludeTypes, currentProps.excludeTypes));
        }
    }, materialId);
}
//# sourceMappingURL=bond-intra-unit-line.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/visual/bond-inter-unit-line.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var bond_inter_unit_line_tmpRefPosBondIt = new mol_model_structure["Bond"].ElementBondIterator();
function bond_inter_unit_line_setRefPosition(pos, structure, unit, index) {
    bond_inter_unit_line_tmpRefPosBondIt.setElement(structure, unit, index);
    while (bond_inter_unit_line_tmpRefPosBondIt.hasNext) {
        var bA = bond_inter_unit_line_tmpRefPosBondIt.move();
        bA.otherUnit.conformation.position(bA.otherUnit.elements[bA.otherIndex], pos);
        return pos;
    }
    return null;
}
var bond_inter_unit_line_tmpRef = Object(linear_algebra["Vec3"])();
var bond_inter_unit_line_tmpLoc = mol_model_structure["StructureElement"].Location.create(void 0);
function createInterUnitBondLines(ctx, structure, theme, props, lines) {
    var bonds = structure.interUnitBonds;
    var edgeCount = bonds.edgeCount, edges = bonds.edges;
    var sizeFactor = props.sizeFactor, ignoreHydrogens = props.ignoreHydrogens, includeTypes = props.includeTypes, excludeTypes = props.excludeTypes;
    var include = types["BondType"].fromNames(includeTypes);
    var exclude = types["BondType"].fromNames(excludeTypes);
    var ignoreHydrogen = ignoreHydrogens ? function (edgeIndex) {
        var b = edges[edgeIndex];
        var uA = b.unitA, uB = b.unitB;
        return Object(common["k" /* isHydrogen */])(uA, uA.elements[b.indexA]) || Object(common["k" /* isHydrogen */])(uB, uB.elements[b.indexB]);
    } : function () { return false; };
    if (!edgeCount)
        return lines_lines["a" /* Lines */].createEmpty(lines);
    var builderProps = {
        linkCount: edgeCount,
        referencePosition: function (edgeIndex) {
            var b = edges[edgeIndex];
            var unitA, unitB;
            var indexA, indexB;
            if (b.unitA.id < b.unitB.id) {
                unitA = b.unitA, unitB = b.unitB;
                indexA = b.indexA, indexB = b.indexB;
            }
            else if (b.unitA.id > b.unitB.id) {
                unitA = b.unitB, unitB = b.unitA;
                indexA = b.indexB, indexB = b.indexA;
            }
            else {
                throw new Error('same units in createInterUnitBondCylinderMesh');
            }
            return bond_inter_unit_line_setRefPosition(bond_inter_unit_line_tmpRef, structure, unitA, indexA) || bond_inter_unit_line_setRefPosition(bond_inter_unit_line_tmpRef, structure, unitB, indexB);
        },
        position: function (posA, posB, edgeIndex) {
            var b = edges[edgeIndex];
            var uA = b.unitA, uB = b.unitB;
            uA.conformation.position(uA.elements[b.indexA], posA);
            uB.conformation.position(uB.elements[b.indexB], posB);
        },
        style: function (edgeIndex) {
            var o = edges[edgeIndex].props.order;
            var f = mol_util["a" /* BitFlags */].create(edges[edgeIndex].props.flag);
            if (types["BondType"].is(f, 2 /* MetallicCoordination */) || types["BondType"].is(f, 4 /* HydrogenBond */)) {
                // show metall coordinations and hydrogen bonds with dashed cylinders
                return util_link["c" /* LinkStyle */].Dashed;
            }
            else if (o === 2) {
                return util_link["c" /* LinkStyle */].Double;
            }
            else if (o === 3) {
                return util_link["c" /* LinkStyle */].Triple;
            }
            else {
                return util_link["c" /* LinkStyle */].Solid;
            }
        },
        radius: function (edgeIndex) {
            var b = edges[edgeIndex];
            bond_inter_unit_line_tmpLoc.structure = structure;
            bond_inter_unit_line_tmpLoc.unit = b.unitA;
            bond_inter_unit_line_tmpLoc.element = b.unitA.elements[b.indexA];
            var sizeA = theme.size.size(bond_inter_unit_line_tmpLoc);
            bond_inter_unit_line_tmpLoc.unit = b.unitB;
            bond_inter_unit_line_tmpLoc.element = b.unitB.elements[b.indexB];
            var sizeB = theme.size.size(bond_inter_unit_line_tmpLoc);
            return Math.min(sizeA, sizeB) * sizeFactor;
        },
        ignore: function (edgeIndex) { return ignoreHydrogen(edgeIndex) || ignoreBondType(include, exclude, edges[edgeIndex].props.flag); }
    };
    return Object(util_link["e" /* createLinkLines */])(ctx, builderProps, props, lines);
}
var InterUnitBondLineParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, complex_visual["a" /* ComplexLinesParams */]), BondLineParams), { ignoreHydrogens: param_definition["ParamDefinition"].Boolean(false) });
function InterUnitBondLineVisual(materialId) {
    return Object(complex_visual["b" /* ComplexLinesVisual */])({
        defaultProps: param_definition["ParamDefinition"].getDefaultValues(InterUnitBondLineParams),
        createGeometry: createInterUnitBondLines,
        createLocationIterator: bond_BondIterator.fromStructure,
        getLoci: getInterBondLoci,
        eachLocation: eachInterBond,
        setUpdateState: function (state, newProps, currentProps) {
            state.createGeometry = (newProps.sizeFactor !== currentProps.sizeFactor ||
                newProps.linkScale !== currentProps.linkScale ||
                newProps.linkSpacing !== currentProps.linkSpacing ||
                newProps.ignoreHydrogens !== currentProps.ignoreHydrogens ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.includeTypes, currentProps.includeTypes) ||
                !Object(mol_util["g" /* arrayEqual */])(newProps.excludeTypes, currentProps.excludeTypes));
        }
    }, materialId);
}
//# sourceMappingURL=bond-inter-unit-line.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/representation/line.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */









var LineVisuals = {
    'intra-bond': function (ctx, getParams) { return Object(units_representation["a" /* UnitsRepresentation */])('Intra-unit bond line', ctx, getParams, IntraUnitBondLineVisual); },
    'inter-bond': function (ctx, getParams) { return Object(complex_representation["a" /* ComplexRepresentation */])('Inter-unit bond line', ctx, getParams, InterUnitBondLineVisual); },
};
var LineParams = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, IntraUnitBondLineParams), InterUnitBondLineParams), { sizeFactor: param_definition["ParamDefinition"].Numeric(1.0, { min: 0.01, max: 10, step: 0.01 }), unitKinds: Object(structure_params["i" /* getUnitKindsParam */])(['atomic']), visuals: param_definition["ParamDefinition"].MultiSelect(['intra-bond', 'inter-bond'], param_definition["ParamDefinition"].objectToOptions(LineVisuals)) });
function getLineParams(ctx, structure) {
    return param_definition["ParamDefinition"].clone(LineParams);
}
function LineRepresentation(ctx, getParams) {
    return mol_repr_representation["a" /* Representation */].createMulti('Line', ctx, getParams, structure_representation["c" /* StructureRepresentationStateBuilder */], LineVisuals);
}
var LineRepresentationProvider = Object(structure_representation["b" /* StructureRepresentationProvider */])({
    name: 'line',
    label: 'Line',
    description: 'Displays bonds as lines.',
    factory: LineRepresentation,
    getParams: getLineParams,
    defaultValues: param_definition["ParamDefinition"].getDefaultValues(LineParams),
    defaultColorTheme: { name: 'element-symbol' },
    defaultSizeTheme: { name: 'uniform' },
    isApplicable: function (structure) { return structure.elementCount > 0; }
});
//# sourceMappingURL=line.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-repr/structure/registry.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */















var registry_StructureRepresentationRegistry = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(StructureRepresentationRegistry, _super);
    function StructureRepresentationRegistry() {
        var _this = _super.call(this) || this;
        Object(object["c" /* objectForEach */])(StructureRepresentationRegistry.BuiltIn, function (p, k) {
            if (p.name !== k)
                throw new Error("Fix BuiltInStructureRepresentations to have matching names. " + p.name + " " + k);
            _this.add(p);
        });
        return _this;
    }
    return StructureRepresentationRegistry;
}(mol_repr_representation["b" /* RepresentationRegistry */]));

(function (StructureRepresentationRegistry) {
    StructureRepresentationRegistry.BuiltIn = {
        'cartoon': CartoonRepresentationProvider,
        'ball-and-stick': BallAndStickRepresentationProvider,
        'carbohydrate': CarbohydrateRepresentationProvider,
        'ellipsoid': EllipsoidRepresentationProvider,
        'gaussian-surface': GaussianSurfaceRepresentationProvider,
        // 'gaussian-volume': GaussianVolumeRepresentationProvider, // TODO disabled for now, needs more work
        'label': LabelRepresentationProvider,
        'line': LineRepresentationProvider,
        'molecular-surface': MolecularSurfaceRepresentationProvider,
        'orientation': OrientationRepresentationProvider,
        'point': PointRepresentationProvider,
        'putty': PuttyRepresentationProvider,
        'spacefill': SpacefillRepresentationProvider,
    };
})(registry_StructureRepresentationRegistry || (registry_StructureRepresentationRegistry = {}));
//# sourceMappingURL=registry.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/volume/registry.js + 1 modules
var registry = __webpack_require__(379);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/color.js + 17 modules
var color = __webpack_require__(196);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/size.js + 1 modules
var mol_theme_size = __webpack_require__(150);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/index.js
var mol_util_color = __webpack_require__(24);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/data-source.js
var data_source = __webpack_require__(177);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/input/input-observer.js
var input_observer = __webpack_require__(84);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/log-entry.js
var log_entry = __webpack_require__(253);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/rx-event-helper.js
var rx_event_helper = __webpack_require__(180);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior.js + 22 modules
var behavior = __webpack_require__(170);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/behavior/behavior.js
var behavior_behavior = __webpack_require__(68);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/command.js
var command = __webpack_require__(95);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/layout.js
/**
 * Copyright (c) 2018-2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var regionStateOptions = [
    ['full', 'Full'],
    ['collapsed', 'Collapsed'],
    ['hidden', 'Hidden'],
];
var simpleRegionStateOptions = [
    ['full', 'Full'],
    ['hidden', 'Hidden'],
];
var PluginLayoutStateParams = {
    isExpanded: param_definition["ParamDefinition"].Boolean(false),
    showControls: param_definition["ParamDefinition"].Boolean(true),
    regionState: param_definition["ParamDefinition"].Group({
        left: param_definition["ParamDefinition"].Select('full', regionStateOptions),
        top: param_definition["ParamDefinition"].Select('full', simpleRegionStateOptions),
        right: param_definition["ParamDefinition"].Select('full', simpleRegionStateOptions),
        bottom: param_definition["ParamDefinition"].Select('full', simpleRegionStateOptions),
    }),
    controlsDisplay: param_definition["ParamDefinition"].Value('outside', { isHidden: true })
};
var layout_PluginLayout = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PluginLayout, _super);
    function PluginLayout(context) {
        var _this = _super.call(this, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, param_definition["ParamDefinition"].getDefaultValues(PluginLayoutStateParams)), (context.spec.layout && context.spec.layout.initial))) || this;
        _this.context = context;
        _this.events = {
            updated: _this.ev()
        };
        _this.rootState = void 0;
        commands["PluginCommands"].Layout.Update.subscribe(context, function (e) { return _this.updateProps(e.state); });
        // TODO how best make sure it runs on node.js as well as in the browser?
        if (typeof document !== 'undefined') {
            // <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' />
            _this.expandedViewport = document.createElement('meta');
            _this.expandedViewport.name = 'viewport';
            _this.expandedViewport.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0';
        }
        return _this;
    }
    PluginLayout.prototype.updateProps = function (state) {
        var prevExpanded = !!this.state.isExpanded;
        this.updateState(state);
        if (this.root && typeof state.isExpanded === 'boolean' && state.isExpanded !== prevExpanded)
            this.handleExpand();
        this.events.updated.next();
    };
    PluginLayout.prototype.setProps = function (props) {
        this.updateState(props);
    };
    PluginLayout.prototype.setRoot = function (root) {
        this.root = root;
        if (this.state.isExpanded)
            this.handleExpand();
    };
    PluginLayout.prototype.getScrollElement = function () {
        if (document.scrollingElement)
            return document.scrollingElement;
        if (document.documentElement)
            return document.documentElement;
        return document.body;
    };
    PluginLayout.prototype.handleExpand = function () {
        try {
            var body = document.getElementsByTagName('body')[0];
            var head = document.getElementsByTagName('head')[0];
            if (!body || !head || !this.root)
                return;
            if (this.state.isExpanded) {
                var children = head.children;
                var viewports = [];
                var hasExp = false;
                for (var i = 0; i < children.length; i++) {
                    if (children[i] === this.expandedViewport) {
                        hasExp = true;
                    }
                    else if ((children[i].name || '').toLowerCase() === 'viewport') {
                        viewports.push(children[i]);
                    }
                }
                for (var _i = 0, viewports_1 = viewports; _i < viewports_1.length; _i++) {
                    var v = viewports_1[_i];
                    head.removeChild(v);
                }
                if (!hasExp)
                    head.appendChild(this.expandedViewport);
                var s = body.style;
                var doc = this.getScrollElement();
                var scrollLeft = doc.scrollLeft;
                var scrollTop = doc.scrollTop;
                this.rootState = {
                    top: s.top, bottom: s.bottom, right: s.right, left: s.left,
                    scrollTop: scrollTop, scrollLeft: scrollLeft,
                    position: s.position, overflow: s.overflow,
                    viewports: viewports,
                    zIndex: this.root.style.zIndex,
                    width: s.width, height: s.height,
                    maxWidth: s.maxWidth, maxHeight: s.maxHeight,
                    margin: s.margin, marginLeft: s.marginLeft, marginRight: s.marginRight, marginTop: s.marginTop, marginBottom: s.marginBottom
                };
                s.overflow = 'hidden';
                s.position = 'fixed';
                s.top = '0';
                s.bottom = '0';
                s.right = '0';
                s.left = '0';
                s.width = '100%';
                s.height = '100%';
                s.maxWidth = '100%';
                s.maxHeight = '100%';
                s.margin = '0';
                s.marginLeft = '0';
                s.marginRight = '0';
                s.marginTop = '0';
                s.marginBottom = '0';
                // TODO: setting this breaks viewport controls for some reason. Is there a fix?
                // this.root.style.zIndex = '100000';
            }
            else {
                var children = head.children;
                for (var i = 0; i < children.length; i++) {
                    if (children[i] === this.expandedViewport) {
                        head.removeChild(this.expandedViewport);
                        break;
                    }
                }
                if (this.rootState) {
                    var t = this.rootState;
                    for (var _a = 0, _b = t.viewports; _a < _b.length; _a++) {
                        var v = _b[_a];
                        head.appendChild(v);
                    }
                    var s = body.style;
                    s.top = t.top;
                    s.bottom = t.bottom;
                    s.left = t.left;
                    s.right = t.right;
                    s.width = t.width;
                    s.height = t.height;
                    s.maxWidth = t.maxWidth;
                    s.maxHeight = t.maxHeight;
                    s.margin = t.margin;
                    s.marginLeft = t.marginLeft;
                    s.marginRight = t.marginRight;
                    s.marginTop = t.marginTop;
                    s.marginBottom = t.marginBottom;
                    s.position = t.position;
                    s.overflow = t.overflow || '';
                    var doc = this.getScrollElement();
                    doc.scrollTop = t.scrollTop;
                    doc.scrollLeft = t.scrollLeft;
                    this.rootState = void 0;
                    this.root.style.zIndex = t.zIndex;
                }
            }
        }
        catch (e) {
            var msg = 'Layout change error, you might have to reload the page.';
            this.context.log.error(msg);
            console.error(msg, e);
        }
    };
    return PluginLayout;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));

//# sourceMappingURL=layout.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/state.js
var mol_plugin_state = __webpack_require__(372);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/util/substructure-parent-helper.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var substructure_parent_helper_SubstructureParentHelper = /** @class */ (function () {
    function SubstructureParentHelper(plugin) {
        var _this = this;
        this.plugin = plugin;
        this.ev = rx_event_helper["RxEventHelper"].create();
        this.events = {
            updated: this.ev(),
            removed: this.ev(),
        };
        // private decorators = new Map<string, string[]>();
        this.root = new Map();
        this.tracked = new Map();
        plugin.state.data.events.object.created.subscribe(function (e) {
            _this.addMapping(e.state, e.ref, e.obj);
        });
        plugin.state.data.events.object.removed.subscribe(function (e) {
            if (_this.removeMapping(e.ref)) {
                _this.events.removed.next({ ref: e.ref, obj: e.obj });
            }
        });
        plugin.state.data.events.object.updated.subscribe(function (e) {
            if (_this.updateMapping(e.state, e.ref, e.oldObj, e.obj)) {
                _this.events.updated.next({ ref: e.ref, oldObj: e.oldObj, obj: e.obj });
            }
        });
    }
    SubstructureParentHelper.prototype.getDecorator = function (root) {
        var tree = this.plugin.state.data.tree;
        var children = tree.children.get(root);
        if (children.size !== 1)
            return root;
        var child = children.first();
        if (tree.transforms.get(child).transformer.definition.isDecorator) {
            return this.getDecorator(child);
        }
        return root;
    };
    /** Returns the root node of given structure if existing, takes decorators into account */
    SubstructureParentHelper.prototype.get = function (s, ignoreDecorators) {
        if (ignoreDecorators === void 0) { ignoreDecorators = false; }
        var r = this.root.get(s);
        if (!r)
            return;
        if (ignoreDecorators)
            return this.plugin.state.data.cells.get(r.ref);
        return this.plugin.state.data.cells.get(this.getDecorator(r.ref));
    };
    SubstructureParentHelper.prototype.addMapping = function (state, ref, obj) {
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.is(obj))
            return false;
        this.tracked.set(ref, obj.data);
        // if the structure is already present in the tree, do not rewrite the root.
        if (this.root.has(obj.data)) {
            var e = this.root.get(obj.data);
            e.count++;
        }
        else {
            var parent_1 = state.select(mol_state["StateSelection"].Generators.byRef(ref).rootOfType([objects["a" /* PluginStateObject */].Molecule.Structure]))[0];
            if (!parent_1) {
                this.root.set(obj.data, { ref: ref, count: 1 });
            }
            else {
                this.root.set(obj.data, { ref: parent_1.transform.ref, count: 1 });
            }
        }
        return true;
    };
    SubstructureParentHelper.prototype.removeMapping = function (ref) {
        if (!this.tracked.has(ref))
            return false;
        var s = this.tracked.get(ref);
        this.tracked.delete(ref);
        var root = this.root.get(s);
        if (root.count > 1) {
            root.count--;
        }
        else {
            this.root.delete(s);
        }
        return true;
    };
    SubstructureParentHelper.prototype.updateMapping = function (state, ref, oldObj, obj) {
        if (!objects["a" /* PluginStateObject */].Molecule.Structure.is(obj))
            return false;
        this.removeMapping(ref);
        this.addMapping(state, ref, obj);
        return true;
    };
    SubstructureParentHelper.prototype.dispose = function () {
        this.ev.dispose();
    };
    return SubstructureParentHelper;
}());
//# sourceMappingURL=substructure-parent-helper.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/now.js
var now = __webpack_require__(83);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/execution/observable.js + 1 modules
var observable = __webpack_require__(289);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/util/task-manager.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var task_manager_TaskManager = /** @class */ (function () {
    function TaskManager() {
        this.ev = rx_event_helper["RxEventHelper"].create();
        this.id = 0;
        this.abortRequests = new Map();
        this.currentContext = [];
        this.events = {
            progress: this.ev(),
            finished: this.ev()
        };
    }
    TaskManager.prototype.track = function (internalId, taskId) {
        var _this = this;
        return function (progress) {
            if (progress.canAbort && progress.requestAbort && _this.abortRequests.has(progress.root.progress.taskId)) {
                progress.requestAbort(_this.abortRequests.get(taskId));
            }
            var elapsed = Object(now["b" /* now */])() - progress.root.progress.startedTime;
            _this.events.progress.next({
                id: internalId,
                level: elapsed < 250 ? 'none' : elapsed < 1500 ? 'background' : 'overlay',
                progress: progress
            });
        };
    };
    TaskManager.prototype.run = function (task, createNewContext) {
        if (createNewContext === void 0) { createNewContext = false; }
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var id, ctx, ret;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        id = this.id++;
                        if (createNewContext || this.currentContext.length === 0) {
                            ctx = { ctx: Object(observable["a" /* CreateObservableCtx */])(task, this.track(id, task.id), 100), refCount: 1 };
                        }
                        else {
                            ctx = this.currentContext[this.currentContext.length - 1];
                            ctx.refCount++;
                        }
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, , 3, 4]);
                        return [4 /*yield*/, Object(observable["b" /* ExecuteInContext */])(ctx.ctx, task)];
                    case 2:
                        ret = _a.sent();
                        return [2 /*return*/, ret];
                    case 3:
                        this.events.finished.next({ id: id });
                        this.abortRequests.delete(task.id);
                        ctx.refCount--;
                        if (ctx.refCount === 0)
                            Object(mol_util_array["arrayRemoveInPlace"])(this.currentContext, ctx);
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    TaskManager.prototype.requestAbort = function (progress, reason) {
        this.abortRequests.set(progress.root.progress.taskId, reason);
    };
    TaskManager.prototype.dispose = function () {
        this.ev.dispose();
    };
    return TaskManager;
}());
(function (TaskManager) {
    function delay(time) {
        return new Promise(function (res) { return setTimeout(res, time); });
    }
    function testTask(N) {
        var _this = this;
        return mol_task["b" /* Task */].create('Test', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var i;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        i = 0;
                        _a.label = 1;
                    case 1:
                        if (!(i < N)) return [3 /*break*/, 5];
                        return [4 /*yield*/, delay(100 + Math.random() * 200)];
                    case 2:
                        _a.sent();
                        if (!ctx.shouldUpdate) return [3 /*break*/, 4];
                        return [4 /*yield*/, ctx.update({ message: 'Step ' + i, current: i, max: N, isIndeterminate: false })];
                    case 3:
                        _a.sent();
                        _a.label = 4;
                    case 4:
                        i++;
                        return [3 /*break*/, 1];
                    case 5: return [2 /*return*/];
                }
            });
        }); });
    }
    TaskManager.testTask = testTask;
})(task_manager_TaskManager || (task_manager_TaskManager = {}));
//# sourceMappingURL=task-manager.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/util/toast.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * Adapted from LiteMol (c) David Sehnal
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




var toast_PluginToastManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PluginToastManager, _super);
    function PluginToastManager(plugin) {
        var _this = _super.call(this, { entries: Object(immutable["OrderedMap"])() }) || this;
        _this.events = {
            changed: _this.ev()
        };
        _this.serialNumber = 0;
        _this.serialId = 0;
        commands["PluginCommands"].Toast.Show.subscribe(plugin, function (e) { return _this.show(e); });
        commands["PluginCommands"].Toast.Hide.subscribe(plugin, function (e) { return _this.hide(_this.findByKey(e.key)); });
        return _this;
    }
    PluginToastManager.prototype.findByKey = function (key) {
        return this.state.entries.find(function (e) { return !!e && e.key === key; });
    };
    PluginToastManager.prototype.show = function (toast) {
        var _this = this;
        var entries = this.state.entries;
        var e = void 0;
        var id = ++this.serialId;
        var serialNumber;
        if (toast.key && (e = this.findByKey(toast.key))) {
            if (e.timeout !== void 0)
                clearTimeout(e.timeout);
            serialNumber = e.serialNumber;
            entries = entries.remove(e.id);
        }
        else {
            serialNumber = ++this.serialNumber;
        }
        e = {
            id: id,
            serialNumber: serialNumber,
            key: toast.key,
            title: toast.title,
            message: toast.message,
            timeout: this.timeout(id, toast.timeoutMs),
            hide: function () { return _this.hideId(id); }
        };
        if (this.updateState({ entries: entries.set(id, e) }))
            this.events.changed.next();
    };
    PluginToastManager.prototype.timeout = function (id, delay) {
        var _this = this;
        if (delay === void 0)
            return void 0;
        if (delay < 0)
            delay = 500;
        return setTimeout(function () {
            var e = _this.state.entries.get(id);
            e.timeout = void 0;
            _this.hide(e);
        }, delay);
    };
    PluginToastManager.prototype.hideId = function (id) {
        this.hide(this.state.entries.get(id));
    };
    PluginToastManager.prototype.hide = function (e) {
        if (!e)
            return;
        if (e.timeout !== void 0)
            clearTimeout(e.timeout);
        e.hide = void 0;
        if (this.updateState({ entries: this.state.entries.delete(e.id) }))
            this.events.changed.next();
    };
    return PluginToastManager;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));

//# sourceMappingURL=toast.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/util.js
var mol_canvas3d_util = __webpack_require__(332);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/download.js
var download = __webpack_require__(329);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-task/execution/synchronous.js
var synchronous = __webpack_require__(266);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/helper/camera-helper.js
var camera_helper = __webpack_require__(284);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/set.js
var set = __webpack_require__(90);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/util/viewport-screenshot.js
/**
 * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var viewport_screenshot_ViewportScreenshotHelper = /** @class */ (function () {
    function ViewportScreenshotHelper(plugin) {
        this.plugin = plugin;
        this._params = void 0;
        this.transparent = this.params.transparent.defaultValue;
        this.axes = { name: 'off', params: {} };
        this.currentResolution = this.params.resolution.defaultValue;
        this.canvas = function () {
            var canvas = document.createElement('canvas');
            return canvas;
        }();
    }
    ViewportScreenshotHelper.prototype.createParams = function () {
        var max = Math.min(this.plugin.canvas3d ? this.plugin.canvas3d.webgl.maxRenderbufferSize : 4096, 4096);
        return {
            resolution: param_definition["ParamDefinition"].MappedStatic('viewport', {
                viewport: param_definition["ParamDefinition"].Group({}),
                hd: param_definition["ParamDefinition"].Group({}),
                'full-hd': param_definition["ParamDefinition"].Group({}),
                'ultra-hd': param_definition["ParamDefinition"].Group({}),
                custom: param_definition["ParamDefinition"].Group({
                    width: param_definition["ParamDefinition"].Numeric(1920, { min: 128, max: max, step: 1 }),
                    height: param_definition["ParamDefinition"].Numeric(1080, { min: 128, max: max, step: 1 }),
                }, { isFlat: true })
            }, {
                options: [
                    ['viewport', 'Viewport'],
                    ['hd', 'HD (1280 x 720)'],
                    ['full-hd', 'Full HD (1920 x 1080)'],
                    ['ultra-hd', 'Ultra HD (3840 x 2160)'],
                    ['custom', 'Custom']
                ]
            }),
            transparent: param_definition["ParamDefinition"].Boolean(false),
            axes: camera_helper["b" /* CameraHelperParams */].axes,
        };
    };
    Object.defineProperty(ViewportScreenshotHelper.prototype, "params", {
        get: function () {
            if (this._params)
                return this._params;
            return this._params = this.createParams();
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(ViewportScreenshotHelper.prototype, "values", {
        get: function () {
            return {
                transparent: this.transparent,
                axes: this.axes,
                resolution: this.currentResolution
            };
        },
        enumerable: false,
        configurable: true
    });
    ViewportScreenshotHelper.prototype.getCanvasSize = function () {
        var _a, _b;
        return {
            width: ((_a = this.plugin.canvas3d) === null || _a === void 0 ? void 0 : _a.webgl.gl.drawingBufferWidth) || 0,
            height: ((_b = this.plugin.canvas3d) === null || _b === void 0 ? void 0 : _b.webgl.gl.drawingBufferHeight) || 0
        };
    };
    ViewportScreenshotHelper.prototype.getSize = function () {
        switch (this.currentResolution.name) {
            case 'viewport': return this.getCanvasSize();
            case 'hd': return { width: 1280, height: 720 };
            case 'full-hd': return { width: 1920, height: 1080 };
            case 'ultra-hd': return { width: 3840, height: 2160 };
            default: return { width: this.currentResolution.params.width, height: this.currentResolution.params.height };
        }
    };
    Object.defineProperty(ViewportScreenshotHelper.prototype, "imagePass", {
        get: function () {
            if (this._imagePass)
                return this._imagePass;
            this._imagePass = this.plugin.canvas3d.getImagePass({
                transparentBackground: this.transparent,
                drawPass: { cameraHelper: { axes: this.axes } },
                multiSample: { mode: 'on', sampleLevel: 2 },
                postprocessing: this.plugin.canvas3d.props.postprocessing
            });
            return this._imagePass;
        },
        enumerable: false,
        configurable: true
    });
    ViewportScreenshotHelper.prototype.getFilename = function () {
        var models = this.plugin.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Model)).map(function (s) { return s.obj.data; });
        var uniqueIds = new Set();
        models.forEach(function (m) { return uniqueIds.add(m.entryId.toUpperCase()); });
        var idString = set["a" /* SetUtils */].toArray(uniqueIds).join('-');
        return (idString || 'molstar-image') + ".png";
    };
    // private preview = () => {
    //     const { width, height } = this.getSize()
    //     if (width <= 0 || height <= 0) return
    //     let w: number, h: number
    //     const aH = maxHeightUi / height
    //     const aW = maxWidthUi / width
    //     if (aH < aW) {
    //         h = Math.round(Math.min(maxHeightUi, height))
    //         w = Math.round(width * (h / height))
    //     } else {
    //         w = Math.round(Math.min(maxWidthUi, width))
    //         h = Math.round(height * (w / width))
    //     }
    //     setCanvasSize(this.canvas, w, h)
    //     const pixelRatio = this.plugin.canvas3d?.webgl.pixelRatio || 1
    //     const pw = Math.round(w * pixelRatio)
    //     const ph = Math.round(h * pixelRatio)
    //     const imageData = this.imagePass.getImageData(pw, ph)
    //     this.canvasContext.putImageData(imageData, 0, 0)
    // }
    ViewportScreenshotHelper.prototype.draw = function (ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var _a, width, height, imageData, canvas, canvasCtx;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _a = this.getSize(), width = _a.width, height = _a.height;
                        if (width <= 0 || height <= 0)
                            return [2 /*return*/];
                        return [4 /*yield*/, ctx.update('Rendering image...')];
                    case 1:
                        _b.sent();
                        this.imagePass.setProps({
                            drawPass: { cameraHelper: { axes: this.axes } },
                            transparentBackground: this.transparent,
                            postprocessing: this.plugin.canvas3d.props.postprocessing // TODO this line should not be required, updating should work by listening to this.plugin.events.canvas3d.settingsUpdated
                        });
                        imageData = this.imagePass.getImageData(width, height);
                        return [4 /*yield*/, ctx.update('Encoding image...')];
                    case 2:
                        _b.sent();
                        canvas = this.canvas;
                        canvas.width = imageData.width;
                        canvas.height = imageData.height;
                        canvasCtx = canvas.getContext('2d');
                        if (!canvasCtx)
                            throw new Error('Could not create canvas 2d context');
                        canvasCtx.putImageData(imageData, 0, 0);
                        return [2 /*return*/];
                }
            });
        });
    };
    ViewportScreenshotHelper.prototype.downloadTask = function () {
        var _this = this;
        return mol_task["b" /* Task */].create('Download Image', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var blob;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.draw(ctx);
                        return [4 /*yield*/, ctx.update('Downloading image...')];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, Object(mol_canvas3d_util["a" /* canvasToBlob */])(this.canvas, 'png')];
                    case 2:
                        blob = _a.sent();
                        Object(download["a" /* download */])(blob, this.getFilename());
                        return [2 /*return*/];
                }
            });
        }); });
    };
    ViewportScreenshotHelper.prototype.downloadCurrent = function () {
        var _this = this;
        return this.plugin.runTask(mol_task["b" /* Task */].create('Download Image', function (ctx) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var blob;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, ctx.update('Downloading image...')];
                    case 1:
                        _a.sent();
                        return [4 /*yield*/, Object(mol_canvas3d_util["a" /* canvasToBlob */])(this.canvas, 'png')];
                    case 2:
                        blob = _a.sent();
                        Object(download["a" /* download */])(blob, this.getFilename());
                        return [2 /*return*/];
                }
            });
        }); }));
    };
    ViewportScreenshotHelper.prototype.imageData = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.draw(synchronous["a" /* SyncRuntimeContext */])];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, this.canvas.toDataURL()];
                }
            });
        });
    };
    ViewportScreenshotHelper.prototype.download = function () {
        this.plugin.runTask(this.downloadTask());
    };
    return ViewportScreenshotHelper;
}());
//# sourceMappingURL=viewport-screenshot.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/version.js
var version = __webpack_require__(314);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/assets.js
var assets = __webpack_require__(114);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/snapshots.js
var snapshots = __webpack_require__(364);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/animation.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */




// TODO: pause functionality (this needs to reset if the state tree changes)
// TODO: handle unregistered animations on state restore
// TODO: better API
var animation_PluginAnimationManager = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PluginAnimationManager, _super);
    function PluginAnimationManager(context) {
        var _this = _super.call(this, { params: { current: '' }, animationState: 'stopped' }) || this;
        _this.context = context;
        _this.map = new Map();
        _this.animations = [];
        _this._params = void 0;
        _this.events = {
            updated: _this.ev()
        };
        _this._frame = void 0;
        _this.animate = function (t) { return Object(tslib_es6["__awaiter"])(_this, void 0, void 0, function () {
            var newState;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._frame = void 0;
                        if (this._current.startedTime < 0)
                            this._current.startedTime = t;
                        return [4 /*yield*/, this._current.anim.apply(this._current.state, { lastApplied: this._current.lastTime, current: t - this._current.startedTime }, { params: this._current.paramValues, plugin: this.context })];
                    case 1:
                        newState = _a.sent();
                        if (newState.kind === 'finished') {
                            this.stop();
                        }
                        else if (newState.kind === 'next') {
                            this._current.state = newState.state;
                            this._current.lastTime = t - this._current.startedTime;
                            if (this.state.animationState === 'playing')
                                this._frame = requestAnimationFrame(this.animate);
                        }
                        else if (newState.kind === 'skip') {
                            if (this.state.animationState === 'playing')
                                this._frame = requestAnimationFrame(this.animate);
                        }
                        return [2 /*return*/];
                }
            });
        }); };
        return _this;
    }
    Object.defineProperty(PluginAnimationManager.prototype, "isEmpty", {
        get: function () { return this.animations.length === 0; },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PluginAnimationManager.prototype, "current", {
        get: function () { return this._current; },
        enumerable: false,
        configurable: true
    });
    PluginAnimationManager.prototype.triggerUpdate = function () {
        this.events.updated.next();
    };
    PluginAnimationManager.prototype.getParams = function () {
        if (!this._params) {
            this._params = {
                current: param_definition["ParamDefinition"].Select(this.animations[0] && this.animations[0].name, this.animations.map(function (a) { return [a.name, a.display.name]; }), { label: 'Animation' })
            };
        }
        return this._params;
    };
    PluginAnimationManager.prototype.updateParams = function (newParams) {
        if (this.isEmpty)
            return;
        this.updateState({ params: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, this.state.params), newParams) });
        var anim = this.map.get(this.state.params.current);
        var params = anim.params(this.context);
        this._current = {
            anim: anim,
            params: params,
            paramValues: param_definition["ParamDefinition"].getDefaultValues(params),
            state: {},
            startedTime: -1,
            lastTime: 0
        };
        this.triggerUpdate();
    };
    PluginAnimationManager.prototype.updateCurrentParams = function (values) {
        if (this.isEmpty)
            return;
        this._current.paramValues = Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, this._current.paramValues), values);
        this.triggerUpdate();
    };
    PluginAnimationManager.prototype.register = function (animation) {
        if (this.map.has(animation.name)) {
            this.context.log.error("Animation '" + animation.name + "' is already registered.");
            return;
        }
        this._params = void 0;
        this.map.set(animation.name, animation);
        this.animations.push(animation);
        if (this.animations.length === 1) {
            this.updateParams({ current: animation.name });
        }
        else {
            this.triggerUpdate();
        }
    };
    PluginAnimationManager.prototype.play = function (animation, params) {
        this.stop();
        if (!this.map.has(animation.name)) {
            this.register(animation);
        }
        this.updateParams({ current: animation.name });
        this.updateCurrentParams(params);
        this.start();
    };
    PluginAnimationManager.prototype.start = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var anim;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.updateState({ animationState: 'playing' });
                        if (!this.context.behaviors.state.isAnimating.value) {
                            this.context.behaviors.state.isAnimating.next(true);
                        }
                        this.triggerUpdate();
                        anim = this._current.anim;
                        if (!anim.setup) return [3 /*break*/, 2];
                        return [4 /*yield*/, anim.setup(this._current.paramValues, this.context)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this._current.lastTime = 0;
                        this._current.startedTime = -1;
                        this._current.state = this._current.anim.initialState(anim, this.context);
                        requestAnimationFrame(this.animate);
                        return [2 /*return*/];
                }
            });
        });
    };
    PluginAnimationManager.prototype.stop = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var anim;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (typeof this._frame !== 'undefined')
                            cancelAnimationFrame(this._frame);
                        if (!(this.state.animationState !== 'stopped')) return [3 /*break*/, 3];
                        anim = this._current.anim;
                        if (!anim.teardown) return [3 /*break*/, 2];
                        return [4 /*yield*/, anim.teardown(this._current.paramValues, this.context)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        this.updateState({ animationState: 'stopped' });
                        this.triggerUpdate();
                        _a.label = 3;
                    case 3:
                        if (this.context.behaviors.state.isAnimating.value) {
                            this.context.behaviors.state.isAnimating.next(false);
                        }
                        return [2 /*return*/];
                }
            });
        });
    };
    Object.defineProperty(PluginAnimationManager.prototype, "isAnimating", {
        get: function () {
            return this.state.animationState === 'playing';
        },
        enumerable: false,
        configurable: true
    });
    PluginAnimationManager.prototype.getSnapshot = function () {
        if (!this.current)
            return { state: this.state };
        return {
            state: this.state,
            current: {
                paramValues: this._current.paramValues,
                state: this._current.anim.stateSerialization ? this._current.anim.stateSerialization.toJSON(this._current.state) : this._current.state
            }
        };
    };
    PluginAnimationManager.prototype.setSnapshot = function (snapshot) {
        if (this.isEmpty)
            return;
        this.updateState({ animationState: snapshot.state.animationState });
        this.updateParams(snapshot.state.params);
        if (snapshot.current) {
            this.current.paramValues = snapshot.current.paramValues;
            this.current.state = this._current.anim.stateSerialization
                ? this._current.anim.stateSerialization.fromJSON(snapshot.current.state)
                : snapshot.current.state;
            this.triggerUpdate();
            if (this.state.animationState === 'playing')
                this.resume();
        }
    };
    PluginAnimationManager.prototype.resume = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var anim;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this._current.lastTime = 0;
                        this._current.startedTime = -1;
                        anim = this._current.anim;
                        if (!this.context.behaviors.state.isAnimating.value) {
                            this.context.behaviors.state.isAnimating.next(true);
                        }
                        if (!anim.setup) return [3 /*break*/, 2];
                        return [4 /*yield*/, anim.setup(this._current.paramValues, this.context)];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        requestAnimationFrame(this.animate);
                        return [2 /*return*/];
                }
            });
        });
    };
    return PluginAnimationManager;
}(mol_plugin_state_component["b" /* StatefulPluginComponent */]));
//# sourceMappingURL=animation.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/manager/volume/hierarchy.js + 1 modules
var volume_hierarchy = __webpack_require__(380);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/filter.js
var filter = __webpack_require__(169);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/take.js
var take = __webpack_require__(293);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin/context.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */
















































var context_PluginContext = /** @class */ (function () {
    function PluginContext(spec) {
        var _this = this;
        this.spec = spec;
        this.runTask = function (task) { return _this.tasks.run(task); };
        this.disposed = false;
        this.ev = rx_event_helper["RxEventHelper"].create();
        this.tasks = new task_manager_TaskManager();
        this.state = new mol_plugin_state["a" /* PluginState */](this);
        this.commands = new command["b" /* PluginCommandManager */]();
        this.events = {
            log: this.ev(),
            task: this.tasks.events,
            canvas3d: {
                settingsUpdated: this.ev(),
            }
        };
        this.config = new config["PluginConfigManager"](this.spec.config);
        this.canvas3dInit = this.ev.behavior(false);
        this.behaviors = {
            state: {
                isAnimating: this.ev.behavior(false),
                isUpdating: this.ev.behavior(false),
                // TODO: should there be separate "updated" event?
                //   Often, this is used to indicate that the state has updated
                //   and it might not be the best way to react to state updates.
                isBusy: this.ev.behavior(false)
            },
            interaction: {
                hover: this.ev.behavior({ current: mol_repr_representation["a" /* Representation */].Loci.Empty, modifiers: input_observer["b" /* ModifiersKeys */].None, buttons: 0, button: 0 }),
                click: this.ev.behavior({ current: mol_repr_representation["a" /* Representation */].Loci.Empty, modifiers: input_observer["b" /* ModifiersKeys */].None, buttons: 0, button: 0 }),
                selectionMode: this.ev.behavior(false)
            },
            labels: {
                highlight: this.ev.behavior({ labels: [] })
            },
            layout: {
                leftPanelTabName: this.ev.behavior('root')
            },
            canvas3d: {
                initialized: this.canvas3dInit.pipe(Object(filter["a" /* filter */])(function (v) { return !!v; }), Object(take["a" /* take */])(1))
            }
        };
        this.layout = new layout_PluginLayout(this);
        this.representation = {
            structure: {
                registry: new registry_StructureRepresentationRegistry(),
                themes: { colorThemeRegistry: color["a" /* ColorTheme */].createRegistry(), sizeThemeRegistry: mol_theme_size["a" /* SizeTheme */].createRegistry() },
            },
            volume: {
                registry: new registry["a" /* VolumeRepresentationRegistry */](),
                themes: { colorThemeRegistry: color["a" /* ColorTheme */].createRegistry(), sizeThemeRegistry: mol_theme_size["a" /* SizeTheme */].createRegistry() }
            }
        };
        this.query = {
            structure: {
                registry: new structure_selection_query["d" /* StructureSelectionQueryRegistry */]()
            }
        };
        this.dataFormats = new registry_DataFormatRegistry();
        this.builders = {
            data: new data_DataBuilder(this),
            structure: void 0
        };
        this.helpers = {
            substructureParent: new substructure_parent_helper_SubstructureParentHelper(this),
            viewportScreenshot: void 0
        };
        this.managers = {
            structure: {
                hierarchy: new hierarchy["StructureHierarchyManager"](this),
                component: new structure_component["StructureComponentManager"](this),
                measurement: new measurement["a" /* StructureMeasurementManager */](this),
                selection: new selection_StructureSelectionManager(this),
                focus: new focus_StructureFocusManager(this),
            },
            volume: {
                hierarchy: new volume_hierarchy["a" /* VolumeHierarchyManager */](this)
            },
            interactivity: void 0,
            camera: new camera_CameraManager(this),
            animation: new animation_PluginAnimationManager(this),
            snapshot: new snapshots["a" /* PluginStateSnapshotManager */](this),
            lociLabels: void 0,
            toast: new toast_PluginToastManager(this),
            asset: new assets["AssetManager"]()
        };
        this.customModelProperties = new custom_property_CustomProperty.Registry();
        this.customStructureProperties = new custom_property_CustomProperty.Registry();
        this.customParamEditors = new Map();
        this.customStructureControls = new Map();
        this.genericRepresentationControls = new Map();
        /**
         * Used to store application specific custom state which is then available
         * to State Actions and similar constructs via the PluginContext.
         */
        this.customState = Object.create(null);
        this.log = {
            entries: Object(immutable["List"])(),
            entry: function (e) { return _this.events.log.next(e); },
            error: function (msg) { return _this.events.log.next(log_entry["a" /* LogEntry */].error(msg)); },
            message: function (msg) { return _this.events.log.next(log_entry["a" /* LogEntry */].message(msg)); },
            info: function (msg) { return _this.events.log.next(log_entry["a" /* LogEntry */].info(msg)); },
            warn: function (msg) { return _this.events.log.next(log_entry["a" /* LogEntry */].warning(msg)); },
        };
        /**
         * This should be used in all transform related request so that it could be "spoofed" to allow
         * "static" access to resources.
         */
        this.fetch = data_source["a" /* ajaxGet */];
        // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
        // and freezing the params object causes "read-only exception"
        // TODO: is this the best place to do it?
        Object(immer_esm["c" /* setAutoFreeze */])(false);
        this.events.log.subscribe(function (e) { return _this.log.entries = _this.log.entries.push(e); });
        this.initBehaviorEvents();
        this.initBuiltInBehavior();
        this.initBehaviors();
        this.initDataActions();
        this.initAnimations();
        this.initCustomParamEditors();
        this.managers.interactivity = new interactivity["a" /* InteractivityManager */](this);
        this.managers.lociLabels = new loci_label_LociLabelManager(this);
        this.builders.structure = new structure_StructureBuilder(this);
        this.log.message("Mol* Plugin " + version["a" /* PLUGIN_VERSION */] + " [" + version["b" /* PLUGIN_VERSION_DATE */].toLocaleString() + "]");
        if (!debug["b" /* isProductionMode */])
            this.log.message("Development mode enabled");
        if (debug["a" /* isDebugMode */])
            this.log.message("Debug mode enabled");
    }
    PluginContext.prototype.build = function () {
        return this.state.data.build();
    };
    PluginContext.prototype.initViewer = function (canvas, container) {
        try {
            this.layout.setRoot(container);
            if (this.spec.layout && this.spec.layout.initial)
                this.layout.setProps(this.spec.layout.initial);
            this.canvas3d = canvas3d["Canvas3D"].fromCanvas(canvas);
            this.canvas3dInit.next(true);
            var renderer = this.canvas3d.props.renderer;
            commands["PluginCommands"].Canvas3D.SetSettings(this, { settings: { renderer: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, renderer), { backgroundColor: Object(mol_util_color["Color"])(0xFCFBF9) }) } });
            this.canvas3d.animate();
            this.helpers.viewportScreenshot = new viewport_screenshot_ViewportScreenshotHelper(this);
            return true;
        }
        catch (e) {
            this.log.error('' + e);
            console.error(e);
            return false;
        }
    };
    Object.defineProperty(PluginContext.prototype, "isBusy", {
        /** return true is animating or updating */
        get: function () {
            return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(PluginContext.prototype, "selectionMode", {
        get: function () {
            return this.behaviors.interaction.selectionMode.value;
        },
        set: function (mode) {
            this.behaviors.interaction.selectionMode.next(mode);
        },
        enumerable: false,
        configurable: true
    });
    PluginContext.prototype.dataTransaction = function (f, options) {
        return this.runTask(this.state.data.transaction(f, options));
    };
    PluginContext.prototype.requestTaskAbort = function (progress, reason) {
        this.tasks.requestAbort(progress, reason);
    };
    PluginContext.prototype.clear = function (resetViewportSettings) {
        var _a;
        if (resetViewportSettings === void 0) { resetViewportSettings = false; }
        if (resetViewportSettings)
            (_a = this.canvas3d) === null || _a === void 0 ? void 0 : _a.setProps(canvas3d["DefaultCanvas3DParams"]);
        return commands["PluginCommands"].State.RemoveObject(this, { state: this.state.data, ref: mol_state["StateTransform"].RootRef });
    };
    PluginContext.prototype.dispose = function () {
        var _a;
        if (this.disposed)
            return;
        this.commands.dispose();
        (_a = this.canvas3d) === null || _a === void 0 ? void 0 : _a.dispose();
        this.ev.dispose();
        this.state.dispose();
        this.tasks.dispose();
        this.layout.dispose();
        this.helpers.substructureParent.dispose();
        Object(object["c" /* objectForEach */])(this.managers, function (m) { var _a, _b; return (_b = (_a = m) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a); });
        Object(object["c" /* objectForEach */])(this.managers.structure, function (m) { var _a, _b; return (_b = (_a = m) === null || _a === void 0 ? void 0 : _a.dispose) === null || _b === void 0 ? void 0 : _b.call(_a); });
        this.disposed = true;
    };
    PluginContext.prototype.initBehaviorEvents = function () {
        var _this = this;
        Object(merge["a" /* merge */])(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(function (u) {
            if (_this.behaviors.state.isUpdating.value !== u)
                _this.behaviors.state.isUpdating.next(u);
        });
        var timeoutMs = this.config.get(config["PluginConfig"].General.IsBusyTimeoutMs) || 750;
        var isBusy = this.behaviors.state.isBusy;
        var timeout = void 0;
        var setBusy = function () {
            if (!isBusy.value)
                isBusy.next(true);
        };
        var reset = function () {
            if (timeout !== void 0)
                clearTimeout(timeout);
            timeout = void 0;
        };
        Object(merge["a" /* merge */])(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(function (v) {
            var isUpdating = _this.behaviors.state.isUpdating.value;
            var isAnimating = _this.behaviors.state.isAnimating.value;
            if (isUpdating || isAnimating) {
                if (!isBusy.value) {
                    reset();
                    timeout = setTimeout(setBusy, timeoutMs);
                }
            }
            else {
                reset();
                isBusy.next(false);
            }
        });
        this.behaviors.interaction.selectionMode.subscribe(function (v) {
            var _a;
            if (!v) {
                (_a = _this.managers.interactivity) === null || _a === void 0 ? void 0 : _a.lociSelects.deselectAll();
            }
        });
    };
    PluginContext.prototype.initBuiltInBehavior = function () {
        var _this = this;
        behavior["BuiltInPluginBehaviors"].State.registerDefault(this);
        behavior["BuiltInPluginBehaviors"].Representation.registerDefault(this);
        behavior["BuiltInPluginBehaviors"].Camera.registerDefault(this);
        behavior["BuiltInPluginBehaviors"].Misc.registerDefault(this);
        Object(merge["a" /* merge */])(this.state.data.events.log, this.state.behaviors.events.log).subscribe(function (e) { return _this.events.log.next(e); });
    };
    PluginContext.prototype.initBehaviors = function () {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var tree, _i, _a, cat, _b, _c, b, cat, _d, _e, b, cat;
            return Object(tslib_es6["__generator"])(this, function (_f) {
                switch (_f.label) {
                    case 0:
                        tree = this.state.behaviors.build();
                        for (_i = 0, _a = Object.keys(behavior_behavior["PluginBehavior"].Categories); _i < _a.length; _i++) {
                            cat = _a[_i];
                            tree.toRoot().apply(behavior_behavior["PluginBehavior"].CreateCategory, { label: behavior_behavior["PluginBehavior"].Categories[cat] }, { ref: cat, state: { isLocked: true } });
                        }
                        // Init custom properties 1st
                        for (_b = 0, _c = this.spec.behaviors; _b < _c.length; _b++) {
                            b = _c[_b];
                            cat = behavior_behavior["PluginBehavior"].getCategoryId(b.transformer);
                            if (cat !== 'custom-props')
                                continue;
                            tree.to(behavior_behavior["PluginBehavior"].getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
                        }
                        return [4 /*yield*/, this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }))];
                    case 1:
                        _f.sent();
                        tree = this.state.behaviors.build();
                        for (_d = 0, _e = this.spec.behaviors; _d < _e.length; _d++) {
                            b = _e[_d];
                            cat = behavior_behavior["PluginBehavior"].getCategoryId(b.transformer);
                            if (cat === 'custom-props')
                                continue;
                            tree.to(behavior_behavior["PluginBehavior"].getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
                        }
                        return [4 /*yield*/, this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }))];
                    case 2:
                        _f.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    PluginContext.prototype.initDataActions = function () {
        for (var _i = 0, _a = this.spec.actions; _i < _a.length; _i++) {
            var a = _a[_i];
            this.state.data.actions.add(a.action);
        }
    };
    PluginContext.prototype.initAnimations = function () {
        if (!this.spec.animations)
            return;
        for (var _i = 0, _a = this.spec.animations; _i < _a.length; _i++) {
            var anim = _a[_i];
            this.managers.animation.register(anim);
        }
    };
    PluginContext.prototype.initCustomParamEditors = function () {
        if (!this.spec.customParamEditors)
            return;
        for (var _i = 0, _a = this.spec.customParamEditors; _i < _a.length; _i++) {
            var _b = _a[_i], t = _b[0], e = _b[1];
            this.customParamEditors.set(t.id, e);
        }
    };
    return PluginContext;
}());

//# sourceMappingURL=context.js.map

/***/ }),
/* 448 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "Plugin", function() { return /* binding */ plugin_Plugin; });
__webpack_require__.d(__webpack_exports__, "PluginContextContainer", function() { return /* binding */ plugin_PluginContextContainer; });
__webpack_require__.d(__webpack_exports__, "ControlsWrapper", function() { return /* binding */ plugin_ControlsWrapper; });
__webpack_require__.d(__webpack_exports__, "DefaultViewport", function() { return /* binding */ plugin_DefaultViewport; });
__webpack_require__.d(__webpack_exports__, "Log", function() { return /* binding */ plugin_Log; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/react/index.js
var react = __webpack_require__(3);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/index.js + 1 modules
var mol_util = __webpack_require__(5);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/base.js
var base = __webpack_require__(32);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls.js + 9 modules
var mol_plugin_ui_controls = __webpack_require__(271);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-canvas3d/canvas3d.js
var canvas3d = __webpack_require__(158);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/common.js
var common = __webpack_require__(19);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/parameters.js + 5 modules
var parameters = __webpack_require__(66);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/actions.js
var actions = __webpack_require__(387);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/snapshots.js
var snapshots = __webpack_require__(285);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/state/tree.js
var tree = __webpack_require__(376);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport/help.js
var help = __webpack_require__(189);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/controls/icons.js
var icons = __webpack_require__(14);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/left-panel.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */













var left_panel_LeftPanelControls = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(LeftPanelControls, _super);
    function LeftPanelControls() {
        var _a;
        var _this = _super.apply(this, arguments) || this;
        _this.state = { tab: _this.plugin.behaviors.layout.leftPanelTabName.value };
        _this.set = function (tab) {
            if (_this.state.tab === tab) {
                _this.setState({ tab: 'none' }, function () { return _this.plugin.behaviors.layout.leftPanelTabName.next('none'); });
                commands["PluginCommands"].Layout.Update(_this.plugin, { state: { regionState: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.plugin.layout.state.regionState), { left: 'collapsed' }) } });
                return;
            }
            _this.setState({ tab: tab }, function () { return _this.plugin.behaviors.layout.leftPanelTabName.next(tab); });
            if (_this.plugin.layout.state.regionState.left !== 'full') {
                commands["PluginCommands"].Layout.Update(_this.plugin, { state: { regionState: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.plugin.layout.state.regionState), { left: 'full' }) } });
            }
        };
        _this.tabs = {
            'none': react["createElement"](react["Fragment"], null),
            'root': react["createElement"](react["Fragment"], null,
                react["createElement"](common["SectionHeader"], { icon: icons["HomeOutlinedSvg"], title: 'Home' }),
                react["createElement"](actions["StateObjectActions"], { state: _this.plugin.state.data, nodeRef: mol_state["StateTransform"].RootRef, hideHeader: true, initiallyCollapsed: true, alwaysExpandFirst: true }),
                ((_a = _this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.remoteState) !== 'none' && react["createElement"](snapshots["RemoteStateSnapshots"], { listOnly: true })),
            'data': react["createElement"](react["Fragment"], null,
                react["createElement"](common["SectionHeader"], { icon: icons["AccountTreeOutlinedSvg"], title: react["createElement"](react["Fragment"], null,
                        react["createElement"](left_panel_RemoveAllButton, null),
                        " State Tree") }),
                react["createElement"](tree["StateTree"], { state: _this.plugin.state.data })),
            'states': react["createElement"](snapshots["StateSnapshots"], null),
            'settings': react["createElement"](react["Fragment"], null,
                react["createElement"](common["SectionHeader"], { icon: icons["TuneSvg"], title: 'Plugin Settings' }),
                react["createElement"](left_panel_FullSettings, null)),
            'help': react["createElement"](react["Fragment"], null,
                react["createElement"](common["SectionHeader"], { icon: icons["HelpOutlineSvg"], title: 'Help' }),
                react["createElement"](help["HelpContent"], null))
        };
        return _this;
    }
    LeftPanelControls.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.layout.leftPanelTabName, function (tab) {
            if (_this.state.tab !== tab)
                _this.setState({ tab: tab });
            if (tab === 'none' && _this.plugin.layout.state.regionState.left !== 'collapsed') {
                commands["PluginCommands"].Layout.Update(_this.plugin, { state: { regionState: Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, _this.plugin.layout.state.regionState), { left: 'collapsed' }) } });
            }
        });
        this.subscribe(this.plugin.state.data.events.changed, function (_a) {
            var state = _a.state;
            if (_this.state.tab !== 'data')
                return;
            if (state.cells.size === 1)
                _this.set('root');
        });
    };
    LeftPanelControls.prototype.render = function () {
        var _this = this;
        var tab = this.state.tab;
        return react["createElement"]("div", { className: 'msp-left-panel-controls' },
            react["createElement"]("div", { className: 'msp-left-panel-controls-buttons' },
                react["createElement"](common["IconButton"], { svg: icons["HomeOutlinedSvg"], toggleState: tab === 'root', transparent: true, onClick: function () { return _this.set('root'); }, title: 'Home' }),
                react["createElement"](left_panel_DataIcon, { set: this.set }),
                react["createElement"](common["IconButton"], { svg: icons["SaveOutlinedSvg"], toggleState: tab === 'states', transparent: true, onClick: function () { return _this.set('states'); }, title: 'Plugin State' }),
                react["createElement"](common["IconButton"], { svg: icons["HelpOutlineSvg"], toggleState: tab === 'help', transparent: true, onClick: function () { return _this.set('help'); }, title: 'Help' }),
                react["createElement"]("div", { className: 'msp-left-panel-controls-buttons-bottom' },
                    react["createElement"](common["IconButton"], { svg: icons["TuneSvg"], toggleState: tab === 'settings', transparent: true, onClick: function () { return _this.set('settings'); }, title: 'Settings' }))),
            react["createElement"]("div", { className: 'msp-scrollable-container' }, this.tabs[tab]));
    };
    return LeftPanelControls;
}(base["PluginUIComponent"]));

var left_panel_DataIcon = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(DataIcon, _super);
    function DataIcon() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { changed: false };
        return _this;
    }
    Object.defineProperty(DataIcon.prototype, "tab", {
        get: function () {
            return this.plugin.behaviors.layout.leftPanelTabName.value;
        },
        enumerable: false,
        configurable: true
    });
    DataIcon.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.behaviors.layout.leftPanelTabName, function (tab) {
            if (_this.tab === 'data')
                _this.setState({ changed: false });
            else
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.data.events.changed, function (state) {
            if (_this.tab !== 'data')
                _this.setState({ changed: true });
        });
    };
    DataIcon.prototype.render = function () {
        var _this = this;
        return react["createElement"](common["IconButton"], { svg: icons["AccountTreeOutlinedSvg"], toggleState: this.tab === 'data', transparent: true, onClick: function () { return _this.props.set('data'); }, title: 'State Tree', style: { position: 'relative' }, extraContent: this.state.changed ? react["createElement"]("div", { className: 'msp-left-panel-controls-button-data-dirty' }) : void 0 });
    };
    return DataIcon;
}(base["PluginUIComponent"]));
var left_panel_FullSettings = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(FullSettings, _super);
    function FullSettings() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.setSettings = function (p) {
            var _a;
            commands["PluginCommands"].Canvas3D.SetSettings(_this.plugin, { settings: (_a = {}, _a[p.name] = p.value, _a) });
        };
        return _this;
    }
    FullSettings.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.canvas3d.settingsUpdated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.layout.events.updated, function () { return _this.forceUpdate(); });
        this.subscribe(this.plugin.canvas3d.camera.stateChanged, function (state) {
            if (state.radiusMax !== undefined || state.radius !== undefined) {
                _this.forceUpdate();
            }
        });
    };
    FullSettings.prototype.render = function () {
        return react["createElement"](react["Fragment"], null,
            this.plugin.canvas3d && react["createElement"](react["Fragment"], null,
                react["createElement"](common["SectionHeader"], { title: 'Viewport' }),
                react["createElement"](parameters["ParameterControls"], { params: canvas3d["Canvas3DParams"], values: this.plugin.canvas3d.props, onChange: this.setSettings })),
            react["createElement"](common["SectionHeader"], { title: 'Behavior' }),
            react["createElement"](tree["StateTree"], { state: this.plugin.state.behaviors }));
    };
    return FullSettings;
}(base["PluginUIComponent"]));
var left_panel_RemoveAllButton = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(RemoveAllButton, _super);
    function RemoveAllButton() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.remove = function (e) {
            e.preventDefault();
            commands["PluginCommands"].State.RemoveObject(_this.plugin, { state: _this.plugin.state.data, ref: mol_state["StateTransform"].RootRef });
        };
        return _this;
    }
    RemoveAllButton.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.state.events.cell.created, function (e) {
            if (e.cell.transform.parent === mol_state["StateTransform"].RootRef)
                _this.forceUpdate();
        });
        this.subscribe(this.plugin.state.events.cell.removed, function (e) {
            if (e.parent === mol_state["StateTransform"].RootRef)
                _this.forceUpdate();
        });
    };
    RemoveAllButton.prototype.render = function () {
        var count = this.plugin.state.data.tree.children.get(mol_state["StateTransform"].RootRef).size;
        if (count === 0)
            return null;
        return react["createElement"](common["IconButton"], { svg: icons["DeleteOutlinedSvg"], onClick: this.remove, title: 'Remove All', style: { display: 'inline-block' }, small: true, className: 'msp-no-hover-outline', transparent: true });
    };
    return RemoveAllButton;
}(base["PluginUIComponent"]));
//# sourceMappingURL=left-panel.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/input/input-observer.js
var input_observer = __webpack_require__(84);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/structure.js
var mol_model_structure = __webpack_require__(4);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/Subject.js
var Subject = __webpack_require__(60);

// EXTERNAL MODULE: ./node_modules/rxjs/_esm5/internal/operators/debounceTime.js
var debounceTime = __webpack_require__(388);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/int.js + 11 modules
var mol_data_int = __webpack_require__(6);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-repr/representation.js
var representation = __webpack_require__(40);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/sequence.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */









/** Note, if this is changed, the CSS for `msp-sequence-number` needs adjustment too */
var MaxSequenceNumberSize = 5;
// TODO: this is somewhat inefficient and should be done using a canvas.
var sequence_Sequence = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Sequence, _super);
    function Sequence() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.parentDiv = react["createRef"]();
        _this.lastMouseOverSeqIdx = -1;
        _this.highlightQueue = new Subject["a" /* Subject */]();
        _this.lociHighlightProvider = function (loci, action) {
            var changed = _this.props.sequenceWrapper.markResidue(loci.loci, action);
            if (changed)
                _this.updateMarker();
        };
        _this.lociSelectionProvider = function (loci, action) {
            var changed = _this.props.sequenceWrapper.markResidue(loci.loci, action);
            if (changed)
                _this.updateMarker();
        };
        _this.contextMenu = function (e) {
            e.preventDefault();
        };
        _this.mouseDownLoci = undefined;
        _this.mouseDown = function (e) {
            e.stopPropagation();
            var seqIdx = _this.getSeqIdx(e);
            var loci = _this.getLoci(seqIdx);
            var buttons = Object(input_observer["e" /* getButtons */])(e.nativeEvent);
            var button = Object(input_observer["d" /* getButton */])(e.nativeEvent);
            var modifiers = Object(input_observer["f" /* getModifiers */])(e.nativeEvent);
            _this.click(loci, buttons, button, modifiers);
            _this.mouseDownLoci = loci;
        };
        _this.mouseUp = function (e) {
            e.stopPropagation();
            // ignore mouse-up events without a bound loci
            if (_this.mouseDownLoci === undefined)
                return;
            var seqIdx = _this.getSeqIdx(e);
            var loci = _this.getLoci(seqIdx);
            if (loci && !mol_model_structure["StructureElement"].Loci.areEqual(_this.mouseDownLoci, loci)) {
                var buttons = Object(input_observer["e" /* getButtons */])(e.nativeEvent);
                var button = Object(input_observer["d" /* getButton */])(e.nativeEvent);
                var modifiers = Object(input_observer["f" /* getModifiers */])(e.nativeEvent);
                var ref = _this.mouseDownLoci.elements[0];
                var ext = loci.elements[0];
                var min = Math.min(mol_data_int["OrderedSet"].min(ref.indices), mol_data_int["OrderedSet"].min(ext.indices));
                var max = Math.max(mol_data_int["OrderedSet"].max(ref.indices), mol_data_int["OrderedSet"].max(ext.indices));
                var range = mol_model_structure["StructureElement"].Loci(loci.structure, [{
                        unit: ref.unit,
                        indices: mol_data_int["OrderedSet"].ofRange(min, max)
                    }]);
                _this.click(mol_model_structure["StructureElement"].Loci.subtract(range, _this.mouseDownLoci), buttons, button, modifiers);
            }
            _this.mouseDownLoci = undefined;
        };
        _this.location = mol_model_structure["StructureElement"].Location.create(void 0);
        _this.mouseMove = function (e) {
            e.stopPropagation();
            var buttons = Object(input_observer["e" /* getButtons */])(e.nativeEvent);
            var button = Object(input_observer["d" /* getButton */])(e.nativeEvent);
            var modifiers = Object(input_observer["f" /* getModifiers */])(e.nativeEvent);
            var el = e.target;
            if (!el || !el.getAttribute) {
                if (_this.lastMouseOverSeqIdx === -1)
                    return;
                _this.lastMouseOverSeqIdx = -1;
                _this.highlightQueue.next({ seqIdx: -1, buttons: buttons, button: button, modifiers: modifiers });
                return;
            }
            var seqIdx = el.hasAttribute('data-seqid') ? +el.getAttribute('data-seqid') : -1;
            if (_this.lastMouseOverSeqIdx === seqIdx) {
                return;
            }
            else {
                _this.lastMouseOverSeqIdx = seqIdx;
                if (_this.mouseDownLoci !== undefined) {
                    var loci = _this.getLoci(seqIdx);
                    _this.hover(loci, 0 /* None */, 0 /* None */, Object(tslib_es6["__assign"])(Object(tslib_es6["__assign"])({}, modifiers), { shift: true }));
                }
                else {
                    _this.highlightQueue.next({ seqIdx: seqIdx, buttons: buttons, button: button, modifiers: modifiers });
                }
            }
        };
        _this.mouseLeave = function (e) {
            e.stopPropagation();
            _this.mouseDownLoci = undefined;
            if (_this.lastMouseOverSeqIdx === -1)
                return;
            _this.lastMouseOverSeqIdx = -1;
            var buttons = Object(input_observer["e" /* getButtons */])(e.nativeEvent);
            var button = Object(input_observer["d" /* getButton */])(e.nativeEvent);
            var modifiers = Object(input_observer["f" /* getModifiers */])(e.nativeEvent);
            _this.highlightQueue.next({ seqIdx: -1, buttons: buttons, button: button, modifiers: modifiers });
        };
        return _this;
    }
    Object.defineProperty(Sequence.prototype, "sequenceNumberPeriod", {
        get: function () {
            if (this.props.sequenceNumberPeriod !== undefined) {
                return this.props.sequenceNumberPeriod;
            }
            if (this.props.sequenceWrapper.length > 10)
                return 10;
            var lastSeqNum = this.getSequenceNumber(this.props.sequenceWrapper.length - 1);
            if (lastSeqNum.length > 1)
                return 5;
            return 1;
        },
        enumerable: false,
        configurable: true
    });
    Sequence.prototype.componentDidMount = function () {
        var _this = this;
        this.plugin.managers.interactivity.lociHighlights.addProvider(this.lociHighlightProvider);
        this.plugin.managers.interactivity.lociSelects.addProvider(this.lociSelectionProvider);
        this.subscribe(Object(debounceTime["a" /* debounceTime */])(15)(this.highlightQueue), function (e) {
            var loci = _this.getLoci(e.seqIdx < 0 ? void 0 : e.seqIdx);
            _this.hover(loci, e.buttons, e.button, e.modifiers);
        });
        // this.updateMarker()
    };
    Sequence.prototype.componentWillUnmount = function () {
        _super.prototype.componentWillUnmount.call(this);
        this.plugin.managers.interactivity.lociHighlights.removeProvider(this.lociHighlightProvider);
        this.plugin.managers.interactivity.lociSelects.removeProvider(this.lociSelectionProvider);
    };
    Sequence.prototype.getLoci = function (seqIdx) {
        if (seqIdx !== undefined) {
            var loci = this.props.sequenceWrapper.getLoci(seqIdx);
            if (!mol_model_structure["StructureElement"].Loci.isEmpty(loci))
                return loci;
        }
    };
    Sequence.prototype.getSeqIdx = function (e) {
        var seqIdx = undefined;
        var el = e.target;
        if (el && el.getAttribute) {
            seqIdx = el.hasAttribute('data-seqid') ? +el.getAttribute('data-seqid') : undefined;
        }
        return seqIdx;
    };
    Sequence.prototype.hover = function (loci, buttons, button, modifiers) {
        var ev = { current: representation["a" /* Representation */].Loci.Empty, buttons: buttons, button: button, modifiers: modifiers };
        if (loci !== undefined && !mol_model_structure["StructureElement"].Loci.isEmpty(loci)) {
            ev.current = { loci: loci };
        }
        this.plugin.behaviors.interaction.hover.next(ev);
    };
    Sequence.prototype.click = function (loci, buttons, button, modifiers) {
        var ev = { current: representation["a" /* Representation */].Loci.Empty, buttons: buttons, button: button, modifiers: modifiers };
        if (loci !== undefined && !mol_model_structure["StructureElement"].Loci.isEmpty(loci)) {
            ev.current = { loci: loci };
        }
        this.plugin.behaviors.interaction.click.next(ev);
    };
    Sequence.prototype.getBackgroundColor = function (marker) {
        // TODO: make marker color configurable
        if (typeof marker === 'undefined')
            console.error('unexpected marker value');
        return marker === 0 ? '' : marker % 2 === 0 ? 'rgb(51, 255, 25)' /* selected */ : 'rgb(255, 102, 153)' /* highlighted */;
    };
    Sequence.prototype.getResidueClass = function (seqIdx, label) {
        return label.length > 1
            ? this.props.sequenceWrapper.residueClass(seqIdx) + (seqIdx === 0 ? ' msp-sequence-residue-long-begin' : ' msp-sequence-residue-long')
            : this.props.sequenceWrapper.residueClass(seqIdx);
    };
    Sequence.prototype.residue = function (seqIdx, label, marker) {
        return react["createElement"]("span", { key: seqIdx, "data-seqid": seqIdx, style: { backgroundColor: this.getBackgroundColor(marker) }, className: this.getResidueClass(seqIdx, label) }, "\u200B" + label + "\u200B");
    };
    Sequence.prototype.getSequenceNumberClass = function (seqIdx, seqNum, label) {
        var classList = ['msp-sequence-number'];
        if (seqNum.startsWith('-')) {
            if (label.length > 1 && seqIdx > 0)
                classList.push('msp-sequence-number-long-negative');
            else
                classList.push('msp-sequence-number-negative');
        }
        else {
            if (label.length > 1 && seqIdx > 0)
                classList.push('msp-sequence-number-long');
        }
        return classList.join(' ');
    };
    Sequence.prototype.getSequenceNumber = function (seqIdx) {
        var seqNum = '';
        var loci = this.props.sequenceWrapper.getLoci(seqIdx);
        var l = mol_model_structure["StructureElement"].Loci.getFirstLocation(loci, this.location);
        if (l) {
            if (mol_model_structure["Unit"].isAtomic(l.unit)) {
                var seqId = mol_model_structure["StructureProperties"].residue.auth_seq_id(l);
                var insCode = mol_model_structure["StructureProperties"].residue.pdbx_PDB_ins_code(l);
                seqNum = "" + seqId + (insCode ? insCode : '');
            }
            else if (mol_model_structure["Unit"].isCoarse(l.unit)) {
                seqNum = "" + (seqIdx + 1);
            }
        }
        return seqNum;
    };
    Sequence.prototype.padSeqNum = function (n) {
        if (n.length < MaxSequenceNumberSize)
            return n + new Array(MaxSequenceNumberSize - n.length + 1).join('\u00A0');
        return n;
    };
    Sequence.prototype.getSequenceNumberSpan = function (seqIdx, label) {
        var seqNum = this.getSequenceNumber(seqIdx);
        return react["createElement"]("span", { key: "marker-" + seqIdx, className: this.getSequenceNumberClass(seqIdx, seqNum, label) }, this.padSeqNum(seqNum));
    };
    Sequence.prototype.updateMarker = function () {
        if (!this.parentDiv.current)
            return;
        var xs = this.parentDiv.current.children;
        var markerArray = this.props.sequenceWrapper.markerArray;
        var hasNumbers = !this.props.hideSequenceNumbers, period = this.sequenceNumberPeriod;
        // let first: HTMLSpanElement | undefined;
        var o = 0;
        for (var i = 0, il = markerArray.length; i < il; i++) {
            if (hasNumbers && i % period === 0 && i < il)
                o++;
            // o + 1 to account for help icon
            var span = xs[o];
            if (!span)
                return;
            o++;
            // if (!first && markerArray[i] > 0) {
            //     first = span;
            // }
            var backgroundColor = this.getBackgroundColor(markerArray[i]);
            if (span.style.backgroundColor !== backgroundColor)
                span.style.backgroundColor = backgroundColor;
        }
        // if (first) {
        //     first.scrollIntoView({ block: 'nearest' });
        // }
    };
    Sequence.prototype.render = function () {
        var sw = this.props.sequenceWrapper;
        var elems = [];
        var hasNumbers = !this.props.hideSequenceNumbers, period = this.sequenceNumberPeriod;
        for (var i = 0, il = sw.length; i < il; ++i) {
            var label = sw.residueLabel(i);
            // add sequence number before name so the html element do not get separated by a line-break
            if (hasNumbers && i % period === 0 && i < il) {
                elems[elems.length] = this.getSequenceNumberSpan(i, label);
            }
            elems[elems.length] = this.residue(i, label, sw.markerArray[i]);
        }
        // calling .updateMarker here is neccesary to ensure existing
        // residue spans are updated as react won't update them
        this.updateMarker();
        return react["createElement"]("div", { className: 'msp-sequence-wrapper msp-sequence-wrapper-non-empty', onContextMenu: this.contextMenu, onMouseDown: this.mouseDown, onMouseUp: this.mouseUp, onMouseMove: this.mouseMove, onMouseLeave: this.mouseLeave, ref: this.parentDiv }, elems);
    };
    return Sequence;
}(base["PluginUIComponent"]));

//# sourceMappingURL=sequence.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/loci.js
var mol_model_loci = __webpack_require__(23);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/marker-action.js
var marker_action = __webpack_require__(45);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/wrapper.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */




var wrapper_SequenceWrapper = /** @class */ (function () {
    function SequenceWrapper(data, markerArray, length) {
        this.data = data;
        this.markerArray = markerArray;
        this.length = length;
    }
    SequenceWrapper.prototype.markResidue = function (loci, action) {
        if (Object(mol_model_loci["isEveryLoci"])(loci)) {
            return Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, mol_data_int["Interval"].ofLength(this.length), action);
        }
        else {
            return this.mark(loci, action);
        }
    };
    return SequenceWrapper;
}());
//# sourceMappingURL=wrapper.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/color/names.js
var names = __webpack_require__(47);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/polymer.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var polymer_PolymerSequenceWrapper = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PolymerSequenceWrapper, _super);
    function PolymerSequenceWrapper(data) {
        var _this = this;
        var l = mol_model_structure["StructureElement"].Location.create(data.structure, data.units[0], data.units[0].elements[0]);
        var entitySeq = data.units[0].model.sequence.byEntityKey[mol_model_structure["StructureProperties"].entity.key(l)];
        var length = entitySeq.sequence.length;
        var markerArray = new Uint8Array(length);
        _this = _super.call(this, data, markerArray, length) || this;
        _this.unitMap = new Map();
        for (var _i = 0, _a = data.units; _i < _a.length; _i++) {
            var unit = _a[_i];
            _this.unitMap.set(unit.id, unit);
        }
        _this.sequence = entitySeq.sequence;
        _this.missing = data.units[0].model.properties.missingResidues;
        _this.modelNum = data.units[0].model.modelNum;
        _this.asymId = mol_model_structure["Unit"].isAtomic(data.units[0]) ? mol_model_structure["StructureProperties"].chain.label_asym_id(l) : mol_model_structure["StructureProperties"].coarse.asym_id(l);
        var missing = [];
        for (var i = 0; i < length; ++i) {
            if (_this.missing.has(_this.modelNum, _this.asymId, _this.seqId(i)))
                missing.push(i);
        }
        _this.observed = mol_data_int["OrderedSet"].subtract(mol_data_int["Interval"].ofBounds(0, length), mol_data_int["SortedArray"].ofSortedArray(missing));
        return _this;
    }
    PolymerSequenceWrapper.prototype.seqId = function (seqIdx) {
        return this.sequence.seqId.value(seqIdx);
    };
    PolymerSequenceWrapper.prototype.residueLabel = function (seqIdx) {
        return this.sequence.label.value(seqIdx);
    };
    PolymerSequenceWrapper.prototype.residueColor = function (seqIdx) {
        return this.missing.has(this.modelNum, this.asymId, this.seqId(seqIdx))
            ? names["a" /* ColorNames */].grey
            : names["a" /* ColorNames */].black;
    };
    PolymerSequenceWrapper.prototype.residueClass = function (seqIdx) {
        return this.missing.has(this.modelNum, this.asymId, this.seqId(seqIdx))
            ? 'msp-sequence-missing'
            : 'msp-sequence-present';
    };
    PolymerSequenceWrapper.prototype.mark = function (loci, action) {
        var _this = this;
        var changed = false;
        var structure = this.data.structure;
        var index = function (seqId) { return _this.sequence.index(seqId); };
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            loci = mol_model_structure["StructureElement"].Loci.remap(loci, structure);
            for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
                var e = _a[_i];
                if (!this.unitMap.has(e.unit.id))
                    continue;
                if (mol_model_structure["Unit"].isAtomic(e.unit)) {
                    changed = applyMarkerAtomic(e, action, this.markerArray, index) || changed;
                }
                else {
                    changed = applyMarkerCoarse(e, action, this.markerArray, index) || changed;
                }
            }
        }
        else if (mol_model_structure["Structure"].isLoci(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, this.observed, action))
                changed = true;
        }
        return changed;
    };
    PolymerSequenceWrapper.prototype.getLoci = function (seqIdx) {
        var query = createResidueQuery(this.data.units[0].chainGroupId, this.data.units[0].conformation.operator.name, this.seqId(seqIdx));
        return mol_model_structure["StructureSelection"].toLociWithSourceUnits(mol_model_structure["StructureQuery"].run(query, this.data.structure));
    };
    return PolymerSequenceWrapper;
}(wrapper_SequenceWrapper));

function createResidueQuery(chainGroupId, operatorName, label_seq_id) {
    return mol_model_structure["Queries"].generators.atoms({
        unitTest: function (ctx) {
            return (mol_model_structure["StructureProperties"].unit.chainGroupId(ctx.element) === chainGroupId &&
                mol_model_structure["StructureProperties"].unit.operator_name(ctx.element) === operatorName);
        },
        residueTest: function (ctx) {
            if (ctx.element.unit.kind === 0 /* Atomic */) {
                return mol_model_structure["StructureProperties"].residue.label_seq_id(ctx.element) === label_seq_id;
            }
            else {
                return (mol_model_structure["StructureProperties"].coarse.seq_id_begin(ctx.element) <= label_seq_id &&
                    mol_model_structure["StructureProperties"].coarse.seq_id_end(ctx.element) >= label_seq_id);
            }
        }
    });
}
function applyMarkerAtomic(e, action, markerArray, index) {
    var _a = e.unit, model = _a.model, elements = _a.elements;
    var residueIndex = model.atomicHierarchy.residueAtomSegments.index;
    var label_seq_id = model.atomicHierarchy.residues.label_seq_id;
    var changed = false;
    mol_data_int["OrderedSet"].forEachSegment(e.indices, function (i) { return residueIndex[elements[i]]; }, function (rI) {
        var seqId = label_seq_id.value(rI);
        changed = Object(marker_action["d" /* applyMarkerActionAtPosition */])(markerArray, index(seqId), action) || changed;
    });
    return changed;
}
function applyMarkerCoarse(e, action, markerArray, index) {
    var _a = e.unit, model = _a.model, elements = _a.elements;
    var begin = mol_model_structure["Unit"].isSpheres(e.unit) ? model.coarseHierarchy.spheres.seq_id_begin : model.coarseHierarchy.gaussians.seq_id_begin;
    var end = mol_model_structure["Unit"].isSpheres(e.unit) ? model.coarseHierarchy.spheres.seq_id_end : model.coarseHierarchy.gaussians.seq_id_end;
    var changed = false;
    mol_data_int["OrderedSet"].forEach(e.indices, function (i) {
        var eI = elements[i];
        for (var s = index(begin.value(eI)), e_1 = index(end.value(eI)); s <= e_1; s++) {
            changed = Object(marker_action["d" /* applyMarkerActionAtPosition */])(markerArray, s, action) || changed;
        }
    });
    return changed;
}
//# sourceMappingURL=polymer.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/hetero.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var hetero_HeteroSequenceWrapper = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(HeteroSequenceWrapper, _super);
    function HeteroSequenceWrapper(data) {
        var _this = this;
        var sequence = [];
        var sequenceIndices = new Map();
        var residueIndices = new Map();
        var seqToUnit = new Map();
        for (var i = 0, il = data.units.length; i < il; ++i) {
            var unit = data.units[i];
            var _a = unit.model.atomicHierarchy, residueAtomSegments = _a.residueAtomSegments, atoms = _a.atoms;
            var residueIt = mol_data_int["Segmentation"].transientSegments(residueAtomSegments, unit.elements);
            while (residueIt.hasNext) {
                var index = residueIt.move().index;
                sequenceIndices.set(index, sequence.length);
                residueIndices.set(sequence.length, index);
                seqToUnit.set(sequence.length, unit);
                sequence.push(atoms.label_comp_id.value(residueAtomSegments.offsets[index]));
            }
        }
        var length = sequence.length;
        var markerArray = new Uint8Array(length);
        _this = _super.call(this, data, markerArray, length) || this;
        _this.unitMap = new Map();
        for (var _i = 0, _b = data.units; _i < _b.length; _i++) {
            var unit = _b[_i];
            _this.unitMap.set(unit.id, unit);
        }
        _this.sequence = sequence;
        _this.sequenceIndices = sequenceIndices;
        _this.residueIndices = residueIndices;
        _this.seqToUnit = seqToUnit;
        return _this;
    }
    HeteroSequenceWrapper.prototype.residueLabel = function (seqIdx) {
        return this.sequence[seqIdx];
    };
    HeteroSequenceWrapper.prototype.residueColor = function (seqIdx) {
        return names["a" /* ColorNames */].black;
    };
    HeteroSequenceWrapper.prototype.residueClass = function (seqIdx) {
        return 'msp-sequence-present';
    };
    HeteroSequenceWrapper.prototype.mark = function (loci, action) {
        var _this = this;
        var changed = false;
        var structure = this.data.structure;
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            loci = mol_model_structure["StructureElement"].Loci.remap(loci, structure);
            var _loop_1 = function (e) {
                var unit = this_1.unitMap.get(e.unit.id);
                if (unit) {
                    var residueIndex_1 = e.unit.model.atomicHierarchy.residueAtomSegments.index;
                    mol_data_int["OrderedSet"].forEach(e.indices, function (v) {
                        var seqIdx = _this.sequenceIndices.get(residueIndex_1[unit.elements[v]]);
                        if (seqIdx !== undefined && Object(marker_action["c" /* applyMarkerAction */])(_this.markerArray, mol_data_int["Interval"].ofSingleton(seqIdx), action))
                            changed = true;
                    });
                }
            };
            var this_1 = this;
            for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
                var e = _a[_i];
                _loop_1(e);
            }
        }
        else if (mol_model_structure["Structure"].isLoci(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, mol_data_int["Interval"].ofBounds(0, this.length), action))
                changed = true;
        }
        return changed;
    };
    HeteroSequenceWrapper.prototype.getLoci = function (seqIdx) {
        var elements = [];
        var rI = this.residueIndices.get(seqIdx);
        if (rI !== undefined) {
            var unit = this.seqToUnit.get(seqIdx);
            var offsets = unit.model.atomicHierarchy.residueAtomSegments.offsets;
            var start = mol_data_int["SortedArray"].findPredecessorIndex(unit.elements, offsets[rI]);
            var end = mol_data_int["SortedArray"].findPredecessorIndex(unit.elements, offsets[rI + 1]);
            elements.push({ unit: unit, indices: mol_data_int["Interval"].ofBounds(start, end) });
        }
        return mol_model_structure["StructureElement"].Loci(this.data.structure, elements);
    };
    return HeteroSequenceWrapper;
}(wrapper_SequenceWrapper));

//# sourceMappingURL=hetero.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/chain.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var chain_ChainSequenceWrapper = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ChainSequenceWrapper, _super);
    function ChainSequenceWrapper(data) {
        var _this = this;
        var residueCount = 0;
        var elementCount = 0;
        var counts = [];
        var l = mol_model_structure["StructureElement"].Location.create(data.structure);
        var unitIndices = new Map();
        var lociElements = [];
        for (var i = 0, il = data.units.length; i < il; ++i) {
            var unit = data.units[i];
            mol_model_structure["StructureElement"].Location.set(l, data.structure, unit, unit.elements[0]);
            var entitySeq = unit.model.sequence.byEntityKey[mol_model_structure["StructureProperties"].entity.key(l)];
            if (entitySeq)
                residueCount += entitySeq.sequence.length;
            elementCount += unit.elements.length;
            var indices = mol_data_int["Interval"].ofBounds(0, unit.elements.length);
            unitIndices.set(unit.id, indices);
            lociElements.push({ unit: unit, indices: indices });
        }
        if (residueCount > 0)
            counts.push(residueCount + " residues");
        counts.push(elementCount + " elements");
        var length = 1;
        var markerArray = new Uint8Array(length);
        _this = _super.call(this, data, markerArray, length) || this;
        _this.label = "Whole Chain (" + counts.join(', ') + ")";
        _this.unitIndices = unitIndices;
        _this.loci = mol_model_structure["StructureElement"].Loci(_this.data.structure, lociElements);
        return _this;
    }
    ChainSequenceWrapper.prototype.residueLabel = function (seqIdx) {
        return this.label;
    };
    ChainSequenceWrapper.prototype.residueColor = function (seqIdx) {
        return names["a" /* ColorNames */].black;
    };
    ChainSequenceWrapper.prototype.residueClass = function (seqIdx) {
        return 'msp-sequence-present';
    };
    ChainSequenceWrapper.prototype.mark = function (loci, action) {
        var changed = false;
        var structure = this.data.structure;
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            loci = mol_model_structure["StructureElement"].Loci.remap(loci, structure);
            for (var _i = 0, _a = loci.elements; _i < _a.length; _i++) {
                var e = _a[_i];
                var indices = this.unitIndices.get(e.unit.id);
                if (indices) {
                    if (mol_data_int["OrderedSet"].isSubset(indices, e.indices)) {
                        if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, mol_data_int["Interval"].ofSingleton(0), action))
                            changed = true;
                    }
                }
            }
        }
        else if (mol_model_structure["Structure"].isLoci(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, mol_data_int["Interval"].ofSingleton(0), action))
                changed = true;
        }
        return changed;
    };
    ChainSequenceWrapper.prototype.getLoci = function (seqIdx) {
        return this.loci;
    };
    return ChainSequenceWrapper;
}(wrapper_SequenceWrapper));

//# sourceMappingURL=chain.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence/element.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */






var element_ElementSequenceWrapper = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ElementSequenceWrapper, _super);
    function ElementSequenceWrapper(data) {
        var _this = this;
        var length = 0;
        var unitIndices = new Map();
        var lociElements = [];
        for (var i = 0, il = data.units.length; i < il; ++i) {
            var unit = data.units[i];
            length += unit.elements.length;
            var indices = mol_data_int["Interval"].ofBounds(0, unit.elements.length);
            unitIndices.set(unit.id, indices);
            lociElements.push({ unit: unit, indices: indices });
        }
        var markerArray = new Uint8Array(length);
        _this = _super.call(this, data, markerArray, length) || this;
        _this.unitIndices = unitIndices;
        return _this;
    }
    ElementSequenceWrapper.prototype.residueLabel = function (seqIdx) {
        return 'X';
    };
    ElementSequenceWrapper.prototype.residueColor = function (seqIdx) {
        return names["a" /* ColorNames */].black;
    };
    ElementSequenceWrapper.prototype.residueClass = function (seqIdx) {
        return 'msp-sequence-present';
    };
    ElementSequenceWrapper.prototype.mark = function (loci, action) {
        var changed = false;
        var _a = this.data, structure = _a.structure, units = _a.units;
        if (mol_model_structure["StructureElement"].Loci.is(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            loci = mol_model_structure["StructureElement"].Loci.remap(loci, structure);
            for (var _i = 0, _b = loci.elements; _i < _b.length; _i++) {
                var e = _b[_i];
                var indices = this.unitIndices.get(e.unit.id);
                if (indices) {
                    if (mol_data_int["OrderedSet"].isSubset(indices, e.indices)) {
                        if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, e.indices, action))
                            changed = true;
                    }
                }
            }
        }
        else if (mol_model_structure["Structure"].isLoci(loci)) {
            if (!mol_model_structure["Structure"].areRootsEquivalent(loci.structure, structure))
                return false;
            for (var i = 0, il = units.length; i < il; ++i) {
                var indices = this.unitIndices.get(units[i].id);
                if (Object(marker_action["c" /* applyMarkerAction */])(this.markerArray, indices, action))
                    changed = true;
            }
        }
        return changed;
    };
    ElementSequenceWrapper.prototype.getLoci = function (seqIdx) {
        var units = this.data.units;
        var lociElements = [];
        var offset = 0;
        for (var i = 0, il = units.length; i < il; ++i) {
            var unit = units[i];
            if (seqIdx < offset + unit.elements.length) {
                lociElements.push({ unit: unit, indices: mol_data_int["Interval"].ofSingleton(seqIdx - offset) });
                break;
            }
            offset += unit.elements.length;
        }
        return mol_model_structure["StructureElement"].Loci(this.data.structure, lociElements);
    };
    return ElementSequenceWrapper;
}(wrapper_SequenceWrapper));

//# sourceMappingURL=element.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-theme/label.js
var mol_theme_label = __webpack_require__(72);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/sequence.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 * @author David Sehnal <david.sehnal@gmail.com>
 */
















var MaxDisplaySequenceLength = 5000;
function opKey(l) {
    var ids = mol_model_structure["StructureProperties"].unit.pdbx_struct_oper_list_ids(l);
    var ncs = mol_model_structure["StructureProperties"].unit.struct_ncs_oper_id(l);
    var hkl = mol_model_structure["StructureProperties"].unit.hkl(l);
    var spgrOp = mol_model_structure["StructureProperties"].unit.spgrOp(l);
    return ids.sort().join(',') + "|" + ncs + "|" + hkl + "|" + spgrOp;
}
function splitModelEntityId(modelEntityId) {
    var _a = modelEntityId.split('|'), modelIdx = _a[0], entityId = _a[1];
    return [parseInt(modelIdx), entityId];
}
function getSequenceWrapper(state, structureSelection) {
    var structure = state.structure, modelEntityId = state.modelEntityId, chainGroupId = state.chainGroupId, operatorKey = state.operatorKey;
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var _a = splitModelEntityId(modelEntityId), modelIdx = _a[0], entityId = _a[1];
    var units = [];
    for (var _i = 0, _b = structure.units; _i < _b.length; _i++) {
        var unit = _b[_i];
        mol_model_structure["StructureElement"].Location.set(l, structure, unit, unit.elements[0]);
        if (structure.getModelIndex(unit.model) !== modelIdx)
            continue;
        if (mol_model_structure["StructureProperties"].entity.id(l) !== entityId)
            continue;
        if (unit.chainGroupId !== chainGroupId)
            continue;
        if (opKey(l) !== operatorKey)
            continue;
        units.push(unit);
    }
    if (units.length > 0) {
        var data = { structure: structure, units: units };
        var unit = units[0];
        var sw = void 0;
        if (unit.polymerElements.length) {
            var l_1 = mol_model_structure["StructureElement"].Location.create(structure, unit, unit.elements[0]);
            var entitySeq = unit.model.sequence.byEntityKey[mol_model_structure["StructureProperties"].entity.key(l_1)];
            // check if entity sequence is available
            if (entitySeq && entitySeq.sequence.length <= MaxDisplaySequenceLength) {
                sw = new polymer_PolymerSequenceWrapper(data);
            }
            else {
                var polymerElementCount = units.reduce(function (a, v) { return a + v.polymerElements.length; }, 0);
                if (mol_model_structure["Unit"].isAtomic(unit) || polymerElementCount > MaxDisplaySequenceLength) {
                    sw = new chain_ChainSequenceWrapper(data);
                }
                else {
                    sw = new element_ElementSequenceWrapper(data);
                }
            }
        }
        else if (mol_model_structure["Unit"].isAtomic(unit)) {
            var residueCount = units.reduce(function (a, v) { return a + v.residueCount; }, 0);
            if (residueCount > MaxDisplaySequenceLength) {
                sw = new chain_ChainSequenceWrapper(data);
            }
            else {
                sw = new hetero_HeteroSequenceWrapper(data);
            }
        }
        else {
            console.warn('should not happen, expecting coarse units to be polymeric');
            sw = new chain_ChainSequenceWrapper(data);
        }
        sw.markResidue(structureSelection.getLoci(structure), marker_action["a" /* MarkerAction */].Select);
        return sw;
    }
    else {
        return 'No sequence available';
    }
}
function getModelEntityOptions(structure) {
    var options = [];
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var seen = new Set();
    for (var _i = 0, _a = structure.units; _i < _a.length; _i++) {
        var unit = _a[_i];
        mol_model_structure["StructureElement"].Location.set(l, structure, unit, unit.elements[0]);
        var id = mol_model_structure["StructureProperties"].entity.id(l);
        var modelIdx = structure.getModelIndex(unit.model);
        var key = modelIdx + "|" + id;
        if (seen.has(key))
            continue;
        var description = mol_model_structure["StructureProperties"].entity.pdbx_description(l).join(', ');
        if (structure.models.length) {
            if (structure.representativeModel) { // indicates model trajectory
                description += " (Model " + structure.models[modelIdx].modelNum + ")";
            }
            else if (description.startsWith('Polymer ')) { // indicates generic entity name
                description += " (" + structure.models[modelIdx].entry + ")";
            }
        }
        var label = id + ": " + description;
        options.push([key, label]);
        seen.add(key);
    }
    if (options.length === 0)
        options.push(['', 'No entities']);
    return options;
}
function getChainOptions(structure, modelEntityId) {
    var options = [];
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var seen = new Set();
    var _a = splitModelEntityId(modelEntityId), modelIdx = _a[0], entityId = _a[1];
    for (var _i = 0, _b = structure.units; _i < _b.length; _i++) {
        var unit = _b[_i];
        mol_model_structure["StructureElement"].Location.set(l, structure, unit, unit.elements[0]);
        if (structure.getModelIndex(unit.model) !== modelIdx)
            continue;
        if (mol_model_structure["StructureProperties"].entity.id(l) !== entityId)
            continue;
        var id = unit.chainGroupId;
        if (seen.has(id))
            continue;
        // TODO handle special case
        // - more than one chain in a unit
        var label = Object(mol_theme_label["elementLabel"])(l, { granularity: 'chain', hidePrefix: true, htmlStyling: false });
        options.push([id, label]);
        seen.add(id);
    }
    if (options.length === 0)
        options.push([-1, 'No units']);
    return options;
}
function getOperatorOptions(structure, modelEntityId, chainGroupId) {
    var options = [];
    var l = mol_model_structure["StructureElement"].Location.create(structure);
    var seen = new Set();
    var _a = splitModelEntityId(modelEntityId), modelIdx = _a[0], entityId = _a[1];
    for (var _i = 0, _b = structure.units; _i < _b.length; _i++) {
        var unit = _b[_i];
        mol_model_structure["StructureElement"].Location.set(l, structure, unit, unit.elements[0]);
        if (structure.getModelIndex(unit.model) !== modelIdx)
            continue;
        if (mol_model_structure["StructureProperties"].entity.id(l) !== entityId)
            continue;
        if (unit.chainGroupId !== chainGroupId)
            continue;
        var id = opKey(l);
        if (seen.has(id))
            continue;
        var label = unit.conformation.operator.name;
        options.push([id, label]);
        seen.add(id);
    }
    if (options.length === 0)
        options.push(['', 'No operators']);
    return options;
}
function getStructureOptions(state) {
    var options = [];
    var structures = state.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Structure));
    for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
        var s = structures_1[_i];
        options.push([s.transform.ref, s.obj.data.label]);
    }
    if (options.length === 0)
        options.push(['', 'No structure']);
    return options;
}
var sequence_SequenceView = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(SequenceView, _super);
    function SequenceView() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { structure: mol_model_structure["Structure"].Empty, structureRef: '', modelEntityId: '', chainGroupId: -1, operatorKey: '' };
        _this.setParamProps = function (p) {
            var state = Object(tslib_es6["__assign"])({}, _this.state);
            switch (p.name) {
                case 'structure':
                    state.structureRef = p.value;
                    state.structure = _this.getStructure(p.value);
                    state.modelEntityId = getModelEntityOptions(state.structure)[0][0];
                    state.chainGroupId = getChainOptions(state.structure, state.modelEntityId)[0][0];
                    state.operatorKey = getOperatorOptions(state.structure, state.modelEntityId, state.chainGroupId)[0][0];
                    break;
                case 'entity':
                    state.modelEntityId = p.value;
                    state.chainGroupId = getChainOptions(state.structure, state.modelEntityId)[0][0];
                    state.operatorKey = getOperatorOptions(state.structure, state.modelEntityId, state.chainGroupId)[0][0];
                    break;
                case 'chain':
                    state.chainGroupId = p.value;
                    state.operatorKey = getOperatorOptions(state.structure, state.modelEntityId, state.chainGroupId)[0][0];
                    break;
                case 'operator':
                    state.operatorKey = p.value;
                    break;
            }
            _this.setState(state);
        };
        return _this;
    }
    SequenceView.prototype.componentDidMount = function () {
        var _this = this;
        if (this.plugin.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Structure)).length > 0)
            this.setState(this.getInitialState());
        this.subscribe(this.plugin.state.events.object.updated, function (_a) {
            var ref = _a.ref, obj = _a.obj;
            if (ref === _this.state.structureRef && obj && obj.type === objects["a" /* PluginStateObject */].Molecule.Structure.type && obj.data !== _this.state.structure) {
                _this.setState(_this.getInitialState());
            }
        });
        this.subscribe(this.plugin.state.events.object.created, function (_a) {
            var obj = _a.obj;
            if (obj && obj.type === objects["a" /* PluginStateObject */].Molecule.Structure.type) {
                _this.setState(_this.getInitialState());
            }
        });
        this.subscribe(this.plugin.state.events.object.removed, function (_a) {
            var obj = _a.obj;
            if (obj && obj.type === objects["a" /* PluginStateObject */].Molecule.Structure.type && obj.data === _this.state.structure) {
                _this.setState(_this.getInitialState());
            }
        });
    };
    SequenceView.prototype.getStructure = function (ref) {
        var state = this.plugin.state.data;
        var cell = state.select(ref)[0];
        if (!ref || !cell || !cell.obj)
            return mol_model_structure["Structure"].Empty;
        return cell.obj.data;
    };
    SequenceView.prototype.getSequenceWrapper = function () {
        return getSequenceWrapper(this.state, this.plugin.managers.structure.selection);
    };
    SequenceView.prototype.getInitialState = function () {
        var structureRef = getStructureOptions(this.plugin.state.data)[0][0];
        var structure = this.getStructure(structureRef);
        var modelEntityId = getModelEntityOptions(structure)[0][0];
        var chainGroupId = getChainOptions(structure, modelEntityId)[0][0];
        var operatorKey = getOperatorOptions(structure, modelEntityId, chainGroupId)[0][0];
        if (this.state.structure && this.state.structure === structure) {
            modelEntityId = this.state.modelEntityId;
            chainGroupId = this.state.chainGroupId;
            operatorKey = this.state.operatorKey;
        }
        return { structure: structure, structureRef: structureRef, modelEntityId: modelEntityId, chainGroupId: chainGroupId, operatorKey: operatorKey };
    };
    Object.defineProperty(SequenceView.prototype, "params", {
        get: function () {
            var _a = this.state, structure = _a.structure, modelEntityId = _a.modelEntityId, chainGroupId = _a.chainGroupId;
            var structureOptions = getStructureOptions(this.plugin.state.data);
            var entityOptions = getModelEntityOptions(structure);
            var chainOptions = getChainOptions(structure, modelEntityId);
            var operatorOptions = getOperatorOptions(structure, modelEntityId, chainGroupId);
            return {
                structure: param_definition["ParamDefinition"].Select(structureOptions[0][0], structureOptions, { shortLabel: true }),
                entity: param_definition["ParamDefinition"].Select(entityOptions[0][0], entityOptions, { shortLabel: true }),
                chain: param_definition["ParamDefinition"].Select(chainOptions[0][0], chainOptions, { shortLabel: true, twoColumns: true, label: 'Chain' }),
                operator: param_definition["ParamDefinition"].Select(operatorOptions[0][0], operatorOptions, { shortLabel: true, twoColumns: true })
            };
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(SequenceView.prototype, "values", {
        get: function () {
            return {
                structure: this.state.structureRef,
                entity: this.state.modelEntityId,
                chain: this.state.chainGroupId,
                operator: this.state.operatorKey
            };
        },
        enumerable: false,
        configurable: true
    });
    SequenceView.prototype.render = function () {
        if (this.getStructure(this.state.structureRef) === mol_model_structure["Structure"].Empty) {
            return react["createElement"]("div", { className: 'msp-sequence' },
                react["createElement"]("div", { className: 'msp-sequence-select' },
                    react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"], style: { cursor: 'help', position: 'absolute', right: 0, top: 0 }, title: 'This shows a single sequence. Use the controls to show a different sequence.' }),
                    react["createElement"]("span", null, "Sequence"),
                    react["createElement"]("span", { style: { fontWeight: 'normal' } }, "No structure available")));
        }
        var sequenceWrapper = this.getSequenceWrapper();
        var params = this.params;
        var values = this.values;
        return react["createElement"]("div", { className: 'msp-sequence' },
            react["createElement"]("div", { className: 'msp-sequence-select' },
                react["createElement"](icons["Icon"], { svg: icons["HelpOutlineSvg"], style: { cursor: 'help', position: 'absolute', right: 0, top: 0 }, title: 'This shows a single sequence. Use the controls to show a different sequence.' }),
                react["createElement"]("span", null, "Sequence of"),
                react["createElement"](parameters["PureSelectControl"], { title: "[Structure] " + param_definition["ParamDefinition"].optionLabel(params.structure, values.structure), param: params.structure, name: 'structure', value: values.structure, onChange: this.setParamProps }),
                react["createElement"](parameters["PureSelectControl"], { title: "[Entity] " + param_definition["ParamDefinition"].optionLabel(params.entity, values.entity), param: params.entity, name: 'entity', value: values.entity, onChange: this.setParamProps }),
                react["createElement"](parameters["PureSelectControl"], { title: "[Chain] " + param_definition["ParamDefinition"].optionLabel(params.chain, values.chain), param: params.chain, name: 'chain', value: values.chain, onChange: this.setParamProps }),
                params.operator.options.length > 1 && react["createElement"](react["Fragment"], null,
                    react["createElement"](parameters["PureSelectControl"], { title: "[Instance] " + param_definition["ParamDefinition"].optionLabel(params.operator, values.operator), param: params.operator, name: 'operator', value: values.operator, onChange: this.setParamProps }))),
            typeof sequenceWrapper === 'string'
                ? react["createElement"]("div", { className: 'msp-sequence-wrapper msp-sequence-wrapper-non-empty' }, sequenceWrapper)
                : react["createElement"](sequence_Sequence, { sequenceWrapper: sequenceWrapper }));
    };
    return SequenceView;
}(base["PluginUIComponent"]));

//# sourceMappingURL=sequence.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/task.js
var task = __webpack_require__(389);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/toast.js
var toast = __webpack_require__(390);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-ui/viewport.js + 1 modules
var mol_plugin_ui_viewport = __webpack_require__(323);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-ui/plugin.js
/**
 * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */











var plugin_Plugin = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Plugin, _super);
    function Plugin() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    Plugin.prototype.region = function (kind, element) {
        return react["createElement"]("div", { className: "msp-layout-region msp-layout-" + kind },
            react["createElement"]("div", { className: 'msp-layout-static' }, element));
    };
    Plugin.prototype.render = function () {
        return react["createElement"](base["PluginReactContext"].Provider, { value: this.props.plugin },
            react["createElement"](plugin_Layout, null));
    };
    return Plugin;
}(react["Component"]));

var plugin_PluginContextContainer = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(PluginContextContainer, _super);
    function PluginContextContainer() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    PluginContextContainer.prototype.render = function () {
        return react["createElement"](base["PluginReactContext"].Provider, { value: this.props.plugin },
            react["createElement"]("div", { className: 'msp-plugin' }, this.props.children));
    };
    return PluginContextContainer;
}(react["Component"]));

var plugin_Layout = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Layout, _super);
    function Layout() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.onDrop = function (ev) {
            ev.preventDefault();
            var file;
            if (ev.dataTransfer.items) {
                // Use DataTransferItemList interface to access the file(s)
                for (var i = 0; i < ev.dataTransfer.items.length; i++) {
                    if (ev.dataTransfer.items[i].kind !== 'file')
                        continue;
                    file = ev.dataTransfer.items[i].getAsFile();
                    break;
                }
            }
            else {
                file = ev.dataTransfer.files[0];
            }
            if (!file)
                return;
            var fn = (file === null || file === void 0 ? void 0 : file.name.toLowerCase()) || '';
            if (fn.endsWith('molx') || fn.endsWith('molj')) {
                commands["PluginCommands"].State.Snapshots.OpenFile(_this.plugin, { file: file });
            }
        };
        _this.onDragOver = function (ev) {
            ev.preventDefault();
        };
        return _this;
    }
    Layout.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.layout.events.updated, function () { return _this.forceUpdate(); });
    };
    Layout.prototype.region = function (kind, Element) {
        return react["createElement"]("div", { className: "msp-layout-region msp-layout-" + kind },
            react["createElement"]("div", { className: 'msp-layout-static' }, Element ? react["createElement"](Element, null) : null));
    };
    Object.defineProperty(Layout.prototype, "layoutVisibilityClassName", {
        get: function () {
            var layout = this.plugin.layout.state;
            var controls = (this.plugin.spec.layout && this.plugin.spec.layout.controls) || {};
            var classList = [];
            if (controls.top === 'none' || !layout.showControls || layout.regionState.top === 'hidden') {
                classList.push('msp-layout-hide-top');
            }
            if (controls.left === 'none' || !layout.showControls || layout.regionState.left === 'hidden') {
                classList.push('msp-layout-hide-left');
            }
            else if (layout.regionState.left === 'collapsed') {
                classList.push('msp-layout-collapse-left');
            }
            if (controls.right === 'none' || !layout.showControls || layout.regionState.right === 'hidden') {
                classList.push('msp-layout-hide-right');
            }
            if (controls.bottom === 'none' || !layout.showControls || layout.regionState.bottom === 'hidden') {
                classList.push('msp-layout-hide-bottom');
            }
            return classList.join(' ');
        },
        enumerable: false,
        configurable: true
    });
    Object.defineProperty(Layout.prototype, "layoutClassName", {
        get: function () {
            var layout = this.plugin.layout.state;
            var classList = ['msp-plugin-content'];
            if (layout.isExpanded) {
                classList.push('msp-layout-expanded');
            }
            else {
                classList.push('msp-layout-standard', "msp-layout-standard-" + layout.controlsDisplay);
            }
            return classList.join(' ');
        },
        enumerable: false,
        configurable: true
    });
    Layout.prototype.render = function () {
        var _a, _b, _c;
        var layout = this.plugin.layout.state;
        var controls = ((_a = this.plugin.spec.layout) === null || _a === void 0 ? void 0 : _a.controls) || {};
        var viewport = ((_c = (_b = this.plugin.spec.components) === null || _b === void 0 ? void 0 : _b.viewport) === null || _c === void 0 ? void 0 : _c.view) || plugin_DefaultViewport;
        return react["createElement"]("div", { className: 'msp-plugin', onDrop: this.onDrop, onDragOver: this.onDragOver },
            react["createElement"]("div", { className: this.layoutClassName },
                react["createElement"]("div", { className: this.layoutVisibilityClassName },
                    this.region('main', viewport),
                    layout.showControls && controls.top !== 'none' && this.region('top', controls.top || sequence_SequenceView),
                    layout.showControls && controls.left !== 'none' && this.region('left', controls.left || left_panel_LeftPanelControls),
                    layout.showControls && controls.right !== 'none' && this.region('right', controls.right || plugin_ControlsWrapper),
                    layout.showControls && controls.bottom !== 'none' && this.region('bottom', controls.bottom || plugin_Log))));
    };
    return Layout;
}(base["PluginUIComponent"]));
var plugin_ControlsWrapper = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(ControlsWrapper, _super);
    function ControlsWrapper() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    ControlsWrapper.prototype.render = function () {
        var _a;
        var StructureTools = ((_a = this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.structureTools) || mol_plugin_ui_controls["DefaultStructureTools"];
        return react["createElement"]("div", { className: 'msp-scrollable-container' },
            react["createElement"](StructureTools, null));
    };
    return ControlsWrapper;
}(base["PluginUIComponent"]));

var plugin_DefaultViewport = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(DefaultViewport, _super);
    function DefaultViewport() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    DefaultViewport.prototype.render = function () {
        var _a, _b;
        var VPControls = ((_b = (_a = this.plugin.spec.components) === null || _a === void 0 ? void 0 : _a.viewport) === null || _b === void 0 ? void 0 : _b.controls) || mol_plugin_ui_viewport["ViewportControls"];
        return react["createElement"](react["Fragment"], null,
            react["createElement"](mol_plugin_ui_viewport["Viewport"], null),
            react["createElement"]("div", { className: 'msp-viewport-top-left-controls' },
                react["createElement"](mol_plugin_ui_controls["AnimationViewportControls"], null),
                react["createElement"](mol_plugin_ui_controls["TrajectoryViewportControls"], null),
                react["createElement"](mol_plugin_ui_controls["StateSnapshotViewportControls"], null)),
            react["createElement"](mol_plugin_ui_controls["SelectionViewportControls"], null),
            react["createElement"](VPControls, null),
            react["createElement"](task["BackgroundTaskProgress"], null),
            react["createElement"]("div", { className: 'msp-highlight-toast-wrapper' },
                react["createElement"](mol_plugin_ui_controls["LociLabels"], null),
                react["createElement"](toast["Toasts"], null)));
    };
    return DefaultViewport;
}(base["PluginUIComponent"]));

var plugin_Log = /** @class */ (function (_super) {
    Object(tslib_es6["__extends"])(Log, _super);
    function Log() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.wrapper = react["createRef"]();
        _this.state = { entries: _this.plugin.log.entries };
        return _this;
    }
    Log.prototype.componentDidMount = function () {
        var _this = this;
        this.subscribe(this.plugin.events.log, function () { return _this.setState({ entries: _this.plugin.log.entries }); });
    };
    Log.prototype.componentDidUpdate = function () {
        this.scrollToBottom();
    };
    Log.prototype.scrollToBottom = function () {
        var log = this.wrapper.current;
        if (log)
            log.scrollTop = log.scrollHeight - log.clientHeight - 1;
    };
    Log.prototype.render = function () {
        // TODO: ability to show full log
        // showing more entries dramatically slows animations.
        var maxEntries = 10;
        var xs = this.state.entries, l = xs.size;
        var entries = [];
        for (var i = Math.max(0, l - maxEntries), o = 0; i < l; i++) {
            var e = xs.get(i);
            entries.push(react["createElement"]("li", { key: o++ },
                react["createElement"]("div", { className: 'msp-log-entry-badge msp-log-entry-' + e.type }),
                react["createElement"]("div", { className: 'msp-log-timestamp' }, Object(mol_util["j" /* formatTime */])(e.timestamp)),
                react["createElement"]("div", { className: 'msp-log-entry' }, e.message)));
        }
        return react["createElement"]("div", { ref: this.wrapper, className: 'msp-log', style: { position: 'absolute', top: '0', right: '0', bottom: '0', left: '0', overflowY: 'auto' } },
            react["createElement"]("ul", { className: 'msp-list-unstyled' }, entries));
    };
    return Log;
}(base["PluginUIComponent"]));

//# sourceMappingURL=plugin.js.map

/***/ }),
/* 449 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "PDBeStructureQualityReport", function() { return /* reexport */ behavior["PDBeStructureQualityReport"]; });
__webpack_require__.d(__webpack_exports__, "PDBePreferredAssembly", function() { return /* reexport */ preferred_assembly_PDBePreferredAssembly; });
__webpack_require__.d(__webpack_exports__, "PDBeStructRefDomain", function() { return /* reexport */ struct_ref_domain_PDBeStructRefDomain; });

// EXTERNAL MODULE: ./node_modules/molstar/lib/extensions/pdbe/structure-quality-report/behavior.js
var behavior = __webpack_require__(385);

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-data/db.js + 3 modules
var mol_data_db = __webpack_require__(7);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/reader/cif/schema.js
var schema = __webpack_require__(135);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-io/writer/cif.js + 6 modules
var cif = __webpack_require__(62);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/property/symmetry.js + 1 modules
var property_symmetry = __webpack_require__(113);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-formats/structure/mmcif.js
var mmcif = __webpack_require__(71);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model/custom-property.js
var custom_property = __webpack_require__(65);

// CONCATENATED MODULE: ./node_modules/molstar/lib/extensions/pdbe/preferred-assembly.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var preferred_assembly_PDBePreferredAssembly;
(function (PDBePreferredAssembly) {
    function getFirstFromModel(model) {
        var symmetry = property_symmetry["a" /* ModelSymmetry */].Provider.get(model);
        return (symmetry === null || symmetry === void 0 ? void 0 : symmetry.assemblies.length) ? symmetry.assemblies[0].id : '';
    }
    PDBePreferredAssembly.getFirstFromModel = getFirstFromModel;
    function get(model) {
        return model._staticPropertyData.__PDBePreferredAssebly__ || getFirstFromModel(model);
    }
    PDBePreferredAssembly.get = get;
    function set(model, prop) {
        model._staticPropertyData.__PDBePreferredAssebly__ = prop;
    }
    PDBePreferredAssembly.Schema = {
        pdbe_preferred_assembly: {
            assembly_id: mol_data_db["Column"].Schema.str
        }
    };
    PDBePreferredAssembly.Descriptor = Object(custom_property["CustomPropertyDescriptor"])({
        name: 'pdbe_preferred_assembly',
        cifExport: {
            prefix: 'pdbe',
            context: function (ctx) { return get(ctx.firstModel); },
            categories: [{
                    name: 'pdbe_preferred_assembly',
                    instance: function (ctx) {
                        return cif["a" /* CifWriter */].Category.ofTable(mol_data_db["Table"].ofArrays(PDBePreferredAssembly.Schema.pdbe_preferred_assembly, { assembly_id: [ctx] }));
                    }
                }]
        }
    });
    function fromCifData(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return void 0;
        var cat = model.sourceData.data.frame.categories.pdbe_preferred_assembly;
        if (!cat)
            return void 0;
        return Object(schema["toTable"])(PDBePreferredAssembly.Schema.pdbe_preferred_assembly, cat).assembly_id.value(0) || getFirstFromModel(model);
    }
    function attachFromCifOrApi(model, params) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var asmName, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (model.customProperties.has(PDBePreferredAssembly.Descriptor))
                            return [2 /*return*/, true];
                        asmName = fromCifData(model);
                        if (!(asmName === void 0 && params.PDBe_apiSourceJson)) return [3 /*break*/, 2];
                        return [4 /*yield*/, params.PDBe_apiSourceJson(model)];
                    case 1:
                        data = _a.sent();
                        if (!data)
                            return [2 /*return*/, false];
                        asmName = asmNameFromJson(model, data);
                        return [3 /*break*/, 3];
                    case 2: return [2 /*return*/, false];
                    case 3:
                        if (!asmName)
                            return [2 /*return*/, false];
                        model.customProperties.add(PDBePreferredAssembly.Descriptor);
                        set(model, asmName);
                        return [2 /*return*/, true];
                }
            });
        });
    }
    PDBePreferredAssembly.attachFromCifOrApi = attachFromCifOrApi;
})(preferred_assembly_PDBePreferredAssembly || (preferred_assembly_PDBePreferredAssembly = {}));
function asmNameFromJson(modelData, data) {
    var assemblies = data[0] && data[0].assemblies;
    if (!assemblies || !assemblies.length)
        return preferred_assembly_PDBePreferredAssembly.getFirstFromModel(modelData);
    for (var _i = 0, assemblies_1 = assemblies; _i < assemblies_1.length; _i++) {
        var asm = assemblies_1[_i];
        if (asm.preferred) {
            return asm.assembly_id;
        }
    }
    return assemblies[0].assembly_id;
}
//# sourceMappingURL=preferred-assembly.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-model-props/common/wrapper.js
var wrapper = __webpack_require__(236);

// CONCATENATED MODULE: ./node_modules/molstar/lib/extensions/pdbe/struct-ref-domain.js
/**
 * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var struct_ref_domain_PDBeStructRefDomain;
(function (PDBeStructRefDomain) {
    function get(model) {
        return model._staticPropertyData.__PDBeStructRefSeq__;
    }
    PDBeStructRefDomain.get = get;
    function set(model, prop) {
        model._staticPropertyData.__PDBeStructRefSeq__ = prop;
    }
    PDBeStructRefDomain.Schema = {
        pdbe_struct_ref_domain: {
            id: mol_data_db["Column"].Schema.int,
            db_name: mol_data_db["Column"].Schema.str,
            db_code: mol_data_db["Column"].Schema.str,
            identifier: mol_data_db["Column"].Schema.str,
            name: mol_data_db["Column"].Schema.str,
            label_entity_id: mol_data_db["Column"].Schema.str,
            label_asym_id: mol_data_db["Column"].Schema.str,
            beg_label_seq_id: mol_data_db["Column"].Schema.int,
            beg_pdbx_PDB_ins_code: mol_data_db["Column"].Schema.str,
            end_label_seq_id: mol_data_db["Column"].Schema.int,
            end_pdbx_PDB_ins_code: mol_data_db["Column"].Schema.str
        }
    };
    PDBeStructRefDomain.Descriptor = Object(custom_property["CustomPropertyDescriptor"])({
        name: 'pdbe_struct_ref_domain',
        cifExport: {
            prefix: 'pdbe',
            context: function (ctx) { return get(ctx.firstModel); },
            categories: [
                wrapper["PropertyWrapper"].defaultInfoCategory('pdbe_struct_ref_domain_info', function (ctx) { return ctx.info; }),
                {
                    name: 'pdbe_struct_ref_domain',
                    instance: function (ctx) {
                        if (!ctx || !ctx.data)
                            return cif["a" /* CifWriter */].Category.Empty;
                        return cif["a" /* CifWriter */].Category.ofTable(ctx.data);
                    }
                }
            ]
        }
    });
    function fromCifData(model) {
        if (!mmcif["MmcifFormat"].is(model.sourceData))
            return void 0;
        var cat = model.sourceData.data.frame.categories.pdbe_struct_ref_domain;
        if (!cat)
            return void 0;
        return Object(schema["toTable"])(PDBeStructRefDomain.Schema.pdbe_struct_ref_domain, cat);
    }
    function attachFromCifOrApi(model, params) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var table, info, data;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (model.customProperties.has(PDBeStructRefDomain.Descriptor))
                            return [2 /*return*/, true];
                        info = wrapper["PropertyWrapper"].tryGetInfoFromCif('pdbe_struct_ref_domain_info', model);
                        if (!info) return [3 /*break*/, 1];
                        table = fromCifData(model);
                        return [3 /*break*/, 4];
                    case 1:
                        if (!params.PDBe_apiSourceJson) return [3 /*break*/, 3];
                        return [4 /*yield*/, params.PDBe_apiSourceJson(model)];
                    case 2:
                        data = _a.sent();
                        if (!data)
                            return [2 /*return*/, false];
                        info = wrapper["PropertyWrapper"].createInfo();
                        table = fromPDBeJson(model, data);
                        return [3 /*break*/, 4];
                    case 3: return [2 /*return*/, false];
                    case 4:
                        model.customProperties.add(PDBeStructRefDomain.Descriptor);
                        set(model, { info: info, data: table });
                        return [2 /*return*/, true];
                }
            });
        });
    }
    PDBeStructRefDomain.attachFromCifOrApi = attachFromCifOrApi;
})(struct_ref_domain_PDBeStructRefDomain || (struct_ref_domain_PDBeStructRefDomain = {}));
function fromPDBeJson(modelData, data) {
    var rows = [];
    var id = 1;
    for (var _i = 0, _a = Object.keys(data); _i < _a.length; _i++) {
        var db_name = _a[_i];
        var db = data[db_name];
        for (var _b = 0, _c = Object.keys(db); _b < _c.length; _b++) {
            var db_code = _c[_b];
            var domain = db[db_code];
            for (var _d = 0, _e = domain.mappings; _d < _e.length; _d++) {
                var map = _e[_d];
                rows.push({
                    id: id++,
                    db_name: db_name,
                    db_code: db_code,
                    identifier: domain.identifier,
                    name: domain.name,
                    label_entity_id: '' + map.entity_id,
                    label_asym_id: map.struct_asym_id,
                    beg_label_seq_id: map.start.residue_number,
                    beg_pdbx_PDB_ins_code: map.start.author_insertion_code,
                    end_label_seq_id: map.end.residue_number,
                    end_pdbx_PDB_ins_code: map.end.author_insertion_code,
                });
            }
        }
    }
    return mol_data_db["Table"].ofRows(struct_ref_domain_PDBeStructRefDomain.Schema.pdbe_struct_ref_domain, rows);
}
//# sourceMappingURL=struct-ref-domain.js.map
// CONCATENATED MODULE: ./node_modules/molstar/lib/extensions/pdbe/index.js
/**
 * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author Alexander Rose <alexander.rose@weirdbyte.de>
 */



//# sourceMappingURL=index.js.map

/***/ }),
/* 450 */
/***/ (function(module, __webpack_exports__, __webpack_require__) {

"use strict";
// ESM COMPAT FLAG
__webpack_require__.r(__webpack_exports__);

// EXPORTS
__webpack_require__.d(__webpack_exports__, "AnimateModelIndex", function() { return /* binding */ AnimateModelIndex; });
__webpack_require__.d(__webpack_exports__, "AnimateAssemblyUnwind", function() { return /* binding */ AnimateAssemblyUnwind; });
__webpack_require__.d(__webpack_exports__, "AnimateUnitsExplode", function() { return /* binding */ AnimateUnitsExplode; });
__webpack_require__.d(__webpack_exports__, "AnimateStateInterpolation", function() { return /* binding */ AnimateStateInterpolation; });

// EXTERNAL MODULE: ./node_modules/tslib/tslib.es6.js
var tslib_es6 = __webpack_require__(0);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/animation/model.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */

var PluginStateAnimation;
(function (PluginStateAnimation) {
    function create(params) {
        return params;
    }
    PluginStateAnimation.create = create;
})(PluginStateAnimation || (PluginStateAnimation = {}));
//# sourceMappingURL=model.js.map
// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/objects.js
var objects = __webpack_require__(8);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin-state/transforms.js + 5 modules
var transforms = __webpack_require__(28);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-state/index.js + 9 modules
var mol_state = __webpack_require__(13);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-plugin/commands.js
var commands = __webpack_require__(26);

// EXTERNAL MODULE: ./node_modules/molstar/lib/mol-util/param-definition.js
var param_definition = __webpack_require__(2);

// CONCATENATED MODULE: ./node_modules/molstar/lib/mol-plugin-state/animation/built-in.js
/**
 * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
 *
 * @author David Sehnal <david.sehnal@gmail.com>
 */







var AnimateModelIndex = PluginStateAnimation.create({
    name: 'built-in.animate-model-index',
    display: { name: 'Animate Trajectory' },
    params: function () { return ({
        mode: param_definition["ParamDefinition"].MappedStatic('palindrome', {
            palindrome: param_definition["ParamDefinition"].Group({}),
            loop: param_definition["ParamDefinition"].Group({}),
            once: param_definition["ParamDefinition"].Group({ direction: param_definition["ParamDefinition"].Select('forward', [['forward', 'Forward'], ['backward', 'Backward']]) }, { isFlat: true })
        }, { options: [['palindrome', 'Palindrome'], ['loop', 'Loop'], ['once', 'Once']] }),
        maxFPS: param_definition["ParamDefinition"].Numeric(15, { min: 1, max: 30, step: 1 })
    }); },
    canApply: function (ctx) {
        var state = ctx.state.data;
        var models = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Model.ModelFromTrajectory));
        for (var _i = 0, models_1 = models; _i < models_1.length; _i++) {
            var m = models_1[_i];
            var parent_1 = mol_state["StateSelection"].findAncestorOfType(state.tree, state.cells, m.transform.ref, [objects["a" /* PluginStateObject */].Molecule.Trajectory]);
            if (parent_1 && parent_1.obj && parent_1.obj.data.length > 1)
                return { canApply: true };
        }
        return { canApply: false, reason: 'No trajectory to animate' };
    },
    initialState: function () { return ({}); },
    apply: function (animState, t, ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var state, models, update, params, palindromeDirections, isEnd, allSingles, _loop_1, _i, models_2, m;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        // limit fps
                        if (t.current > 0 && t.current - t.lastApplied < 1000 / ctx.params.maxFPS) {
                            return [2 /*return*/, { kind: 'skip' }];
                        }
                        state = ctx.plugin.state.data;
                        models = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Model.ModelFromTrajectory));
                        if (models.length === 0) {
                            // nothing more to do here
                            return [2 /*return*/, { kind: 'finished' }];
                        }
                        update = state.build();
                        params = ctx.params;
                        palindromeDirections = animState.palindromeDirections || {};
                        isEnd = false, allSingles = true;
                        _loop_1 = function (m) {
                            var parent_2 = mol_state["StateSelection"].findAncestorOfType(state.tree, state.cells, m.transform.ref, [objects["a" /* PluginStateObject */].Molecule.Trajectory]);
                            if (!parent_2 || !parent_2.obj)
                                return "continue";
                            var traj = parent_2.obj;
                            if (traj.data.length <= 1)
                                return "continue";
                            update.to(m).update(function (old) {
                                var len = traj.data.length;
                                if (len !== 1) {
                                    allSingles = false;
                                }
                                else {
                                    return old;
                                }
                                var dir = 1;
                                if (params.mode.name === 'once') {
                                    dir = params.mode.params.direction === 'backward' ? -1 : 1;
                                    // if we are at start or end already, do nothing.
                                    if ((dir === -1 && old.modelIndex === 0) || (dir === 1 && old.modelIndex === len - 1)) {
                                        isEnd = true;
                                        return old;
                                    }
                                }
                                else if (params.mode.name === 'palindrome') {
                                    if (old.modelIndex === 0)
                                        dir = 1;
                                    else if (old.modelIndex === len - 1)
                                        dir = -1;
                                    else
                                        dir = palindromeDirections[m.transform.ref] || 1;
                                }
                                palindromeDirections[m.transform.ref] = dir;
                                var modelIndex = (old.modelIndex + dir) % len;
                                if (modelIndex < 0)
                                    modelIndex += len;
                                isEnd = isEnd || (dir === -1 && modelIndex === 0) || (dir === 1 && modelIndex === len - 1);
                                return { modelIndex: modelIndex };
                            });
                        };
                        for (_i = 0, models_2 = models; _i < models_2.length; _i++) {
                            m = models_2[_i];
                            _loop_1(m);
                        }
                        if (!!allSingles) return [3 /*break*/, 2];
                        return [4 /*yield*/, commands["PluginCommands"].State.Update(ctx.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        _a.label = 2;
                    case 2:
                        if (allSingles || (params.mode.name === 'once' && isEnd))
                            return [2 /*return*/, { kind: 'finished' }];
                        if (params.mode.name === 'palindrome')
                            return [2 /*return*/, { kind: 'next', state: { palindromeDirections: palindromeDirections } }];
                        return [2 /*return*/, { kind: 'next', state: {} }];
                }
            });
        });
    }
});
var AnimateAssemblyUnwind = PluginStateAnimation.create({
    name: 'built-in.animate-assembly-unwind',
    display: { name: 'Unwind Assembly' },
    params: function (plugin) {
        var targets = [['all', 'All']];
        var structures = plugin.state.data.select(mol_state["StateSelection"].Generators.rootsOfType(objects["a" /* PluginStateObject */].Molecule.Structure));
        for (var _i = 0, structures_1 = structures; _i < structures_1.length; _i++) {
            var s = structures_1[_i];
            targets.push([s.transform.ref, s.obj.data.models[0].label]);
        }
        return {
            durationInMs: param_definition["ParamDefinition"].Numeric(3000, { min: 100, max: 10000, step: 100 }),
            playOnce: param_definition["ParamDefinition"].Boolean(false),
            target: param_definition["ParamDefinition"].Select(targets[0][0], targets)
        };
    },
    canApply: function (plugin) {
        var state = plugin.state.data;
        var root = mol_state["StateTransform"].RootRef;
        var reprs = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D, root));
        return { canApply: reprs.length > 0 };
    },
    initialState: function () { return ({ t: 0 }); },
    setup: function (params, plugin) {
        var state = plugin.state.data;
        var root = !params.target || params.target === 'all' ? mol_state["StateTransform"].RootRef : params.target;
        var reprs = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D, root));
        var update = state.build();
        var changed = false;
        for (var _i = 0, reprs_1 = reprs; _i < reprs_1.length; _i++) {
            var r = reprs_1[_i];
            var unwinds = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.UnwindStructureAssemblyRepresentation3D, r.transform.ref));
            if (unwinds.length > 0)
                continue;
            changed = true;
            update.to(r)
                .apply(transforms["StateTransforms"].Representation.UnwindStructureAssemblyRepresentation3D, { t: 0 }, { tags: 'animate-assembly-unwind' });
        }
        if (!changed)
            return;
        return update.commit({ doNotUpdateCurrent: true });
    },
    teardown: function (_, plugin) {
        var state = plugin.state.data;
        var reprs = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState)
            .withTag('animate-assembly-unwind'));
        if (reprs.length === 0)
            return;
        var update = state.build();
        for (var _i = 0, reprs_2 = reprs; _i < reprs_2.length; _i++) {
            var r = reprs_2[_i];
            update.delete(r.transform.ref);
        }
        return update.commit();
    },
    apply: function (animState, t, ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var state, root, anims, update, d, newTime, finished, _i, anims_1, m;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        state = ctx.plugin.state.data;
                        root = !ctx.params.target || ctx.params.target === 'all' ? mol_state["StateTransform"].RootRef : ctx.params.target;
                        anims = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.UnwindStructureAssemblyRepresentation3D, root));
                        if (anims.length === 0) {
                            return [2 /*return*/, { kind: 'finished' }];
                        }
                        update = state.build();
                        d = (t.current - t.lastApplied) / ctx.params.durationInMs;
                        newTime = (animState.t + d), finished = false;
                        if (ctx.params.playOnce && newTime >= 1) {
                            finished = true;
                            newTime = 1;
                        }
                        else {
                            newTime = newTime % 1;
                        }
                        for (_i = 0, anims_1 = anims; _i < anims_1.length; _i++) {
                            m = anims_1[_i];
                            update.to(m).update({ t: newTime });
                        }
                        return [4 /*yield*/, commands["PluginCommands"].State.Update(ctx.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        if (finished)
                            return [2 /*return*/, { kind: 'finished' }];
                        return [2 /*return*/, { kind: 'next', state: { t: newTime } }];
                }
            });
        });
    }
});
var AnimateUnitsExplode = PluginStateAnimation.create({
    name: 'built-in.animate-units-explode',
    display: { name: 'Explode Units' },
    params: function () { return ({
        durationInMs: param_definition["ParamDefinition"].Numeric(3000, { min: 100, max: 10000, step: 100 })
    }); },
    initialState: function () { return ({ t: 0 }); },
    setup: function (_, plugin) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var state, reprs, update, changed, _i, reprs_3, r, explodes;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                state = plugin.state.data;
                reprs = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure.Representation3D));
                update = state.build();
                changed = false;
                for (_i = 0, reprs_3 = reprs; _i < reprs_3.length; _i++) {
                    r = reprs_3[_i];
                    explodes = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.ExplodeStructureRepresentation3D, r.transform.ref));
                    if (explodes.length > 0)
                        continue;
                    changed = true;
                    update.to(r.transform.ref)
                        .apply(transforms["StateTransforms"].Representation.ExplodeStructureRepresentation3D, { t: 0 }, { tags: 'animate-units-explode' });
                }
                if (!changed)
                    return [2 /*return*/];
                return [2 /*return*/, update.commit({ doNotUpdateCurrent: true })];
            });
        });
    },
    teardown: function (_, plugin) {
        var state = plugin.state.data;
        var reprs = state.select(mol_state["StateSelection"].Generators.ofType(objects["a" /* PluginStateObject */].Molecule.Structure.Representation3DState)
            .withTag('animate-units-explode'));
        if (reprs.length === 0)
            return;
        var update = state.build();
        for (var _i = 0, reprs_4 = reprs; _i < reprs_4.length; _i++) {
            var r = reprs_4[_i];
            update.delete(r.transform.ref);
        }
        return update.commit();
    },
    apply: function (animState, t, ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var state, anims, update, d, newTime, _i, anims_2, m;
            return Object(tslib_es6["__generator"])(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        state = ctx.plugin.state.data;
                        anims = state.select(mol_state["StateSelection"].Generators.ofTransformer(transforms["StateTransforms"].Representation.ExplodeStructureRepresentation3D));
                        if (anims.length === 0) {
                            return [2 /*return*/, { kind: 'finished' }];
                        }
                        update = state.build();
                        d = (t.current - t.lastApplied) / ctx.params.durationInMs;
                        newTime = (animState.t + d) % 1;
                        for (_i = 0, anims_2 = anims; _i < anims_2.length; _i++) {
                            m = anims_2[_i];
                            update.to(m).update({ t: newTime });
                        }
                        return [4 /*yield*/, commands["PluginCommands"].State.Update(ctx.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _a.sent();
                        return [2 /*return*/, { kind: 'next', state: { t: newTime } }];
                }
            });
        });
    }
});
var AnimateStateInterpolation = PluginStateAnimation.create({
    name: 'built-in.animate-state-interpolation',
    display: { name: 'Animate State Interpolation' },
    params: function () { return ({
        transtionDurationInMs: param_definition["ParamDefinition"].Numeric(2000, { min: 100, max: 30000, step: 10 })
    }); },
    canApply: function (plugin) {
        return { canApply: plugin.managers.snapshot.state.entries.size > 1 };
    },
    initialState: function () { return ({}); },
    apply: function (animState, t, ctx) {
        return Object(tslib_es6["__awaiter"])(this, void 0, void 0, function () {
            var snapshots, currentT, srcIndex, tarIndex, _src, _tar, src, tar, state, update, _i, src_1, s, _a, tar_1, t_1, e, f;
            return Object(tslib_es6["__generator"])(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        snapshots = ctx.plugin.managers.snapshot.state.entries;
                        if (snapshots.size < 2)
                            return [2 /*return*/, { kind: 'finished' }];
                        currentT = (t.current % ctx.params.transtionDurationInMs) / ctx.params.transtionDurationInMs;
                        srcIndex = Math.floor(t.current / ctx.params.transtionDurationInMs) % snapshots.size;
                        tarIndex = Math.ceil(t.current / ctx.params.transtionDurationInMs);
                        if (tarIndex === srcIndex)
                            tarIndex++;
                        tarIndex = tarIndex % snapshots.size;
                        _src = snapshots.get(srcIndex).snapshot, _tar = snapshots.get(tarIndex).snapshot;
                        if (!_src.data || !_tar.data)
                            return [2 /*return*/, { kind: 'skip' }];
                        src = _src.data.tree.transforms, tar = _tar.data.tree.transforms;
                        state = ctx.plugin.state.data;
                        update = state.build();
                        for (_i = 0, src_1 = src; _i < src_1.length; _i++) {
                            s = src_1[_i];
                            for (_a = 0, tar_1 = tar; _a < tar_1.length; _a++) {
                                t_1 = tar_1[_a];
                                if (t_1.ref !== s.ref)
                                    continue;
                                if (t_1.version === s.version)
                                    continue;
                                e = mol_state["StateTransform"].fromJSON(s), f = mol_state["StateTransform"].fromJSON(t_1);
                                if (!e.transformer.definition.interpolate) {
                                    update.to(s.ref).update(currentT <= 0.5 ? e.params : f.params);
                                }
                                else {
                                    update.to(s.ref).update(e.transformer.definition.interpolate(e.params, f.params, currentT, ctx.plugin));
                                }
                            }
                        }
                        return [4 /*yield*/, commands["PluginCommands"].State.Update(ctx.plugin, { state: state, tree: update, options: { doNotLogTiming: true } })];
                    case 1:
                        _b.sent();
                        return [2 /*return*/, { kind: 'next', state: {} }];
                }
            });
        });
    }
});
//# sourceMappingURL=built-in.js.map

/***/ })
/******/ ]);
